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"
53 #include <sys/eventfd.h>
58 #include <sys/types.h>
61 #ifdef HAVE_SYS_TIME_H
63 #endif /* HAVE_SYS_TIME_H */
66 #endif /* HAVE_UNISTD_H */
73 #endif /* G_OS_WIN32 */
76 #include <sys/socket.h>
78 #endif /* G_OS_BEOS */
83 #include "giochannel.h"
87 #include "gstrfuncs.h"
88 #include "gtestutils.h"
89 #include "gthreadprivate.h"
95 #ifdef G_MAIN_POLL_DEBUG
101 * @title: The Main Event Loop
102 * @short_description: manages all available sources of events
104 * The main event loop manages all the available sources of events for
105 * GLib and GTK+ applications. These events can come from any number of
106 * different types of sources such as file descriptors (plain files,
107 * pipes or sockets) and timeouts. New types of event sources can also
108 * be added using g_source_attach().
110 * To allow multiple independent sets of sources to be handled in
111 * different threads, each source is associated with a #GMainContext.
112 * A GMainContext can only be running in a single thread, but
113 * sources can be added to it and removed from it from other threads.
115 * Each event source is assigned a priority. The default priority,
116 * #G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
117 * Values greater than 0 denote lower priorities. Events from high priority
118 * sources are always processed before events from lower priority sources.
120 * Idle functions can also be added, and assigned a priority. These will
121 * be run whenever no events with a higher priority are ready to be processed.
123 * The #GMainLoop data type represents a main event loop. A GMainLoop is
124 * created with g_main_loop_new(). After adding the initial event sources,
125 * g_main_loop_run() is called. This continuously checks for new events from
126 * each of the event sources and dispatches them. Finally, the processing of
127 * an event from one of the sources leads to a call to g_main_loop_quit() to
128 * exit the main loop, and g_main_loop_run() returns.
130 * It is possible to create new instances of #GMainLoop recursively.
131 * This is often used in GTK+ applications when showing modal dialog
132 * boxes. Note that event sources are associated with a particular
133 * #GMainContext, and will be checked and dispatched for all main
134 * loops associated with that GMainContext.
136 * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
137 * gtk_main_quit() and gtk_events_pending().
139 * <refsect2><title>Creating new source types</title>
140 * <para>One of the unusual features of the #GMainLoop functionality
141 * is that new types of event source can be created and used in
142 * addition to the builtin type of event source. A new event source
143 * type is used for handling GDK events. A new source type is created
144 * by <firstterm>deriving</firstterm> from the #GSource structure.
145 * The derived type of source is represented by a structure that has
146 * the #GSource structure as a first element, and other elements specific
147 * to the new source type. To create an instance of the new source type,
148 * call g_source_new() passing in the size of the derived structure and
149 * a table of functions. These #GSourceFuncs determine the behavior of
150 * the new source type.</para>
151 * <para>New source types basically interact with the main context
152 * in two ways. Their prepare function in #GSourceFuncs can set a timeout
153 * to determine the maximum amount of time that the main loop will sleep
154 * before checking the source again. In addition, or as well, the source
155 * can add file descriptors to the set that the main context checks using
156 * g_source_add_poll().</para>
158 * <refsect2><title>Customizing the main loop iteration</title>
159 * <para>Single iterations of a #GMainContext can be run with
160 * g_main_context_iteration(). In some cases, more detailed control
161 * of exactly how the details of the main loop work is desired, for
162 * instance, when integrating the #GMainLoop with an external main loop.
163 * In such cases, you can call the component functions of
164 * g_main_context_iteration() directly. These functions are
165 * g_main_context_prepare(), g_main_context_query(),
166 * g_main_context_check() and g_main_context_dispatch().</para>
167 * <para>The operation of these functions can best be seen in terms
168 * of a state diagram, as shown in <xref linkend="mainloop-states"/>.</para>
169 * <figure id="mainloop-states"><title>States of a Main Context</title>
170 * <graphic fileref="mainloop-states.gif" format="GIF"></graphic>
177 typedef struct _GTimeoutSource GTimeoutSource;
178 typedef struct _GChildWatchSource GChildWatchSource;
179 typedef struct _GUnixSignalWatchSource GUnixSignalWatchSource;
180 typedef struct _GPollRec GPollRec;
181 typedef struct _GSourceCallback GSourceCallback;
185 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
186 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
189 #ifdef G_THREADS_ENABLED
190 typedef struct _GMainWaiter GMainWaiter;
199 typedef struct _GMainDispatch GMainDispatch;
201 struct _GMainDispatch
204 GSList *dispatching_sources; /* stack of current sources */
207 #ifdef G_MAIN_POLL_DEBUG
208 gboolean _g_main_poll_debug = FALSE;
213 #ifdef G_THREADS_ENABLED
214 /* The following lock is used for both the list of sources
215 * and the list of poll records
226 GPtrArray *pending_dispatches;
227 gint timeout; /* Timeout for current iteration */
230 GSource *source_list;
231 gint in_check_or_prepare;
233 GPollRec *poll_records, *poll_records_tail;
234 guint n_poll_records;
235 GPollFD *cached_poll_array;
236 guint cached_poll_array_size;
238 #ifdef G_THREADS_ENABLED
240 /* this pipe is used to wake up the main loop when a source is added.
242 gint wake_up_pipe[2];
243 #else /* G_OS_WIN32 */
244 HANDLE wake_up_semaphore;
245 #endif /* G_OS_WIN32 */
248 gboolean poll_waiting;
250 /* Flag indicating whether the set of fd's changed during a poll */
251 gboolean poll_changed;
252 #endif /* G_THREADS_ENABLED */
257 gboolean time_is_fresh;
259 gboolean real_time_is_fresh;
262 struct _GSourceCallback
267 GDestroyNotify notify;
272 GMainContext *context;
277 struct _GTimeoutSource
285 struct _GChildWatchSource
292 #else /* G_OS_WIN32 */
294 gboolean child_exited;
295 #endif /* G_OS_WIN32 */
298 struct _GUnixSignalWatchSource
313 struct _GSourcePrivate
315 GSList *child_sources;
316 GSource *parent_source;
319 #ifdef G_THREADS_ENABLED
320 #define LOCK_CONTEXT(context) g_static_mutex_lock (&context->mutex)
321 #define UNLOCK_CONTEXT(context) g_static_mutex_unlock (&context->mutex)
322 #define G_THREAD_SELF g_thread_self ()
324 #define LOCK_CONTEXT(context) (void)0
325 #define UNLOCK_CONTEXT(context) (void)0
326 #define G_THREAD_SELF NULL
329 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
330 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
331 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
333 #define SOURCE_UNREF(source, context) \
335 if ((source)->ref_count > 1) \
336 (source)->ref_count--; \
338 g_source_unref_internal ((source), (context), TRUE); \
342 /* Forward declarations */
344 static void g_source_unref_internal (GSource *source,
345 GMainContext *context,
347 static void g_source_destroy_internal (GSource *source,
348 GMainContext *context,
350 static void g_source_set_priority_unlocked (GSource *source,
351 GMainContext *context,
353 static void g_main_context_poll (GMainContext *context,
358 static void g_main_context_add_poll_unlocked (GMainContext *context,
361 static void g_main_context_remove_poll_unlocked (GMainContext *context,
363 static void g_main_context_wakeup_unlocked (GMainContext *context);
365 static void _g_main_wake_up_all_contexts (void);
367 static gboolean g_timeout_prepare (GSource *source,
369 static gboolean g_timeout_check (GSource *source);
370 static gboolean g_timeout_dispatch (GSource *source,
371 GSourceFunc callback,
373 static gboolean g_child_watch_prepare (GSource *source,
375 static gboolean g_child_watch_check (GSource *source);
376 static gboolean g_child_watch_dispatch (GSource *source,
377 GSourceFunc callback,
380 static gpointer unix_signal_helper_thread (gpointer data) G_GNUC_NORETURN;
381 static void g_unix_signal_handler (int signum);
382 static gboolean g_unix_signal_watch_prepare (GSource *source,
384 static gboolean g_unix_signal_watch_check (GSource *source);
385 static gboolean g_unix_signal_watch_dispatch (GSource *source,
386 GSourceFunc callback,
388 static void g_unix_signal_watch_finalize (GSource *source);
390 static gboolean g_idle_prepare (GSource *source,
392 static gboolean g_idle_check (GSource *source);
393 static gboolean g_idle_dispatch (GSource *source,
394 GSourceFunc callback,
397 G_LOCK_DEFINE_STATIC (main_loop);
398 static GMainContext *default_main_context;
399 static GSList *main_contexts_without_pipe = NULL;
405 guint checked_eventfd : 1;
406 guint have_eventfd : 1;
408 EventFdState event_fd_state = { 0, 0 };
411 /* The UNIX signal pipe contains a single byte specifying which
412 * signal was received.
414 #define _UNIX_SIGNAL_PIPE_SIGCHLD_CHAR 'C'
415 #define _UNIX_SIGNAL_PIPE_SIGHUP_CHAR 'H'
416 #define _UNIX_SIGNAL_PIPE_SIGINT_CHAR 'I'
417 #define _UNIX_SIGNAL_PIPE_SIGTERM_CHAR 'T'
418 /* Guards all the data below */
419 G_LOCK_DEFINE_STATIC (unix_signal_lock);
421 UNIX_SIGNAL_UNINITIALIZED = 0,
422 UNIX_SIGNAL_INITIALIZED_SINGLE,
423 UNIX_SIGNAL_INITIALIZED_THREADED
425 static gint unix_signal_init_state = UNIX_SIGNAL_UNINITIALIZED;
427 /* These are only used in the UNIX_SIGNAL_INITIALIZED_SINGLE case */
428 gboolean sighup_delivered : 1;
429 gboolean sigint_delivered : 1;
430 gboolean sigterm_delivered : 1;
432 static sigset_t unix_signal_mask;
433 static UnixSignalState unix_signal_state;
434 static gint unix_signal_wake_up_pipe[2];
435 GSList *unix_signal_watches;
437 /* Not guarded ( FIXME should it be? ) */
438 static gint child_watch_count = 1;
440 static GSourceFuncs g_unix_signal_funcs =
442 g_unix_signal_watch_prepare,
443 g_unix_signal_watch_check,
444 g_unix_signal_watch_dispatch,
445 g_unix_signal_watch_finalize
447 #endif /* !G_OS_WIN32 */
448 G_LOCK_DEFINE_STATIC (main_context_list);
449 static GSList *main_context_list = NULL;
451 GSourceFuncs g_timeout_funcs =
459 GSourceFuncs g_child_watch_funcs =
461 g_child_watch_prepare,
463 g_child_watch_dispatch,
467 GSourceFuncs g_idle_funcs =
476 * g_main_context_ref:
477 * @context: a #GMainContext
479 * Increases the reference count on a #GMainContext object by one.
481 * Returns: the @context that was passed in (since 2.6)
484 g_main_context_ref (GMainContext *context)
486 g_return_val_if_fail (context != NULL, NULL);
487 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
489 g_atomic_int_inc (&context->ref_count);
495 poll_rec_list_free (GMainContext *context,
498 g_slice_free_chain (GPollRec, list, next);
502 * g_main_context_unref:
503 * @context: a #GMainContext
505 * Decreases the reference count on a #GMainContext object by one. If
506 * the result is zero, free the context and free all associated memory.
509 g_main_context_unref (GMainContext *context)
512 g_return_if_fail (context != NULL);
513 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
515 if (!g_atomic_int_dec_and_test (&context->ref_count))
518 G_LOCK (main_context_list);
519 main_context_list = g_slist_remove (main_context_list, context);
520 G_UNLOCK (main_context_list);
522 source = context->source_list;
525 GSource *next = source->next;
526 g_source_destroy_internal (source, context, FALSE);
530 #ifdef G_THREADS_ENABLED
531 g_static_mutex_free (&context->mutex);
534 g_ptr_array_free (context->pending_dispatches, TRUE);
535 g_free (context->cached_poll_array);
537 poll_rec_list_free (context, context->poll_records);
539 #ifdef G_THREADS_ENABLED
540 if (g_thread_supported())
543 if (context->wake_up_pipe[0] != -1)
544 close (context->wake_up_pipe[0]);
545 if (context->wake_up_pipe[1] != -1)
546 close (context->wake_up_pipe[1]);
548 CloseHandle (context->wake_up_semaphore);
552 main_contexts_without_pipe = g_slist_remove (main_contexts_without_pipe,
555 if (context->cond != NULL)
556 g_cond_free (context->cond);
562 #ifdef G_THREADS_ENABLED
564 g_main_context_init_pipe (GMainContext *context)
566 GError *error = NULL;
569 if (context->wake_up_pipe[0] != -1)
573 if (!event_fd_state.checked_eventfd
574 || event_fd_state.have_eventfd)
578 event_fd_state.checked_eventfd = TRUE;
579 efd = eventfd (0, EFD_CLOEXEC);
580 if (efd == -1 && errno == ENOSYS)
582 event_fd_state.have_eventfd = FALSE;
583 if (!g_unix_open_pipe (context->wake_up_pipe, FD_CLOEXEC, &error))
584 g_error ("Cannot create pipe main loop wake-up: %s", error->message);
588 event_fd_state.have_eventfd = TRUE;
589 context->wake_up_pipe[0] = efd;
592 g_error ("Cannot create eventfd for main loop wake-up: %s", g_strerror (errno));
595 if (!g_unix_open_pipe (context->wake_up_pipe, FD_CLOEXEC, &error))
596 g_error ("Cannot create pipe main loop wake-up: %s", error->message);
599 context->wake_up_rec.fd = context->wake_up_pipe[0];
600 context->wake_up_rec.events = G_IO_IN;
602 if (context->wake_up_semaphore != NULL)
604 context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
605 if (context->wake_up_semaphore == NULL)
606 g_error ("Cannot create wake-up semaphore: %s",
607 g_win32_error_message (GetLastError ()));
608 context->wake_up_rec.fd = (gintptr) context->wake_up_semaphore;
609 context->wake_up_rec.events = G_IO_IN;
611 if (_g_main_poll_debug)
612 g_print ("wake-up semaphore: %p\n", context->wake_up_semaphore);
614 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
618 _g_main_thread_init (void)
622 curr = main_contexts_without_pipe;
625 g_main_context_init_pipe ((GMainContext *)curr->data);
628 g_slist_free (main_contexts_without_pipe);
629 main_contexts_without_pipe = NULL;
631 #endif /* G_THREADS_ENABLED */
634 * g_main_context_new:
636 * Creates a new #GMainContext structure.
638 * Return value: the new #GMainContext
641 g_main_context_new (void)
643 GMainContext *context = g_new0 (GMainContext, 1);
645 #ifdef G_MAIN_POLL_DEBUG
647 static gboolean beenhere = FALSE;
651 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
652 _g_main_poll_debug = TRUE;
658 #ifdef G_THREADS_ENABLED
659 g_static_mutex_init (&context->mutex);
661 context->owner = NULL;
662 context->waiters = NULL;
665 context->wake_up_pipe[0] = -1;
666 context->wake_up_pipe[1] = -1;
668 context->wake_up_semaphore = NULL;
672 context->ref_count = 1;
674 context->next_id = 1;
676 context->source_list = NULL;
678 context->poll_func = g_poll;
680 context->cached_poll_array = NULL;
681 context->cached_poll_array_size = 0;
683 context->pending_dispatches = g_ptr_array_new ();
685 context->time_is_fresh = FALSE;
686 context->real_time_is_fresh = FALSE;
688 #ifdef G_THREADS_ENABLED
689 if (g_thread_supported ())
690 g_main_context_init_pipe (context);
692 main_contexts_without_pipe = g_slist_prepend (main_contexts_without_pipe,
696 G_LOCK (main_context_list);
697 main_context_list = g_slist_append (main_context_list, context);
699 #ifdef G_MAIN_POLL_DEBUG
700 if (_g_main_poll_debug)
701 g_print ("created context=%p\n", context);
704 G_UNLOCK (main_context_list);
710 * g_main_context_default:
712 * Returns the global default main context. This is the main context
713 * used for main loop functions when a main loop is not explicitly
714 * specified, and corresponds to the "main" main loop. See also
715 * g_main_context_get_thread_default().
717 * Return value: the global default main context.
720 g_main_context_default (void)
726 if (!default_main_context)
728 default_main_context = g_main_context_new ();
729 #ifdef G_MAIN_POLL_DEBUG
730 if (_g_main_poll_debug)
731 g_print ("default context=%p\n", default_main_context);
735 G_UNLOCK (main_loop);
737 return default_main_context;
740 static GStaticPrivate thread_context_stack = G_STATIC_PRIVATE_INIT;
743 free_context_stack (gpointer data)
745 GQueue *stack = data;
746 GMainContext *context;
748 while (!g_queue_is_empty (stack))
750 context = g_queue_pop_head (stack);
751 g_main_context_release (context);
753 g_main_context_unref (context);
755 g_queue_free (stack);
759 * g_main_context_push_thread_default:
760 * @context: a #GMainContext, or %NULL for the global default context
762 * Acquires @context and sets it as the thread-default context for the
763 * current thread. This will cause certain asynchronous operations
764 * (such as most <link linkend="gio">gio</link>-based I/O) which are
765 * started in this thread to run under @context and deliver their
766 * results to its main loop, rather than running under the global
767 * default context in the main thread. Note that calling this function
768 * changes the context returned by
769 * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
770 * one returned by g_main_context_default(), so it does not affect the
771 * context used by functions like g_idle_add().
773 * Normally you would call this function shortly after creating a new
774 * thread, passing it a #GMainContext which will be run by a
775 * #GMainLoop in that thread, to set a new default context for all
776 * async operations in that thread. (In this case, you don't need to
777 * ever call g_main_context_pop_thread_default().) In some cases
778 * however, you may want to schedule a single operation in a
779 * non-default context, or temporarily use a non-default context in
780 * the main thread. In that case, you can wrap the call to the
781 * asynchronous operation inside a
782 * g_main_context_push_thread_default() /
783 * g_main_context_pop_thread_default() pair, but it is up to you to
784 * ensure that no other asynchronous operations accidentally get
785 * started while the non-default context is active.
787 * Beware that libraries that predate this function may not correctly
788 * handle being used from a thread with a thread-default context. Eg,
789 * see g_file_supports_thread_contexts().
794 g_main_context_push_thread_default (GMainContext *context)
797 gboolean acquired_context;
799 acquired_context = g_main_context_acquire (context);
800 g_return_if_fail (acquired_context);
802 if (context == g_main_context_default ())
805 g_main_context_ref (context);
807 stack = g_static_private_get (&thread_context_stack);
810 stack = g_queue_new ();
811 g_static_private_set (&thread_context_stack, stack,
815 g_queue_push_head (stack, context);
819 * g_main_context_pop_thread_default:
820 * @context: a #GMainContext object, or %NULL
822 * Pops @context off the thread-default context stack (verifying that
823 * it was on the top of the stack).
828 g_main_context_pop_thread_default (GMainContext *context)
832 if (context == g_main_context_default ())
835 stack = g_static_private_get (&thread_context_stack);
837 g_return_if_fail (stack != NULL);
838 g_return_if_fail (g_queue_peek_head (stack) == context);
840 g_queue_pop_head (stack);
842 g_main_context_release (context);
844 g_main_context_unref (context);
848 * g_main_context_get_thread_default:
850 * Gets the thread-default #GMainContext for this thread. Asynchronous
851 * operations that want to be able to be run in contexts other than
852 * the default one should call this method to get a #GMainContext to
853 * add their #GSource<!-- -->s to. (Note that even in single-threaded
854 * programs applications may sometimes want to temporarily push a
855 * non-default context, so it is not safe to assume that this will
856 * always return %NULL if threads are not initialized.)
858 * Returns: the thread-default #GMainContext, or %NULL if the
859 * thread-default context is the global default context.
864 g_main_context_get_thread_default (void)
868 stack = g_static_private_get (&thread_context_stack);
870 return g_queue_peek_head (stack);
875 /* Hooks for adding to the main loop */
879 * @source_funcs: structure containing functions that implement
880 * the sources behavior.
881 * @struct_size: size of the #GSource structure to create.
883 * Creates a new #GSource structure. The size is specified to
884 * allow creating structures derived from #GSource that contain
885 * additional data. The size passed in must be at least
886 * <literal>sizeof (GSource)</literal>.
888 * The source will not initially be associated with any #GMainContext
889 * and must be added to one with g_source_attach() before it will be
892 * Return value: the newly-created #GSource.
895 g_source_new (GSourceFuncs *source_funcs,
900 g_return_val_if_fail (source_funcs != NULL, NULL);
901 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
903 source = (GSource*) g_malloc0 (struct_size);
905 source->source_funcs = source_funcs;
906 source->ref_count = 1;
908 source->priority = G_PRIORITY_DEFAULT;
910 source->flags = G_HOOK_FLAG_ACTIVE;
912 /* NULL/0 initialization for all other fields */
917 /* Holds context's lock
920 g_source_list_add (GSource *source,
921 GMainContext *context)
923 GSource *tmp_source, *last_source;
925 if (source->priv && source->priv->parent_source)
927 /* Put the source immediately before its parent */
928 tmp_source = source->priv->parent_source;
929 last_source = source->priv->parent_source->prev;
934 tmp_source = context->source_list;
935 while (tmp_source && tmp_source->priority <= source->priority)
937 last_source = tmp_source;
938 tmp_source = tmp_source->next;
942 source->next = tmp_source;
944 tmp_source->prev = source;
946 source->prev = last_source;
948 last_source->next = source;
950 context->source_list = source;
953 /* Holds context's lock
956 g_source_list_remove (GSource *source,
957 GMainContext *context)
960 source->prev->next = source->next;
962 context->source_list = source->next;
965 source->next->prev = source->prev;
972 g_source_attach_unlocked (GSource *source,
973 GMainContext *context)
978 source->context = context;
979 result = source->source_id = context->next_id++;
982 g_source_list_add (source, context);
984 tmp_list = source->poll_fds;
987 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
988 tmp_list = tmp_list->next;
993 tmp_list = source->priv->child_sources;
996 g_source_attach_unlocked (tmp_list->data, context);
997 tmp_list = tmp_list->next;
1006 * @source: a #GSource
1007 * @context: a #GMainContext (if %NULL, the default context will be used)
1009 * Adds a #GSource to a @context so that it will be executed within
1010 * that context. Remove it by calling g_source_destroy().
1012 * Return value: the ID (greater than 0) for the source within the
1016 g_source_attach (GSource *source,
1017 GMainContext *context)
1021 g_return_val_if_fail (source->context == NULL, 0);
1022 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
1025 context = g_main_context_default ();
1027 LOCK_CONTEXT (context);
1029 result = g_source_attach_unlocked (source, context);
1031 #ifdef G_THREADS_ENABLED
1032 /* Now wake up the main loop if it is waiting in the poll() */
1033 g_main_context_wakeup_unlocked (context);
1036 UNLOCK_CONTEXT (context);
1042 g_source_destroy_internal (GSource *source,
1043 GMainContext *context,
1047 LOCK_CONTEXT (context);
1049 if (!SOURCE_DESTROYED (source))
1052 gpointer old_cb_data;
1053 GSourceCallbackFuncs *old_cb_funcs;
1055 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1057 old_cb_data = source->callback_data;
1058 old_cb_funcs = source->callback_funcs;
1060 source->callback_data = NULL;
1061 source->callback_funcs = NULL;
1065 UNLOCK_CONTEXT (context);
1066 old_cb_funcs->unref (old_cb_data);
1067 LOCK_CONTEXT (context);
1070 if (!SOURCE_BLOCKED (source))
1072 tmp_list = source->poll_fds;
1075 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1076 tmp_list = tmp_list->next;
1080 if (source->priv && source->priv->child_sources)
1082 /* This is safe because even if a child_source finalizer or
1083 * closure notify tried to modify source->priv->child_sources
1084 * from outside the lock, it would fail since
1085 * SOURCE_DESTROYED(source) is now TRUE.
1087 tmp_list = source->priv->child_sources;
1090 g_source_destroy_internal (tmp_list->data, context, TRUE);
1091 g_source_unref_internal (tmp_list->data, context, TRUE);
1092 tmp_list = tmp_list->next;
1094 g_slist_free (source->priv->child_sources);
1095 source->priv->child_sources = NULL;
1098 g_source_unref_internal (source, context, TRUE);
1102 UNLOCK_CONTEXT (context);
1107 * @source: a #GSource
1109 * Removes a source from its #GMainContext, if any, and mark it as
1110 * destroyed. The source cannot be subsequently added to another
1114 g_source_destroy (GSource *source)
1116 GMainContext *context;
1118 g_return_if_fail (source != NULL);
1120 context = source->context;
1123 g_source_destroy_internal (source, context, FALSE);
1125 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1130 * @source: a #GSource
1132 * Returns the numeric ID for a particular source. The ID of a source
1133 * is a positive integer which is unique within a particular main loop
1134 * context. The reverse
1135 * mapping from ID to source is done by g_main_context_find_source_by_id().
1137 * Return value: the ID (greater than 0) for the source
1140 g_source_get_id (GSource *source)
1144 g_return_val_if_fail (source != NULL, 0);
1145 g_return_val_if_fail (source->context != NULL, 0);
1147 LOCK_CONTEXT (source->context);
1148 result = source->source_id;
1149 UNLOCK_CONTEXT (source->context);
1155 * g_source_get_context:
1156 * @source: a #GSource
1158 * Gets the #GMainContext with which the source is associated.
1159 * Calling this function on a destroyed source is an error.
1161 * Return value: the #GMainContext with which the source is associated,
1162 * or %NULL if the context has not yet been added
1166 g_source_get_context (GSource *source)
1168 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1170 return source->context;
1174 * g_source_add_poll:
1175 * @source:a #GSource
1176 * @fd: a #GPollFD structure holding information about a file
1177 * descriptor to watch.
1179 * Adds a file descriptor to the set of file descriptors polled for
1180 * this source. This is usually combined with g_source_new() to add an
1181 * event source. The event source's check function will typically test
1182 * the @revents field in the #GPollFD struct and return %TRUE if events need
1186 g_source_add_poll (GSource *source,
1189 GMainContext *context;
1191 g_return_if_fail (source != NULL);
1192 g_return_if_fail (fd != NULL);
1193 g_return_if_fail (!SOURCE_DESTROYED (source));
1195 context = source->context;
1198 LOCK_CONTEXT (context);
1200 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1204 if (!SOURCE_BLOCKED (source))
1205 g_main_context_add_poll_unlocked (context, source->priority, fd);
1206 UNLOCK_CONTEXT (context);
1211 * g_source_remove_poll:
1212 * @source:a #GSource
1213 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1215 * Removes a file descriptor from the set of file descriptors polled for
1219 g_source_remove_poll (GSource *source,
1222 GMainContext *context;
1224 g_return_if_fail (source != NULL);
1225 g_return_if_fail (fd != NULL);
1226 g_return_if_fail (!SOURCE_DESTROYED (source));
1228 context = source->context;
1231 LOCK_CONTEXT (context);
1233 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1237 if (!SOURCE_BLOCKED (source))
1238 g_main_context_remove_poll_unlocked (context, fd);
1239 UNLOCK_CONTEXT (context);
1244 * g_source_add_child_source:
1245 * @source:a #GSource
1246 * @child_source: a second #GSource that @source should "poll"
1248 * Adds @child_source to @source as a "polled" source; when @source is
1249 * added to a #GMainContext, @child_source will be automatically added
1250 * with the same priority, when @child_source is triggered, it will
1251 * cause @source to dispatch (in addition to calling its own
1252 * callback), and when @source is destroyed, it will destroy
1253 * @child_source as well. (@source will also still be dispatched if
1254 * its own prepare/check functions indicate that it is ready.)
1256 * If you don't need @child_source to do anything on its own when it
1257 * triggers, you can call g_source_set_dummy_callback() on it to set a
1258 * callback that does nothing (except return %TRUE if appropriate).
1260 * @source will hold a reference on @child_source while @child_source
1261 * is attached to it.
1266 g_source_add_child_source (GSource *source,
1267 GSource *child_source)
1269 GMainContext *context;
1271 g_return_if_fail (source != NULL);
1272 g_return_if_fail (child_source != NULL);
1273 g_return_if_fail (!SOURCE_DESTROYED (source));
1274 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1275 g_return_if_fail (child_source->context == NULL);
1276 g_return_if_fail (child_source->priv == NULL || child_source->priv->parent_source == NULL);
1278 context = source->context;
1281 LOCK_CONTEXT (context);
1284 source->priv = g_slice_new0 (GSourcePrivate);
1285 if (!child_source->priv)
1286 child_source->priv = g_slice_new0 (GSourcePrivate);
1288 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1289 g_source_ref (child_source));
1290 child_source->priv->parent_source = source;
1291 g_source_set_priority_unlocked (child_source, context, source->priority);
1295 UNLOCK_CONTEXT (context);
1296 g_source_attach (child_source, context);
1301 * g_source_remove_child_source:
1302 * @source:a #GSource
1303 * @child_source: a #GSource previously passed to
1304 * g_source_add_child_source().
1306 * Detaches @child_source from @source and destroys it.
1311 g_source_remove_child_source (GSource *source,
1312 GSource *child_source)
1314 GMainContext *context;
1316 g_return_if_fail (source != NULL);
1317 g_return_if_fail (child_source != NULL);
1318 g_return_if_fail (child_source->priv != NULL && child_source->priv->parent_source == source);
1319 g_return_if_fail (!SOURCE_DESTROYED (source));
1320 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1322 context = source->context;
1325 LOCK_CONTEXT (context);
1327 source->priv->child_sources = g_slist_remove (source->priv->child_sources, child_source);
1328 g_source_destroy_internal (child_source, context, TRUE);
1329 g_source_unref_internal (child_source, context, TRUE);
1332 UNLOCK_CONTEXT (context);
1336 * g_source_set_callback_indirect:
1337 * @source: the source
1338 * @callback_data: pointer to callback data "object"
1339 * @callback_funcs: functions for reference counting @callback_data
1340 * and getting the callback and data
1342 * Sets the callback function storing the data as a refcounted callback
1343 * "object". This is used internally. Note that calling
1344 * g_source_set_callback_indirect() assumes
1345 * an initial reference count on @callback_data, and thus
1346 * @callback_funcs->unref will eventually be called once more
1347 * than @callback_funcs->ref.
1350 g_source_set_callback_indirect (GSource *source,
1351 gpointer callback_data,
1352 GSourceCallbackFuncs *callback_funcs)
1354 GMainContext *context;
1355 gpointer old_cb_data;
1356 GSourceCallbackFuncs *old_cb_funcs;
1358 g_return_if_fail (source != NULL);
1359 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1361 context = source->context;
1364 LOCK_CONTEXT (context);
1366 old_cb_data = source->callback_data;
1367 old_cb_funcs = source->callback_funcs;
1369 source->callback_data = callback_data;
1370 source->callback_funcs = callback_funcs;
1373 UNLOCK_CONTEXT (context);
1376 old_cb_funcs->unref (old_cb_data);
1380 g_source_callback_ref (gpointer cb_data)
1382 GSourceCallback *callback = cb_data;
1384 callback->ref_count++;
1389 g_source_callback_unref (gpointer cb_data)
1391 GSourceCallback *callback = cb_data;
1393 callback->ref_count--;
1394 if (callback->ref_count == 0)
1396 if (callback->notify)
1397 callback->notify (callback->data);
1403 g_source_callback_get (gpointer cb_data,
1408 GSourceCallback *callback = cb_data;
1410 *func = callback->func;
1411 *data = callback->data;
1414 static GSourceCallbackFuncs g_source_callback_funcs = {
1415 g_source_callback_ref,
1416 g_source_callback_unref,
1417 g_source_callback_get,
1421 * g_source_set_callback:
1422 * @source: the source
1423 * @func: a callback function
1424 * @data: the data to pass to callback function
1425 * @notify: a function to call when @data is no longer in use, or %NULL.
1427 * Sets the callback function for a source. The callback for a source is
1428 * called from the source's dispatch function.
1430 * The exact type of @func depends on the type of source; ie. you
1431 * should not count on @func being called with @data as its first
1434 * Typically, you won't use this function. Instead use functions specific
1435 * to the type of source you are using.
1438 g_source_set_callback (GSource *source,
1441 GDestroyNotify notify)
1443 GSourceCallback *new_callback;
1445 g_return_if_fail (source != NULL);
1447 new_callback = g_new (GSourceCallback, 1);
1449 new_callback->ref_count = 1;
1450 new_callback->func = func;
1451 new_callback->data = data;
1452 new_callback->notify = notify;
1454 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1459 * g_source_set_funcs:
1460 * @source: a #GSource
1461 * @funcs: the new #GSourceFuncs
1463 * Sets the source functions (can be used to override
1464 * default implementations) of an unattached source.
1469 g_source_set_funcs (GSource *source,
1470 GSourceFuncs *funcs)
1472 g_return_if_fail (source != NULL);
1473 g_return_if_fail (source->context == NULL);
1474 g_return_if_fail (source->ref_count > 0);
1475 g_return_if_fail (funcs != NULL);
1477 source->source_funcs = funcs;
1481 g_source_set_priority_unlocked (GSource *source,
1482 GMainContext *context,
1487 source->priority = priority;
1491 /* Remove the source from the context's source and then
1492 * add it back so it is sorted in the correct place
1494 g_source_list_remove (source, source->context);
1495 g_source_list_add (source, source->context);
1497 if (!SOURCE_BLOCKED (source))
1499 tmp_list = source->poll_fds;
1502 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1503 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1505 tmp_list = tmp_list->next;
1510 if (source->priv && source->priv->child_sources)
1512 tmp_list = source->priv->child_sources;
1515 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1516 tmp_list = tmp_list->next;
1522 * g_source_set_priority:
1523 * @source: a #GSource
1524 * @priority: the new priority.
1526 * Sets the priority of a source. While the main loop is being run, a
1527 * source will be dispatched if it is ready to be dispatched and no
1528 * sources at a higher (numerically smaller) priority are ready to be
1532 g_source_set_priority (GSource *source,
1535 GMainContext *context;
1537 g_return_if_fail (source != NULL);
1539 context = source->context;
1542 LOCK_CONTEXT (context);
1543 g_source_set_priority_unlocked (source, context, priority);
1545 UNLOCK_CONTEXT (source->context);
1549 * g_source_get_priority:
1550 * @source: a #GSource
1552 * Gets the priority of a source.
1554 * Return value: the priority of the source
1557 g_source_get_priority (GSource *source)
1559 g_return_val_if_fail (source != NULL, 0);
1561 return source->priority;
1565 * g_source_set_can_recurse:
1566 * @source: a #GSource
1567 * @can_recurse: whether recursion is allowed for this source
1569 * Sets whether a source can be called recursively. If @can_recurse is
1570 * %TRUE, then while the source is being dispatched then this source
1571 * will be processed normally. Otherwise, all processing of this
1572 * source is blocked until the dispatch function returns.
1575 g_source_set_can_recurse (GSource *source,
1576 gboolean can_recurse)
1578 GMainContext *context;
1580 g_return_if_fail (source != NULL);
1582 context = source->context;
1585 LOCK_CONTEXT (context);
1588 source->flags |= G_SOURCE_CAN_RECURSE;
1590 source->flags &= ~G_SOURCE_CAN_RECURSE;
1593 UNLOCK_CONTEXT (context);
1597 * g_source_get_can_recurse:
1598 * @source: a #GSource
1600 * Checks whether a source is allowed to be called recursively.
1601 * see g_source_set_can_recurse().
1603 * Return value: whether recursion is allowed.
1606 g_source_get_can_recurse (GSource *source)
1608 g_return_val_if_fail (source != NULL, FALSE);
1610 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1615 * g_source_set_name:
1616 * @source: a #GSource
1617 * @name: debug name for the source
1619 * Sets a name for the source, used in debugging and profiling.
1620 * The name defaults to #NULL.
1622 * The source name should describe in a human-readable way
1623 * what the source does. For example, "X11 event queue"
1624 * or "GTK+ repaint idle handler" or whatever it is.
1626 * It is permitted to call this function multiple times, but is not
1627 * recommended due to the potential performance impact. For example,
1628 * one could change the name in the "check" function of a #GSourceFuncs
1629 * to include details like the event type in the source name.
1634 g_source_set_name (GSource *source,
1637 g_return_if_fail (source != NULL);
1639 /* setting back to NULL is allowed, just because it's
1640 * weird if get_name can return NULL but you can't
1644 g_free (source->name);
1645 source->name = g_strdup (name);
1649 * g_source_get_name:
1650 * @source: a #GSource
1652 * Gets a name for the source, used in debugging and profiling.
1653 * The name may be #NULL if it has never been set with
1654 * g_source_set_name().
1656 * Return value: the name of the source
1660 g_source_get_name (GSource *source)
1662 g_return_val_if_fail (source != NULL, NULL);
1664 return source->name;
1668 * g_source_set_name_by_id:
1669 * @tag: a #GSource ID
1670 * @name: debug name for the source
1672 * Sets the name of a source using its ID.
1674 * This is a convenience utility to set source names from the return
1675 * value of g_idle_add(), g_timeout_add(), etc.
1680 g_source_set_name_by_id (guint tag,
1685 g_return_if_fail (tag > 0);
1687 source = g_main_context_find_source_by_id (NULL, tag);
1691 g_source_set_name (source, name);
1697 * @source: a #GSource
1699 * Increases the reference count on a source by one.
1701 * Return value: @source
1704 g_source_ref (GSource *source)
1706 GMainContext *context;
1708 g_return_val_if_fail (source != NULL, NULL);
1710 context = source->context;
1713 LOCK_CONTEXT (context);
1715 source->ref_count++;
1718 UNLOCK_CONTEXT (context);
1723 /* g_source_unref() but possible to call within context lock
1726 g_source_unref_internal (GSource *source,
1727 GMainContext *context,
1730 gpointer old_cb_data = NULL;
1731 GSourceCallbackFuncs *old_cb_funcs = NULL;
1733 g_return_if_fail (source != NULL);
1735 if (!have_lock && context)
1736 LOCK_CONTEXT (context);
1738 source->ref_count--;
1739 if (source->ref_count == 0)
1741 old_cb_data = source->callback_data;
1742 old_cb_funcs = source->callback_funcs;
1744 source->callback_data = NULL;
1745 source->callback_funcs = NULL;
1749 if (!SOURCE_DESTROYED (source))
1750 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
1751 g_source_list_remove (source, context);
1754 if (source->source_funcs->finalize)
1757 UNLOCK_CONTEXT (context);
1758 source->source_funcs->finalize (source);
1760 LOCK_CONTEXT (context);
1763 g_free (source->name);
1764 source->name = NULL;
1766 g_slist_free (source->poll_fds);
1767 source->poll_fds = NULL;
1771 g_slice_free (GSourcePrivate, source->priv);
1772 source->priv = NULL;
1778 if (!have_lock && context)
1779 UNLOCK_CONTEXT (context);
1784 UNLOCK_CONTEXT (context);
1786 old_cb_funcs->unref (old_cb_data);
1789 LOCK_CONTEXT (context);
1795 * @source: a #GSource
1797 * Decreases the reference count of a source by one. If the
1798 * resulting reference count is zero the source and associated
1799 * memory will be destroyed.
1802 g_source_unref (GSource *source)
1804 g_return_if_fail (source != NULL);
1806 g_source_unref_internal (source, source->context, FALSE);
1810 * g_main_context_find_source_by_id:
1811 * @context: a #GMainContext (if %NULL, the default context will be used)
1812 * @source_id: the source ID, as returned by g_source_get_id().
1814 * Finds a #GSource given a pair of context and ID.
1816 * Return value: the #GSource if found, otherwise, %NULL
1819 g_main_context_find_source_by_id (GMainContext *context,
1824 g_return_val_if_fail (source_id > 0, NULL);
1826 if (context == NULL)
1827 context = g_main_context_default ();
1829 LOCK_CONTEXT (context);
1831 source = context->source_list;
1834 if (!SOURCE_DESTROYED (source) &&
1835 source->source_id == source_id)
1837 source = source->next;
1840 UNLOCK_CONTEXT (context);
1846 * g_main_context_find_source_by_funcs_user_data:
1847 * @context: a #GMainContext (if %NULL, the default context will be used).
1848 * @funcs: the @source_funcs passed to g_source_new().
1849 * @user_data: the user data from the callback.
1851 * Finds a source with the given source functions and user data. If
1852 * multiple sources exist with the same source function and user data,
1853 * the first one found will be returned.
1855 * Return value: the source, if one was found, otherwise %NULL
1858 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1859 GSourceFuncs *funcs,
1864 g_return_val_if_fail (funcs != NULL, NULL);
1866 if (context == NULL)
1867 context = g_main_context_default ();
1869 LOCK_CONTEXT (context);
1871 source = context->source_list;
1874 if (!SOURCE_DESTROYED (source) &&
1875 source->source_funcs == funcs &&
1876 source->callback_funcs)
1878 GSourceFunc callback;
1879 gpointer callback_data;
1881 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1883 if (callback_data == user_data)
1886 source = source->next;
1889 UNLOCK_CONTEXT (context);
1895 * g_main_context_find_source_by_user_data:
1896 * @context: a #GMainContext
1897 * @user_data: the user_data for the callback.
1899 * Finds a source with the given user data for the callback. If
1900 * multiple sources exist with the same user data, the first
1901 * one found will be returned.
1903 * Return value: the source, if one was found, otherwise %NULL
1906 g_main_context_find_source_by_user_data (GMainContext *context,
1911 if (context == NULL)
1912 context = g_main_context_default ();
1914 LOCK_CONTEXT (context);
1916 source = context->source_list;
1919 if (!SOURCE_DESTROYED (source) &&
1920 source->callback_funcs)
1922 GSourceFunc callback;
1923 gpointer callback_data = NULL;
1925 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1927 if (callback_data == user_data)
1930 source = source->next;
1933 UNLOCK_CONTEXT (context);
1940 * @tag: the ID of the source to remove.
1942 * Removes the source with the given id from the default main context.
1944 * a #GSource is given by g_source_get_id(), or will be returned by the
1945 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1946 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1947 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1949 * See also g_source_destroy(). You must use g_source_destroy() for sources
1950 * added to a non-default main context.
1952 * Return value: %TRUE if the source was found and removed.
1955 g_source_remove (guint tag)
1959 g_return_val_if_fail (tag > 0, FALSE);
1961 source = g_main_context_find_source_by_id (NULL, tag);
1963 g_source_destroy (source);
1965 return source != NULL;
1969 * g_source_remove_by_user_data:
1970 * @user_data: the user_data for the callback.
1972 * Removes a source from the default main loop context given the user
1973 * data for the callback. If multiple sources exist with the same user
1974 * data, only one will be destroyed.
1976 * Return value: %TRUE if a source was found and removed.
1979 g_source_remove_by_user_data (gpointer user_data)
1983 source = g_main_context_find_source_by_user_data (NULL, user_data);
1986 g_source_destroy (source);
1994 * g_source_remove_by_funcs_user_data:
1995 * @funcs: The @source_funcs passed to g_source_new()
1996 * @user_data: the user data for the callback
1998 * Removes a source from the default main loop context given the
1999 * source functions and user data. If multiple sources exist with the
2000 * same source functions and user data, only one will be destroyed.
2002 * Return value: %TRUE if a source was found and removed.
2005 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
2010 g_return_val_if_fail (funcs != NULL, FALSE);
2012 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
2015 g_source_destroy (source);
2023 * g_get_current_time:
2024 * @result: #GTimeVal structure in which to store current time.
2026 * Equivalent to the UNIX gettimeofday() function, but portable.
2028 * You may find g_get_real_time() to be more convenient.
2031 g_get_current_time (GTimeVal *result)
2036 g_return_if_fail (result != NULL);
2038 /*this is required on alpha, there the timeval structs are int's
2039 not longs and a cast only would fail horribly*/
2040 gettimeofday (&r, NULL);
2041 result->tv_sec = r.tv_sec;
2042 result->tv_usec = r.tv_usec;
2047 g_return_if_fail (result != NULL);
2049 GetSystemTimeAsFileTime (&ft);
2050 memmove (&time64, &ft, sizeof (FILETIME));
2052 /* Convert from 100s of nanoseconds since 1601-01-01
2053 * to Unix epoch. Yes, this is Y2038 unsafe.
2055 time64 -= G_GINT64_CONSTANT (116444736000000000);
2058 result->tv_sec = time64 / 1000000;
2059 result->tv_usec = time64 % 1000000;
2066 * Queries the system wall-clock time.
2068 * This call is functionally equivalent to g_get_current_time() except
2069 * that the return value is often more convenient than dealing with a
2072 * You should only use this call if you are actually interested in the real
2073 * wall-clock time. g_get_monotonic_time() is probably more useful for
2074 * measuring intervals.
2076 * Returns: the number of microseconds since January 1, 1970 UTC.
2081 g_get_real_time (void)
2085 g_get_current_time (&tv);
2087 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2091 * g_get_monotonic_time:
2093 * Queries the system monotonic time, if available.
2095 * On POSIX systems with clock_gettime() and %CLOCK_MONOTONIC this call
2096 * is a very shallow wrapper for that. Otherwise, we make a best effort
2097 * that probably involves returning the wall clock time (with at least
2098 * microsecond accuracy, subject to the limitations of the OS kernel).
2100 * Note that, on Windows, "limitations of the OS kernel" is a rather
2101 * substantial statement. Depending on the configuration of the system,
2102 * the wall clock time is updated as infrequently as 64 times a second
2103 * (which is approximately every 16ms).
2105 * Returns: the monotonic time, in microseconds
2110 g_get_monotonic_time (void)
2112 #ifdef HAVE_CLOCK_GETTIME
2113 /* librt clock_gettime() is our first choice */
2115 static int clockid = CLOCK_REALTIME;
2118 #ifdef HAVE_MONOTONIC_CLOCK
2119 /* We have to check if we actually have monotonic clock support.
2121 * There is no thread safety issue here since there is no harm if we
2125 static gboolean checked;
2127 if G_UNLIKELY (!checked)
2129 if (sysconf (_SC_MONOTONIC_CLOCK) >= 0)
2130 clockid = CLOCK_MONOTONIC;
2136 clock_gettime (clockid, &ts);
2138 /* In theory monotonic time can have any epoch.
2140 * glib presently assumes the following:
2142 * 1) The epoch comes some time after the birth of Jesus of Nazareth, but
2143 * not more than 10000 years later.
2145 * 2) The current time also falls sometime within this range.
2147 * These two reasonable assumptions leave us with a maximum deviation from
2148 * the epoch of 10000 years, or 315569520000000000 seconds.
2150 * If we restrict ourselves to this range then the number of microseconds
2151 * will always fit well inside the constraints of a int64 (by a factor of
2154 * If you actually hit the following assertion, probably you should file a
2155 * bug against your operating system for being excessively silly.
2157 g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts.tv_sec &&
2158 ts.tv_sec < G_GINT64_CONSTANT (315569520000000000));
2160 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2163 /* It may look like we are discarding accuracy on Windows (since its
2164 * current time is expressed in 100s of nanoseconds) but according to
2165 * many sources, the time is only updated 64 times per second, so
2166 * microsecond accuracy is more than enough.
2171 g_get_current_time (&tv);
2173 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2179 g_main_dispatch_free (gpointer dispatch)
2181 g_slice_free (GMainDispatch, dispatch);
2184 /* Running the main loop */
2186 static GMainDispatch *
2189 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
2190 GMainDispatch *dispatch = g_static_private_get (&depth_private);
2193 dispatch = g_slice_new0 (GMainDispatch);
2194 g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
2203 * Returns the depth of the stack of calls to
2204 * g_main_context_dispatch() on any #GMainContext in the current thread.
2205 * That is, when called from the toplevel, it gives 0. When
2206 * called from within a callback from g_main_context_iteration()
2207 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2208 * a callback to a recursive call to g_main_context_iteration(),
2209 * it returns 2. And so forth.
2211 * This function is useful in a situation like the following:
2212 * Imagine an extremely simple "garbage collected" system.
2215 * static GList *free_list;
2218 * allocate_memory (gsize size)
2220 * gpointer result = g_malloc (size);
2221 * free_list = g_list_prepend (free_list, result);
2226 * free_allocated_memory (void)
2229 * for (l = free_list; l; l = l->next);
2231 * g_list_free (free_list);
2239 * g_main_context_iteration (NULL, TRUE);
2240 * free_allocated_memory();
2244 * This works from an application, however, if you want to do the same
2245 * thing from a library, it gets more difficult, since you no longer
2246 * control the main loop. You might think you can simply use an idle
2247 * function to make the call to free_allocated_memory(), but that
2248 * doesn't work, since the idle function could be called from a
2249 * recursive callback. This can be fixed by using g_main_depth()
2253 * allocate_memory (gsize size)
2255 * FreeListBlock *block = g_new (FreeListBlock, 1);
2256 * block->mem = g_malloc (size);
2257 * block->depth = g_main_depth ();
2258 * free_list = g_list_prepend (free_list, block);
2259 * return block->mem;
2263 * free_allocated_memory (void)
2267 * int depth = g_main_depth ();
2268 * for (l = free_list; l; );
2270 * GList *next = l->next;
2271 * FreeListBlock *block = l->data;
2272 * if (block->depth > depth)
2274 * g_free (block->mem);
2276 * free_list = g_list_delete_link (free_list, l);
2284 * There is a temptation to use g_main_depth() to solve
2285 * problems with reentrancy. For instance, while waiting for data
2286 * to be received from the network in response to a menu item,
2287 * the menu item might be selected again. It might seem that
2288 * one could make the menu item's callback return immediately
2289 * and do nothing if g_main_depth() returns a value greater than 1.
2290 * However, this should be avoided since the user then sees selecting
2291 * the menu item do nothing. Furthermore, you'll find yourself adding
2292 * these checks all over your code, since there are doubtless many,
2293 * many things that the user could do. Instead, you can use the
2294 * following techniques:
2299 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
2300 * the user from interacting with elements while the main
2301 * loop is recursing.
2306 * Avoid main loop recursion in situations where you can't handle
2307 * arbitrary callbacks. Instead, structure your code so that you
2308 * simply return to the main loop and then get called again when
2309 * there is more work to do.
2314 * Return value: The main loop recursion level in the current thread
2319 GMainDispatch *dispatch = get_dispatch ();
2320 return dispatch->depth;
2324 * g_main_current_source:
2326 * Returns the currently firing source for this thread.
2328 * Return value: The currently firing source or %NULL.
2333 g_main_current_source (void)
2335 GMainDispatch *dispatch = get_dispatch ();
2336 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
2340 * g_source_is_destroyed:
2341 * @source: a #GSource
2343 * Returns whether @source has been destroyed.
2345 * This is important when you operate upon your objects
2346 * from within idle handlers, but may have freed the object
2347 * before the dispatch of your idle handler.
2351 * idle_callback (gpointer data)
2353 * SomeWidget *self = data;
2355 * GDK_THREADS_ENTER (<!-- -->);
2356 * /<!-- -->* do stuff with self *<!-- -->/
2357 * self->idle_id = 0;
2358 * GDK_THREADS_LEAVE (<!-- -->);
2364 * some_widget_do_stuff_later (SomeWidget *self)
2366 * self->idle_id = g_idle_add (idle_callback, self);
2370 * some_widget_finalize (GObject *object)
2372 * SomeWidget *self = SOME_WIDGET (object);
2374 * if (self->idle_id)
2375 * g_source_remove (self->idle_id);
2377 * G_OBJECT_CLASS (parent_class)->finalize (object);
2381 * This will fail in a multi-threaded application if the
2382 * widget is destroyed before the idle handler fires due
2383 * to the use after free in the callback. A solution, to
2384 * this particular problem, is to check to if the source
2385 * has already been destroy within the callback.
2389 * idle_callback (gpointer data)
2391 * SomeWidget *self = data;
2393 * GDK_THREADS_ENTER ();
2394 * if (!g_source_is_destroyed (g_main_current_source ()))
2396 * /<!-- -->* do stuff with self *<!-- -->/
2398 * GDK_THREADS_LEAVE ();
2404 * Return value: %TRUE if the source has been destroyed
2409 g_source_is_destroyed (GSource *source)
2411 return SOURCE_DESTROYED (source);
2414 /* Temporarily remove all this source's file descriptors from the
2415 * poll(), so that if data comes available for one of the file descriptors
2416 * we don't continually spin in the poll()
2418 /* HOLDS: source->context's lock */
2420 block_source (GSource *source)
2424 g_return_if_fail (!SOURCE_BLOCKED (source));
2426 tmp_list = source->poll_fds;
2429 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2430 tmp_list = tmp_list->next;
2434 /* HOLDS: source->context's lock */
2436 unblock_source (GSource *source)
2440 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
2441 g_return_if_fail (!SOURCE_DESTROYED (source));
2443 tmp_list = source->poll_fds;
2446 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2447 tmp_list = tmp_list->next;
2451 /* HOLDS: context's lock */
2453 g_main_dispatch (GMainContext *context)
2455 GMainDispatch *current = get_dispatch ();
2458 for (i = 0; i < context->pending_dispatches->len; i++)
2460 GSource *source = context->pending_dispatches->pdata[i];
2462 context->pending_dispatches->pdata[i] = NULL;
2465 source->flags &= ~G_SOURCE_READY;
2467 if (!SOURCE_DESTROYED (source))
2469 gboolean was_in_call;
2470 gpointer user_data = NULL;
2471 GSourceFunc callback = NULL;
2472 GSourceCallbackFuncs *cb_funcs;
2474 gboolean need_destroy;
2476 gboolean (*dispatch) (GSource *,
2479 GSList current_source_link;
2481 dispatch = source->source_funcs->dispatch;
2482 cb_funcs = source->callback_funcs;
2483 cb_data = source->callback_data;
2486 cb_funcs->ref (cb_data);
2488 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2489 block_source (source);
2491 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2492 source->flags |= G_HOOK_FLAG_IN_CALL;
2495 cb_funcs->get (cb_data, source, &callback, &user_data);
2497 UNLOCK_CONTEXT (context);
2500 /* The on-stack allocation of the GSList is unconventional, but
2501 * we know that the lifetime of the link is bounded to this
2502 * function as the link is kept in a thread specific list and
2503 * not manipulated outside of this function and its descendants.
2504 * Avoiding the overhead of a g_slist_alloc() is useful as many
2505 * applications do little more than dispatch events.
2507 * This is a performance hack - do not revert to g_slist_prepend()!
2509 current_source_link.data = source;
2510 current_source_link.next = current->dispatching_sources;
2511 current->dispatching_sources = ¤t_source_link;
2512 need_destroy = ! dispatch (source,
2515 g_assert (current->dispatching_sources == ¤t_source_link);
2516 current->dispatching_sources = current_source_link.next;
2520 cb_funcs->unref (cb_data);
2522 LOCK_CONTEXT (context);
2525 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2527 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2528 !SOURCE_DESTROYED (source))
2529 unblock_source (source);
2531 /* Note: this depends on the fact that we can't switch
2532 * sources from one main context to another
2534 if (need_destroy && !SOURCE_DESTROYED (source))
2536 g_assert (source->context == context);
2537 g_source_destroy_internal (source, context, TRUE);
2541 SOURCE_UNREF (source, context);
2544 g_ptr_array_set_size (context->pending_dispatches, 0);
2547 /* Holds context's lock */
2548 static inline GSource *
2549 next_valid_source (GMainContext *context,
2552 GSource *new_source = source ? source->next : context->source_list;
2556 if (!SOURCE_DESTROYED (new_source))
2558 new_source->ref_count++;
2562 new_source = new_source->next;
2566 SOURCE_UNREF (source, context);
2572 * g_main_context_acquire:
2573 * @context: a #GMainContext
2575 * Tries to become the owner of the specified context.
2576 * If some other thread is the owner of the context,
2577 * returns %FALSE immediately. Ownership is properly
2578 * recursive: the owner can require ownership again
2579 * and will release ownership when g_main_context_release()
2580 * is called as many times as g_main_context_acquire().
2582 * You must be the owner of a context before you
2583 * can call g_main_context_prepare(), g_main_context_query(),
2584 * g_main_context_check(), g_main_context_dispatch().
2586 * Return value: %TRUE if the operation succeeded, and
2587 * this thread is now the owner of @context.
2590 g_main_context_acquire (GMainContext *context)
2592 #ifdef G_THREADS_ENABLED
2593 gboolean result = FALSE;
2594 GThread *self = G_THREAD_SELF;
2596 if (context == NULL)
2597 context = g_main_context_default ();
2599 LOCK_CONTEXT (context);
2601 if (!context->owner)
2603 context->owner = self;
2604 g_assert (context->owner_count == 0);
2607 if (context->owner == self)
2609 context->owner_count++;
2613 UNLOCK_CONTEXT (context);
2616 #else /* !G_THREADS_ENABLED */
2618 #endif /* G_THREADS_ENABLED */
2622 * g_main_context_release:
2623 * @context: a #GMainContext
2625 * Releases ownership of a context previously acquired by this thread
2626 * with g_main_context_acquire(). If the context was acquired multiple
2627 * times, the ownership will be released only when g_main_context_release()
2628 * is called as many times as it was acquired.
2631 g_main_context_release (GMainContext *context)
2633 #ifdef G_THREADS_ENABLED
2634 if (context == NULL)
2635 context = g_main_context_default ();
2637 LOCK_CONTEXT (context);
2639 context->owner_count--;
2640 if (context->owner_count == 0)
2642 context->owner = NULL;
2644 if (context->waiters)
2646 GMainWaiter *waiter = context->waiters->data;
2647 gboolean loop_internal_waiter =
2648 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
2649 context->waiters = g_slist_delete_link (context->waiters,
2651 if (!loop_internal_waiter)
2652 g_mutex_lock (waiter->mutex);
2654 g_cond_signal (waiter->cond);
2656 if (!loop_internal_waiter)
2657 g_mutex_unlock (waiter->mutex);
2661 UNLOCK_CONTEXT (context);
2662 #endif /* G_THREADS_ENABLED */
2666 * g_main_context_wait:
2667 * @context: a #GMainContext
2668 * @cond: a condition variable
2669 * @mutex: a mutex, currently held
2671 * Tries to become the owner of the specified context,
2672 * as with g_main_context_acquire(). But if another thread
2673 * is the owner, atomically drop @mutex and wait on @cond until
2674 * that owner releases ownership or until @cond is signaled, then
2675 * try again (once) to become the owner.
2677 * Return value: %TRUE if the operation succeeded, and
2678 * this thread is now the owner of @context.
2681 g_main_context_wait (GMainContext *context,
2685 #ifdef G_THREADS_ENABLED
2686 gboolean result = FALSE;
2687 GThread *self = G_THREAD_SELF;
2688 gboolean loop_internal_waiter;
2690 if (context == NULL)
2691 context = g_main_context_default ();
2693 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2695 if (!loop_internal_waiter)
2696 LOCK_CONTEXT (context);
2698 if (context->owner && context->owner != self)
2703 waiter.mutex = mutex;
2705 context->waiters = g_slist_append (context->waiters, &waiter);
2707 if (!loop_internal_waiter)
2708 UNLOCK_CONTEXT (context);
2709 g_cond_wait (cond, mutex);
2710 if (!loop_internal_waiter)
2711 LOCK_CONTEXT (context);
2713 context->waiters = g_slist_remove (context->waiters, &waiter);
2716 if (!context->owner)
2718 context->owner = self;
2719 g_assert (context->owner_count == 0);
2722 if (context->owner == self)
2724 context->owner_count++;
2728 if (!loop_internal_waiter)
2729 UNLOCK_CONTEXT (context);
2732 #else /* !G_THREADS_ENABLED */
2734 #endif /* G_THREADS_ENABLED */
2738 * g_main_context_prepare:
2739 * @context: a #GMainContext
2740 * @priority: location to store priority of highest priority
2741 * source already ready.
2743 * Prepares to poll sources within a main loop. The resulting information
2744 * for polling is determined by calling g_main_context_query ().
2746 * Return value: %TRUE if some source is ready to be dispatched
2750 g_main_context_prepare (GMainContext *context,
2755 gint current_priority = G_MAXINT;
2758 if (context == NULL)
2759 context = g_main_context_default ();
2761 LOCK_CONTEXT (context);
2763 context->time_is_fresh = FALSE;
2764 context->real_time_is_fresh = FALSE;
2766 if (context->in_check_or_prepare)
2768 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2769 "prepare() member.");
2770 UNLOCK_CONTEXT (context);
2774 #ifdef G_THREADS_ENABLED
2775 if (context->poll_waiting)
2777 g_warning("g_main_context_prepare(): main loop already active in another thread");
2778 UNLOCK_CONTEXT (context);
2782 context->poll_waiting = TRUE;
2783 #endif /* G_THREADS_ENABLED */
2786 /* If recursing, finish up current dispatch, before starting over */
2787 if (context->pending_dispatches)
2790 g_main_dispatch (context, ¤t_time);
2792 UNLOCK_CONTEXT (context);
2797 /* If recursing, clear list of pending dispatches */
2799 for (i = 0; i < context->pending_dispatches->len; i++)
2801 if (context->pending_dispatches->pdata[i])
2802 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2804 g_ptr_array_set_size (context->pending_dispatches, 0);
2806 /* Prepare all sources */
2808 context->timeout = -1;
2810 source = next_valid_source (context, NULL);
2813 gint source_timeout = -1;
2815 if ((n_ready > 0) && (source->priority > current_priority))
2817 SOURCE_UNREF (source, context);
2820 if (SOURCE_BLOCKED (source))
2823 if (!(source->flags & G_SOURCE_READY))
2826 gboolean (*prepare) (GSource *source,
2829 prepare = source->source_funcs->prepare;
2830 context->in_check_or_prepare++;
2831 UNLOCK_CONTEXT (context);
2833 result = (*prepare) (source, &source_timeout);
2835 LOCK_CONTEXT (context);
2836 context->in_check_or_prepare--;
2840 GSource *ready_source = source;
2842 while (ready_source)
2844 ready_source->flags |= G_SOURCE_READY;
2845 ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2850 if (source->flags & G_SOURCE_READY)
2853 current_priority = source->priority;
2854 context->timeout = 0;
2857 if (source_timeout >= 0)
2859 if (context->timeout < 0)
2860 context->timeout = source_timeout;
2862 context->timeout = MIN (context->timeout, source_timeout);
2866 source = next_valid_source (context, source);
2869 UNLOCK_CONTEXT (context);
2872 *priority = current_priority;
2874 return (n_ready > 0);
2878 * g_main_context_query:
2879 * @context: a #GMainContext
2880 * @max_priority: maximum priority source to check
2881 * @timeout_: location to store timeout to be used in polling
2882 * @fds: location to store #GPollFD records that need to be polled.
2883 * @n_fds: length of @fds.
2885 * Determines information necessary to poll this main loop.
2887 * Return value: the number of records actually stored in @fds,
2888 * or, if more than @n_fds records need to be stored, the number
2889 * of records that need to be stored.
2892 g_main_context_query (GMainContext *context,
2901 LOCK_CONTEXT (context);
2903 pollrec = context->poll_records;
2905 while (pollrec && max_priority >= pollrec->priority)
2907 /* We need to include entries with fd->events == 0 in the array because
2908 * otherwise if the application changes fd->events behind our back and
2909 * makes it non-zero, we'll be out of sync when we check the fds[] array.
2910 * (Changing fd->events after adding an FD wasn't an anticipated use of
2911 * this API, but it occurs in practice.) */
2914 fds[n_poll].fd = pollrec->fd->fd;
2915 /* In direct contradiction to the Unix98 spec, IRIX runs into
2916 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2917 * flags in the events field of the pollfd while it should
2918 * just ignoring them. So we mask them out here.
2920 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2921 fds[n_poll].revents = 0;
2924 pollrec = pollrec->next;
2928 #ifdef G_THREADS_ENABLED
2929 context->poll_changed = FALSE;
2934 *timeout = context->timeout;
2937 context->time_is_fresh = FALSE;
2938 context->real_time_is_fresh = FALSE;
2942 UNLOCK_CONTEXT (context);
2948 * g_main_context_check:
2949 * @context: a #GMainContext
2950 * @max_priority: the maximum numerical priority of sources to check
2951 * @fds: array of #GPollFD's that was passed to the last call to
2952 * g_main_context_query()
2953 * @n_fds: return value of g_main_context_query()
2955 * Passes the results of polling back to the main loop.
2957 * Return value: %TRUE if some sources are ready to be dispatched.
2960 g_main_context_check (GMainContext *context,
2970 LOCK_CONTEXT (context);
2972 if (context->in_check_or_prepare)
2974 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2975 "prepare() member.");
2976 UNLOCK_CONTEXT (context);
2980 #ifdef G_THREADS_ENABLED
2981 if (!context->poll_waiting)
2985 if (event_fd_state.have_eventfd)
2988 read (context->wake_up_pipe[0], &buf, sizeof(guint64));
2994 read (context->wake_up_pipe[0], &a, 1);
2999 context->poll_waiting = FALSE;
3001 /* If the set of poll file descriptors changed, bail out
3002 * and let the main loop rerun
3004 if (context->poll_changed)
3006 UNLOCK_CONTEXT (context);
3009 #endif /* G_THREADS_ENABLED */
3011 pollrec = context->poll_records;
3015 if (pollrec->fd->events)
3016 pollrec->fd->revents = fds[i].revents;
3018 pollrec = pollrec->next;
3022 source = next_valid_source (context, NULL);
3025 if ((n_ready > 0) && (source->priority > max_priority))
3027 SOURCE_UNREF (source, context);
3030 if (SOURCE_BLOCKED (source))
3033 if (!(source->flags & G_SOURCE_READY))
3036 gboolean (*check) (GSource *source);
3038 check = source->source_funcs->check;
3040 context->in_check_or_prepare++;
3041 UNLOCK_CONTEXT (context);
3043 result = (*check) (source);
3045 LOCK_CONTEXT (context);
3046 context->in_check_or_prepare--;
3050 GSource *ready_source = source;
3052 while (ready_source)
3054 ready_source->flags |= G_SOURCE_READY;
3055 ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
3060 if (source->flags & G_SOURCE_READY)
3062 source->ref_count++;
3063 g_ptr_array_add (context->pending_dispatches, source);
3067 /* never dispatch sources with less priority than the first
3068 * one we choose to dispatch
3070 max_priority = source->priority;
3074 source = next_valid_source (context, source);
3077 UNLOCK_CONTEXT (context);
3083 * g_main_context_dispatch:
3084 * @context: a #GMainContext
3086 * Dispatches all pending sources.
3089 g_main_context_dispatch (GMainContext *context)
3091 LOCK_CONTEXT (context);
3093 if (context->pending_dispatches->len > 0)
3095 g_main_dispatch (context);
3098 UNLOCK_CONTEXT (context);
3101 /* HOLDS context lock */
3103 g_main_context_iterate (GMainContext *context,
3110 gboolean some_ready;
3111 gint nfds, allocated_nfds;
3112 GPollFD *fds = NULL;
3114 UNLOCK_CONTEXT (context);
3116 #ifdef G_THREADS_ENABLED
3117 if (!g_main_context_acquire (context))
3119 gboolean got_ownership;
3121 LOCK_CONTEXT (context);
3123 g_return_val_if_fail (g_thread_supported (), FALSE);
3129 context->cond = g_cond_new ();
3131 got_ownership = g_main_context_wait (context,
3133 g_static_mutex_get_mutex (&context->mutex));
3139 LOCK_CONTEXT (context);
3140 #endif /* G_THREADS_ENABLED */
3142 if (!context->cached_poll_array)
3144 context->cached_poll_array_size = context->n_poll_records;
3145 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
3148 allocated_nfds = context->cached_poll_array_size;
3149 fds = context->cached_poll_array;
3151 UNLOCK_CONTEXT (context);
3153 g_main_context_prepare (context, &max_priority);
3155 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
3156 allocated_nfds)) > allocated_nfds)
3158 LOCK_CONTEXT (context);
3160 context->cached_poll_array_size = allocated_nfds = nfds;
3161 context->cached_poll_array = fds = g_new (GPollFD, nfds);
3162 UNLOCK_CONTEXT (context);
3168 g_main_context_poll (context, timeout, max_priority, fds, nfds);
3170 some_ready = g_main_context_check (context, max_priority, fds, nfds);
3173 g_main_context_dispatch (context);
3175 #ifdef G_THREADS_ENABLED
3176 g_main_context_release (context);
3177 #endif /* G_THREADS_ENABLED */
3179 LOCK_CONTEXT (context);
3185 * g_main_context_pending:
3186 * @context: a #GMainContext (if %NULL, the default context will be used)
3188 * Checks if any sources have pending events for the given context.
3190 * Return value: %TRUE if events are pending.
3193 g_main_context_pending (GMainContext *context)
3198 context = g_main_context_default();
3200 LOCK_CONTEXT (context);
3201 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3202 UNLOCK_CONTEXT (context);
3208 * g_main_context_iteration:
3209 * @context: a #GMainContext (if %NULL, the default context will be used)
3210 * @may_block: whether the call may block.
3212 * Runs a single iteration for the given main loop. This involves
3213 * checking to see if any event sources are ready to be processed,
3214 * then if no events sources are ready and @may_block is %TRUE, waiting
3215 * for a source to become ready, then dispatching the highest priority
3216 * events sources that are ready. Otherwise, if @may_block is %FALSE
3217 * sources are not waited to become ready, only those highest priority
3218 * events sources will be dispatched (if any), that are ready at this
3219 * given moment without further waiting.
3221 * Note that even when @may_block is %TRUE, it is still possible for
3222 * g_main_context_iteration() to return %FALSE, since the the wait may
3223 * be interrupted for other reasons than an event source becoming ready.
3225 * Return value: %TRUE if events were dispatched.
3228 g_main_context_iteration (GMainContext *context, gboolean may_block)
3233 context = g_main_context_default();
3235 LOCK_CONTEXT (context);
3236 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3237 UNLOCK_CONTEXT (context);
3244 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
3245 * @is_running: set to %TRUE to indicate that the loop is running. This
3246 * is not very important since calling g_main_loop_run() will set this to
3249 * Creates a new #GMainLoop structure.
3251 * Return value: a new #GMainLoop.
3254 g_main_loop_new (GMainContext *context,
3255 gboolean is_running)
3260 context = g_main_context_default();
3262 g_main_context_ref (context);
3264 loop = g_new0 (GMainLoop, 1);
3265 loop->context = context;
3266 loop->is_running = is_running != FALSE;
3267 loop->ref_count = 1;
3274 * @loop: a #GMainLoop
3276 * Increases the reference count on a #GMainLoop object by one.
3278 * Return value: @loop
3281 g_main_loop_ref (GMainLoop *loop)
3283 g_return_val_if_fail (loop != NULL, NULL);
3284 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3286 g_atomic_int_inc (&loop->ref_count);
3292 * g_main_loop_unref:
3293 * @loop: a #GMainLoop
3295 * Decreases the reference count on a #GMainLoop object by one. If
3296 * the result is zero, free the loop and free all associated memory.
3299 g_main_loop_unref (GMainLoop *loop)
3301 g_return_if_fail (loop != NULL);
3302 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3304 if (!g_atomic_int_dec_and_test (&loop->ref_count))
3307 g_main_context_unref (loop->context);
3313 * @loop: a #GMainLoop
3315 * Runs a main loop until g_main_loop_quit() is called on the loop.
3316 * If this is called for the thread of the loop's #GMainContext,
3317 * it will process events from the loop, otherwise it will
3321 g_main_loop_run (GMainLoop *loop)
3323 GThread *self = G_THREAD_SELF;
3325 g_return_if_fail (loop != NULL);
3326 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3328 #ifdef G_THREADS_ENABLED
3329 if (!g_main_context_acquire (loop->context))
3331 gboolean got_ownership = FALSE;
3333 /* Another thread owns this context */
3334 if (!g_thread_supported ())
3336 g_warning ("g_main_loop_run() was called from second thread but "
3337 "g_thread_init() was never called.");
3341 LOCK_CONTEXT (loop->context);
3343 g_atomic_int_inc (&loop->ref_count);
3345 if (!loop->is_running)
3346 loop->is_running = TRUE;
3348 if (!loop->context->cond)
3349 loop->context->cond = g_cond_new ();
3351 while (loop->is_running && !got_ownership)
3352 got_ownership = g_main_context_wait (loop->context,
3353 loop->context->cond,
3354 g_static_mutex_get_mutex (&loop->context->mutex));
3356 if (!loop->is_running)
3358 UNLOCK_CONTEXT (loop->context);
3360 g_main_context_release (loop->context);
3361 g_main_loop_unref (loop);
3365 g_assert (got_ownership);
3368 LOCK_CONTEXT (loop->context);
3369 #endif /* G_THREADS_ENABLED */
3371 if (loop->context->in_check_or_prepare)
3373 g_warning ("g_main_loop_run(): called recursively from within a source's "
3374 "check() or prepare() member, iteration not possible.");
3378 g_atomic_int_inc (&loop->ref_count);
3379 loop->is_running = TRUE;
3380 while (loop->is_running)
3381 g_main_context_iterate (loop->context, TRUE, TRUE, self);
3383 UNLOCK_CONTEXT (loop->context);
3385 #ifdef G_THREADS_ENABLED
3386 g_main_context_release (loop->context);
3387 #endif /* G_THREADS_ENABLED */
3389 g_main_loop_unref (loop);
3394 * @loop: a #GMainLoop
3396 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3397 * for the loop will return.
3399 * Note that sources that have already been dispatched when
3400 * g_main_loop_quit() is called will still be executed.
3403 g_main_loop_quit (GMainLoop *loop)
3405 g_return_if_fail (loop != NULL);
3406 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3408 LOCK_CONTEXT (loop->context);
3409 loop->is_running = FALSE;
3410 g_main_context_wakeup_unlocked (loop->context);
3412 #ifdef G_THREADS_ENABLED
3413 if (loop->context->cond)
3414 g_cond_broadcast (loop->context->cond);
3415 #endif /* G_THREADS_ENABLED */
3417 UNLOCK_CONTEXT (loop->context);
3421 * g_main_loop_is_running:
3422 * @loop: a #GMainLoop.
3424 * Checks to see if the main loop is currently being run via g_main_loop_run().
3426 * Return value: %TRUE if the mainloop is currently being run.
3429 g_main_loop_is_running (GMainLoop *loop)
3431 g_return_val_if_fail (loop != NULL, FALSE);
3432 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3434 return loop->is_running;
3438 * g_main_loop_get_context:
3439 * @loop: a #GMainLoop.
3441 * Returns the #GMainContext of @loop.
3443 * Return value: the #GMainContext of @loop
3446 g_main_loop_get_context (GMainLoop *loop)
3448 g_return_val_if_fail (loop != NULL, NULL);
3449 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3451 return loop->context;
3454 /* HOLDS: context's lock */
3456 g_main_context_poll (GMainContext *context,
3462 #ifdef G_MAIN_POLL_DEBUG
3468 GPollFunc poll_func;
3470 if (n_fds || timeout != 0)
3472 #ifdef G_MAIN_POLL_DEBUG
3473 if (_g_main_poll_debug)
3475 g_print ("polling context=%p n=%d timeout=%d\n",
3476 context, n_fds, timeout);
3477 poll_timer = g_timer_new ();
3481 LOCK_CONTEXT (context);
3483 poll_func = context->poll_func;
3485 UNLOCK_CONTEXT (context);
3486 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3489 g_warning ("poll(2) failed due to: %s.",
3490 g_strerror (errno));
3492 /* If g_poll () returns -1, it has already called g_warning() */
3496 #ifdef G_MAIN_POLL_DEBUG
3497 if (_g_main_poll_debug)
3499 LOCK_CONTEXT (context);
3501 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3504 g_timer_elapsed (poll_timer, NULL));
3505 g_timer_destroy (poll_timer);
3506 pollrec = context->poll_records;
3508 while (pollrec != NULL)
3513 if (fds[i].fd == pollrec->fd->fd &&
3514 pollrec->fd->events &&
3517 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3518 if (fds[i].revents & G_IO_IN)
3520 if (fds[i].revents & G_IO_OUT)
3522 if (fds[i].revents & G_IO_PRI)
3524 if (fds[i].revents & G_IO_ERR)
3526 if (fds[i].revents & G_IO_HUP)
3528 if (fds[i].revents & G_IO_NVAL)
3534 pollrec = pollrec->next;
3538 UNLOCK_CONTEXT (context);
3541 } /* if (n_fds || timeout != 0) */
3545 * g_main_context_add_poll:
3546 * @context: a #GMainContext (or %NULL for the default context)
3547 * @fd: a #GPollFD structure holding information about a file
3548 * descriptor to watch.
3549 * @priority: the priority for this file descriptor which should be
3550 * the same as the priority used for g_source_attach() to ensure that the
3551 * file descriptor is polled whenever the results may be needed.
3553 * Adds a file descriptor to the set of file descriptors polled for
3554 * this context. This will very seldomly be used directly. Instead
3555 * a typical event source will use g_source_add_poll() instead.
3558 g_main_context_add_poll (GMainContext *context,
3563 context = g_main_context_default ();
3565 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3566 g_return_if_fail (fd);
3568 LOCK_CONTEXT (context);
3569 g_main_context_add_poll_unlocked (context, priority, fd);
3570 UNLOCK_CONTEXT (context);
3573 /* HOLDS: main_loop_lock */
3575 g_main_context_add_poll_unlocked (GMainContext *context,
3579 GPollRec *prevrec, *nextrec;
3580 GPollRec *newrec = g_slice_new (GPollRec);
3582 /* This file descriptor may be checked before we ever poll */
3585 newrec->priority = priority;
3587 prevrec = context->poll_records_tail;
3589 while (prevrec && priority < prevrec->priority)
3592 prevrec = prevrec->prev;
3596 prevrec->next = newrec;
3598 context->poll_records = newrec;
3600 newrec->prev = prevrec;
3601 newrec->next = nextrec;
3604 nextrec->prev = newrec;
3606 context->poll_records_tail = newrec;
3608 context->n_poll_records++;
3610 #ifdef G_THREADS_ENABLED
3611 context->poll_changed = TRUE;
3613 /* Now wake up the main loop if it is waiting in the poll() */
3614 g_main_context_wakeup_unlocked (context);
3619 * g_main_context_remove_poll:
3620 * @context:a #GMainContext
3621 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3623 * Removes file descriptor from the set of file descriptors to be
3624 * polled for a particular context.
3627 g_main_context_remove_poll (GMainContext *context,
3631 context = g_main_context_default ();
3633 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3634 g_return_if_fail (fd);
3636 LOCK_CONTEXT (context);
3637 g_main_context_remove_poll_unlocked (context, fd);
3638 UNLOCK_CONTEXT (context);
3642 g_main_context_remove_poll_unlocked (GMainContext *context,
3645 GPollRec *pollrec, *prevrec, *nextrec;
3648 pollrec = context->poll_records;
3652 nextrec = pollrec->next;
3653 if (pollrec->fd == fd)
3655 if (prevrec != NULL)
3656 prevrec->next = nextrec;
3658 context->poll_records = nextrec;
3660 if (nextrec != NULL)
3661 nextrec->prev = prevrec;
3663 context->poll_records_tail = prevrec;
3665 g_slice_free (GPollRec, pollrec);
3667 context->n_poll_records--;
3674 #ifdef G_THREADS_ENABLED
3675 context->poll_changed = TRUE;
3677 /* Now wake up the main loop if it is waiting in the poll() */
3678 g_main_context_wakeup_unlocked (context);
3683 * g_source_get_current_time:
3684 * @source: a #GSource
3685 * @timeval: #GTimeVal structure in which to store current time.
3687 * Gets the "current time" to be used when checking
3688 * this source. The advantage of calling this function over
3689 * calling g_get_current_time() directly is that when
3690 * checking multiple sources, GLib can cache a single value
3691 * instead of having to repeatedly get the system time.
3693 * Deprecated: 2.28: use g_source_get_time() instead
3696 g_source_get_current_time (GSource *source,
3699 GMainContext *context;
3701 g_return_if_fail (source->context != NULL);
3703 context = source->context;
3705 LOCK_CONTEXT (context);
3707 if (!context->real_time_is_fresh)
3709 context->real_time = g_get_real_time ();
3710 context->real_time_is_fresh = TRUE;
3713 timeval->tv_sec = context->real_time / 1000000;
3714 timeval->tv_usec = context->real_time % 1000000;
3716 UNLOCK_CONTEXT (context);
3720 * g_source_get_time:
3721 * @source: a #GSource
3723 * Gets the time to be used when checking this source. The advantage of
3724 * calling this function over calling g_get_monotonic_time() directly is
3725 * that when checking multiple sources, GLib can cache a single value
3726 * instead of having to repeatedly get the system monotonic time.
3728 * The time here is the system monotonic time, if available, or some
3729 * other reasonable alternative otherwise. See g_get_monotonic_time().
3731 * Returns: the monotonic time in microseconds
3736 g_source_get_time (GSource *source)
3738 GMainContext *context;
3741 g_return_val_if_fail (source->context != NULL, 0);
3743 context = source->context;
3745 LOCK_CONTEXT (context);
3747 if (!context->time_is_fresh)
3749 context->time = g_get_monotonic_time ();
3750 context->time_is_fresh = TRUE;
3753 result = context->time;
3755 UNLOCK_CONTEXT (context);
3761 * g_main_context_set_poll_func:
3762 * @context: a #GMainContext
3763 * @func: the function to call to poll all file descriptors
3765 * Sets the function to use to handle polling of file descriptors. It
3766 * will be used instead of the poll() system call
3767 * (or GLib's replacement function, which is used where
3768 * poll() isn't available).
3770 * This function could possibly be used to integrate the GLib event
3771 * loop with an external event loop.
3774 g_main_context_set_poll_func (GMainContext *context,
3778 context = g_main_context_default ();
3780 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3782 LOCK_CONTEXT (context);
3785 context->poll_func = func;
3787 context->poll_func = g_poll;
3789 UNLOCK_CONTEXT (context);
3793 * g_main_context_get_poll_func:
3794 * @context: a #GMainContext
3796 * Gets the poll function set by g_main_context_set_poll_func().
3798 * Return value: the poll function
3801 g_main_context_get_poll_func (GMainContext *context)
3806 context = g_main_context_default ();
3808 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3810 LOCK_CONTEXT (context);
3811 result = context->poll_func;
3812 UNLOCK_CONTEXT (context);
3818 _g_main_wake_up_all_contexts (void)
3822 /* We were woken up. Wake up all other contexts in all other threads */
3823 G_LOCK (main_context_list);
3824 for (list = main_context_list; list; list = list->next)
3826 GMainContext *context = list->data;
3828 LOCK_CONTEXT (context);
3829 g_main_context_wakeup_unlocked (context);
3830 UNLOCK_CONTEXT (context);
3832 G_UNLOCK (main_context_list);
3836 /* HOLDS: context's lock */
3837 /* Wake the main loop up from a poll() */
3839 g_main_context_wakeup_unlocked (GMainContext *context)
3841 #ifdef G_THREADS_ENABLED
3842 if (g_thread_supported() && context->poll_waiting)
3844 context->poll_waiting = FALSE;
3847 if (event_fd_state.have_eventfd)
3850 write (context->wake_up_pipe[0], &buf, sizeof(buf));
3854 write (context->wake_up_pipe[1], "A", 1);
3856 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
3863 * g_main_context_wakeup:
3864 * @context: a #GMainContext
3866 * If @context is currently waiting in a poll(), interrupt
3867 * the poll(), and continue the iteration process.
3870 g_main_context_wakeup (GMainContext *context)
3873 context = g_main_context_default ();
3875 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3877 LOCK_CONTEXT (context);
3878 g_main_context_wakeup_unlocked (context);
3879 UNLOCK_CONTEXT (context);
3883 * g_main_context_is_owner:
3884 * @context: a #GMainContext
3886 * Determines whether this thread holds the (recursive)
3887 * ownership of this #GMaincontext. This is useful to
3888 * know before waiting on another thread that may be
3889 * blocking to get ownership of @context.
3891 * Returns: %TRUE if current thread is owner of @context.
3896 g_main_context_is_owner (GMainContext *context)
3901 context = g_main_context_default ();
3903 #ifdef G_THREADS_ENABLED
3904 LOCK_CONTEXT (context);
3905 is_owner = context->owner == G_THREAD_SELF;
3906 UNLOCK_CONTEXT (context);
3917 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3918 gint64 current_time)
3920 timeout_source->expiration = current_time +
3921 (guint64) timeout_source->interval * 1000;
3923 if (timeout_source->seconds)
3926 static gint timer_perturb = -1;
3928 if (timer_perturb == -1)
3931 * we want a per machine/session unique 'random' value; try the dbus
3932 * address first, that has a UUID in it. If there is no dbus, use the
3933 * hostname for hashing.
3935 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3936 if (!session_bus_address)
3937 session_bus_address = g_getenv ("HOSTNAME");
3938 if (session_bus_address)
3939 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
3944 /* We want the microseconds part of the timeout to land on the
3945 * 'timer_perturb' mark, but we need to make sure we don't try to
3946 * set the timeout in the past. We do this by ensuring that we
3947 * always only *increase* the expiration time by adding a full
3948 * second in the case that the microsecond portion decreases.
3950 timeout_source->expiration -= timer_perturb;
3952 remainder = timeout_source->expiration % 1000000;
3953 if (remainder >= 1000000/4)
3954 timeout_source->expiration += 1000000;
3956 timeout_source->expiration -= remainder;
3957 timeout_source->expiration += timer_perturb;
3962 g_timeout_prepare (GSource *source,
3965 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3966 gint64 now = g_source_get_time (source);
3968 if (now < timeout_source->expiration)
3970 /* Round up to ensure that we don't try again too early */
3971 *timeout = (timeout_source->expiration - now + 999) / 1000;
3980 g_timeout_check (GSource *source)
3982 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3983 gint64 now = g_source_get_time (source);
3985 return timeout_source->expiration <= now;
3989 g_timeout_dispatch (GSource *source,
3990 GSourceFunc callback,
3993 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3998 g_warning ("Timeout source dispatched without callback\n"
3999 "You must call g_source_set_callback().");
4003 again = callback (user_data);
4006 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
4012 * g_timeout_source_new:
4013 * @interval: the timeout interval in milliseconds.
4015 * Creates a new timeout source.
4017 * The source will not initially be associated with any #GMainContext
4018 * and must be added to one with g_source_attach() before it will be
4021 * Return value: the newly-created timeout source
4024 g_timeout_source_new (guint interval)
4026 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4027 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4029 timeout_source->interval = interval;
4030 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4036 * g_timeout_source_new_seconds:
4037 * @interval: the timeout interval in seconds
4039 * Creates a new timeout source.
4041 * The source will not initially be associated with any #GMainContext
4042 * and must be added to one with g_source_attach() before it will be
4045 * The scheduling granularity/accuracy of this timeout source will be
4048 * Return value: the newly-created timeout source
4053 g_timeout_source_new_seconds (guint interval)
4055 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4056 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4058 timeout_source->interval = 1000 * interval;
4059 timeout_source->seconds = TRUE;
4061 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4068 * g_timeout_add_full:
4069 * @priority: the priority of the timeout source. Typically this will be in
4070 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4071 * @interval: the time between calls to the function, in milliseconds
4072 * (1/1000ths of a second)
4073 * @function: function to call
4074 * @data: data to pass to @function
4075 * @notify: function to call when the timeout is removed, or %NULL
4077 * Sets a function to be called at regular intervals, with the given
4078 * priority. The function is called repeatedly until it returns
4079 * %FALSE, at which point the timeout is automatically destroyed and
4080 * the function will not be called again. The @notify function is
4081 * called when the timeout is destroyed. The first call to the
4082 * function will be at the end of the first @interval.
4084 * Note that timeout functions may be delayed, due to the processing of other
4085 * event sources. Thus they should not be relied on for precise timing.
4086 * After each call to the timeout function, the time of the next
4087 * timeout is recalculated based on the current time and the given interval
4088 * (it does not try to 'catch up' time lost in delays).
4090 * This internally creates a main loop source using g_timeout_source_new()
4091 * and attaches it to the main loop context using g_source_attach(). You can
4092 * do these steps manually if you need greater control.
4094 * Return value: the ID (greater than 0) of the event source.
4095 * Rename to: g_timeout_add
4098 g_timeout_add_full (gint priority,
4100 GSourceFunc function,
4102 GDestroyNotify notify)
4107 g_return_val_if_fail (function != NULL, 0);
4109 source = g_timeout_source_new (interval);
4111 if (priority != G_PRIORITY_DEFAULT)
4112 g_source_set_priority (source, priority);
4114 g_source_set_callback (source, function, data, notify);
4115 id = g_source_attach (source, NULL);
4116 g_source_unref (source);
4123 * @interval: the time between calls to the function, in milliseconds
4124 * (1/1000ths of a second)
4125 * @function: function to call
4126 * @data: data to pass to @function
4128 * Sets a function to be called at regular intervals, with the default
4129 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
4130 * until it returns %FALSE, at which point the timeout is automatically
4131 * destroyed and the function will not be called again. The first call
4132 * to the function will be at the end of the first @interval.
4134 * Note that timeout functions may be delayed, due to the processing of other
4135 * event sources. Thus they should not be relied on for precise timing.
4136 * After each call to the timeout function, the time of the next
4137 * timeout is recalculated based on the current time and the given interval
4138 * (it does not try to 'catch up' time lost in delays).
4140 * If you want to have a timer in the "seconds" range and do not care
4141 * about the exact time of the first call of the timer, use the
4142 * g_timeout_add_seconds() function; this function allows for more
4143 * optimizations and more efficient system power usage.
4145 * This internally creates a main loop source using g_timeout_source_new()
4146 * and attaches it to the main loop context using g_source_attach(). You can
4147 * do these steps manually if you need greater control.
4149 * Return value: the ID (greater than 0) of the event source.
4152 g_timeout_add (guint32 interval,
4153 GSourceFunc function,
4156 return g_timeout_add_full (G_PRIORITY_DEFAULT,
4157 interval, function, data, NULL);
4161 * g_timeout_add_seconds_full:
4162 * @priority: the priority of the timeout source. Typically this will be in
4163 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4164 * @interval: the time between calls to the function, in seconds
4165 * @function: function to call
4166 * @data: data to pass to @function
4167 * @notify: function to call when the timeout is removed, or %NULL
4169 * Sets a function to be called at regular intervals, with @priority.
4170 * The function is called repeatedly until it returns %FALSE, at which
4171 * point the timeout is automatically destroyed and the function will
4172 * not be called again.
4174 * Unlike g_timeout_add(), this function operates at whole second granularity.
4175 * The initial starting point of the timer is determined by the implementation
4176 * and the implementation is expected to group multiple timers together so that
4177 * they fire all at the same time.
4178 * To allow this grouping, the @interval to the first timer is rounded
4179 * and can deviate up to one second from the specified interval.
4180 * Subsequent timer iterations will generally run at the specified interval.
4182 * Note that timeout functions may be delayed, due to the processing of other
4183 * event sources. Thus they should not be relied on for precise timing.
4184 * After each call to the timeout function, the time of the next
4185 * timeout is recalculated based on the current time and the given @interval
4187 * If you want timing more precise than whole seconds, use g_timeout_add()
4190 * The grouping of timers to fire at the same time results in a more power
4191 * and CPU efficient behavior so if your timer is in multiples of seconds
4192 * and you don't require the first timer exactly one second from now, the
4193 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
4195 * This internally creates a main loop source using
4196 * g_timeout_source_new_seconds() and attaches it to the main loop context
4197 * using g_source_attach(). You can do these steps manually if you need
4200 * Return value: the ID (greater than 0) of the event source.
4203 * Rename to: g_timeout_add_seconds
4206 g_timeout_add_seconds_full (gint priority,
4208 GSourceFunc function,
4210 GDestroyNotify notify)
4215 g_return_val_if_fail (function != NULL, 0);
4217 source = g_timeout_source_new_seconds (interval);
4219 if (priority != G_PRIORITY_DEFAULT)
4220 g_source_set_priority (source, priority);
4222 g_source_set_callback (source, function, data, notify);
4223 id = g_source_attach (source, NULL);
4224 g_source_unref (source);
4230 * g_timeout_add_seconds:
4231 * @interval: the time between calls to the function, in seconds
4232 * @function: function to call
4233 * @data: data to pass to @function
4235 * Sets a function to be called at regular intervals with the default
4236 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4237 * it returns %FALSE, at which point the timeout is automatically destroyed
4238 * and the function will not be called again.
4240 * This internally creates a main loop source using
4241 * g_timeout_source_new_seconds() and attaches it to the main loop context
4242 * using g_source_attach(). You can do these steps manually if you need
4243 * greater control. Also see g_timeout_add_seconds_full().
4245 * Note that the first call of the timer may not be precise for timeouts
4246 * of one second. If you need finer precision and have such a timeout,
4247 * you may want to use g_timeout_add() instead.
4249 * Return value: the ID (greater than 0) of the event source.
4254 g_timeout_add_seconds (guint interval,
4255 GSourceFunc function,
4258 g_return_val_if_fail (function != NULL, 0);
4260 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4263 /* Child watch functions */
4268 g_child_watch_prepare (GSource *source,
4277 g_child_watch_check (GSource *source)
4279 GChildWatchSource *child_watch_source;
4280 gboolean child_exited;
4282 child_watch_source = (GChildWatchSource *) source;
4284 child_exited = child_watch_source->poll.revents & G_IO_IN;
4291 * Note: We do _not_ check for the special value of STILL_ACTIVE
4292 * since we know that the process has exited and doing so runs into
4293 * problems if the child process "happens to return STILL_ACTIVE(259)"
4294 * as Microsoft's Platform SDK puts it.
4296 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4298 gchar *emsg = g_win32_error_message (GetLastError ());
4299 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4302 child_watch_source->child_status = -1;
4305 child_watch_source->child_status = child_status;
4308 return child_exited;
4311 #else /* G_OS_WIN32 */
4314 check_for_child_exited (GSource *source)
4316 GChildWatchSource *child_watch_source;
4319 /* protect against another SIGCHLD in the middle of this call */
4320 count = child_watch_count;
4322 child_watch_source = (GChildWatchSource *) source;
4324 if (child_watch_source->child_exited)
4327 if (child_watch_source->count < count)
4331 if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
4333 child_watch_source->child_status = child_status;
4334 child_watch_source->child_exited = TRUE;
4336 child_watch_source->count = count;
4339 return child_watch_source->child_exited;
4343 g_child_watch_prepare (GSource *source,
4348 return check_for_child_exited (source);
4352 g_child_watch_check (GSource *source)
4354 return check_for_child_exited (source);
4358 check_for_signal_delivery (GSource *source)
4360 GUnixSignalWatchSource *unix_signal_source = (GUnixSignalWatchSource*) source;
4363 G_LOCK (unix_signal_lock);
4364 if (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_SINGLE)
4366 switch (unix_signal_source->signum)
4369 delivered = unix_signal_state.sighup_delivered;
4372 delivered = unix_signal_state.sigint_delivered;
4375 delivered = unix_signal_state.sigterm_delivered;
4378 g_assert_not_reached ();
4385 g_assert (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_THREADED);
4386 delivered = unix_signal_source->pending;
4388 G_UNLOCK (unix_signal_lock);
4394 g_unix_signal_watch_prepare (GSource *source,
4399 return check_for_signal_delivery (source);
4403 g_unix_signal_watch_check (GSource *source)
4405 return check_for_signal_delivery (source);
4409 g_unix_signal_watch_dispatch (GSource *source,
4410 GSourceFunc callback,
4413 GUnixSignalWatchSource *unix_signal_source;
4415 unix_signal_source = (GUnixSignalWatchSource *) source;
4419 g_warning ("Unix signal source dispatched without callback\n"
4420 "You must call g_source_set_callback().");
4424 (callback) (user_data);
4426 G_LOCK (unix_signal_lock);
4427 if (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_SINGLE)
4429 switch (unix_signal_source->signum)
4432 unix_signal_state.sighup_delivered = FALSE;
4435 unix_signal_state.sigint_delivered = FALSE;
4438 unix_signal_state.sigterm_delivered = FALSE;
4444 g_assert (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_THREADED);
4445 unix_signal_source->pending = FALSE;
4447 G_UNLOCK (unix_signal_lock);
4453 ensure_unix_signal_handler_installed_unlocked (int signum)
4455 struct sigaction action;
4456 GError *error = NULL;
4458 if (unix_signal_init_state == UNIX_SIGNAL_UNINITIALIZED)
4460 sigemptyset (&unix_signal_mask);
4463 if (unix_signal_init_state == UNIX_SIGNAL_UNINITIALIZED
4464 || unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_SINGLE)
4466 if (!g_thread_supported ())
4468 /* There is nothing to do for initializing in the non-threaded
4471 if (unix_signal_init_state == UNIX_SIGNAL_UNINITIALIZED)
4472 unix_signal_init_state = UNIX_SIGNAL_INITIALIZED_SINGLE;
4476 if (!g_unix_open_pipe (unix_signal_wake_up_pipe, FD_CLOEXEC, &error))
4477 g_error ("Cannot create UNIX signal wake up pipe: %s\n", error->message);
4478 g_unix_set_fd_nonblocking (unix_signal_wake_up_pipe[1], TRUE, NULL);
4480 /* We create a helper thread that polls on the wakeup pipe indefinitely */
4481 if (g_thread_create (unix_signal_helper_thread, NULL, FALSE, &error) == NULL)
4482 g_error ("Cannot create a thread to monitor UNIX signals: %s\n", error->message);
4484 unix_signal_init_state = UNIX_SIGNAL_INITIALIZED_THREADED;
4488 if (sigismember (&unix_signal_mask, signum))
4491 sigaddset (&unix_signal_mask, signum);
4493 action.sa_handler = g_unix_signal_handler;
4494 sigemptyset (&action.sa_mask);
4495 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4496 sigaction (signum, &action, NULL);
4500 _g_main_create_unix_signal_watch (int signum)
4503 GUnixSignalWatchSource *unix_signal_source;
4505 source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
4506 unix_signal_source = (GUnixSignalWatchSource *) source;
4508 unix_signal_source->signum = signum;
4509 unix_signal_source->pending = FALSE;
4511 G_LOCK (unix_signal_lock);
4512 ensure_unix_signal_handler_installed_unlocked (signum);
4513 unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
4514 G_UNLOCK (unix_signal_lock);
4520 g_unix_signal_watch_finalize (GSource *source)
4522 G_LOCK (unix_signal_lock);
4523 unix_signal_watches = g_slist_remove (unix_signal_watches, source);
4524 G_UNLOCK (unix_signal_lock);
4527 #endif /* G_OS_WIN32 */
4530 g_child_watch_dispatch (GSource *source,
4531 GSourceFunc callback,
4534 GChildWatchSource *child_watch_source;
4535 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
4537 child_watch_source = (GChildWatchSource *) source;
4541 g_warning ("Child watch source dispatched without callback\n"
4542 "You must call g_source_set_callback().");
4546 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
4548 /* We never keep a child watch source around as the child is gone */
4555 g_unix_signal_handler (int signum)
4557 if (signum == SIGCHLD)
4558 child_watch_count ++;
4560 if (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_THREADED)
4566 buf[0] = _UNIX_SIGNAL_PIPE_SIGCHLD_CHAR;
4569 buf[0] = _UNIX_SIGNAL_PIPE_SIGHUP_CHAR;
4572 buf[0] = _UNIX_SIGNAL_PIPE_SIGINT_CHAR;
4575 buf[0] = _UNIX_SIGNAL_PIPE_SIGTERM_CHAR;
4578 /* Shouldn't happen */
4581 write (unix_signal_wake_up_pipe[1], buf, 1);
4585 /* We count on the signal interrupting the poll in the same thread. */
4589 /* Nothing to do - the handler will call waitpid() */
4592 unix_signal_state.sighup_delivered = TRUE;
4595 unix_signal_state.sigint_delivered = TRUE;
4598 unix_signal_state.sigterm_delivered = TRUE;
4601 g_assert_not_reached ();
4608 deliver_unix_signal (int signum)
4611 g_assert (signum == SIGHUP || signum == SIGINT || signum == SIGTERM);
4613 G_LOCK (unix_signal_lock);
4614 for (iter = unix_signal_watches; iter; iter = iter->next)
4616 GUnixSignalWatchSource *source = iter->data;
4618 if (source->signum != signum)
4621 source->pending = TRUE;
4623 G_UNLOCK (unix_signal_lock);
4627 * This thread is created whenever anything in GLib needs
4628 * to deal with UNIX signals; at present, just SIGCHLD
4629 * from g_child_watch_source_new().
4631 * Note: We could eventually make this thread a more public interface
4632 * and allow e.g. GDBus to use it instead of its own worker thread.
4635 unix_signal_helper_thread (gpointer data)
4640 ssize_t i, bytes_read;
4641 gboolean sigterm_received = FALSE;
4642 gboolean sigint_received = FALSE;
4643 gboolean sighup_received = FALSE;
4645 bytes_read = read (unix_signal_wake_up_pipe[0], b, sizeof (b));
4648 g_warning ("Failed to read from child watch wake up pipe: %s",
4650 /* Not much we can do here sanely; just wait a second and hope
4653 g_usleep (G_USEC_PER_SEC);
4656 for (i = 0; i < bytes_read; i++)
4660 case _UNIX_SIGNAL_PIPE_SIGCHLD_CHAR:
4661 /* The child watch source will call waitpid() in its
4662 * prepare() and check() methods; however, we don't
4663 * know which pid exited, so we need to wake up
4664 * all contexts. Note: actually we could get the pid
4665 * from the "siginfo_t" via the handler, but to pass
4666 * that info down the pipe would require a more structured
4667 * data stream (as opposed to a single byte).
4670 case _UNIX_SIGNAL_PIPE_SIGTERM_CHAR:
4671 sigterm_received = TRUE;
4673 case _UNIX_SIGNAL_PIPE_SIGHUP_CHAR:
4674 sighup_received = TRUE;
4676 case _UNIX_SIGNAL_PIPE_SIGINT_CHAR:
4677 sigint_received = TRUE;
4680 g_warning ("Invalid char '%c' read from child watch pipe", b[i]);
4684 if (sigterm_received)
4685 deliver_unix_signal (SIGTERM);
4686 if (sigint_received)
4687 deliver_unix_signal (SIGINT);
4688 if (sighup_received)
4689 deliver_unix_signal (SIGHUP);
4690 _g_main_wake_up_all_contexts ();
4695 g_child_watch_source_init (void)
4697 G_LOCK (unix_signal_lock);
4698 ensure_unix_signal_handler_installed_unlocked (SIGCHLD);
4699 G_UNLOCK (unix_signal_lock);
4702 #endif /* !G_OS_WIN32 */
4705 * g_child_watch_source_new:
4706 * @pid: process to watch. On POSIX the pid of a child process. On
4707 * Windows a handle for a process (which doesn't have to be a child).
4709 * Creates a new child_watch source.
4711 * The source will not initially be associated with any #GMainContext
4712 * and must be added to one with g_source_attach() before it will be
4715 * Note that child watch sources can only be used in conjunction with
4716 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4719 * Note that on platforms where #GPid must be explicitly closed
4720 * (see g_spawn_close_pid()) @pid must not be closed while the
4721 * source is still active. Typically, you will want to call
4722 * g_spawn_close_pid() in the callback function for the source.
4724 * Note further that using g_child_watch_source_new() is not
4725 * compatible with calling <literal>waitpid(-1)</literal> in
4726 * the application. Calling waitpid() for individual pids will
4729 * Return value: the newly-created child watch source
4734 g_child_watch_source_new (GPid pid)
4736 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4737 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4740 child_watch_source->poll.fd = (gintptr) pid;
4741 child_watch_source->poll.events = G_IO_IN;
4743 g_source_add_poll (source, &child_watch_source->poll);
4744 #else /* G_OS_WIN32 */
4745 g_child_watch_source_init ();
4746 #endif /* G_OS_WIN32 */
4748 child_watch_source->pid = pid;
4754 * g_child_watch_add_full:
4755 * @priority: the priority of the idle source. Typically this will be in the
4756 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4757 * @pid: process to watch. On POSIX the pid of a child process. On
4758 * Windows a handle for a process (which doesn't have to be a child).
4759 * @function: function to call
4760 * @data: data to pass to @function
4761 * @notify: function to call when the idle is removed, or %NULL
4763 * Sets a function to be called when the child indicated by @pid
4764 * exits, at the priority @priority.
4766 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4767 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4768 * the spawn function for the child watching to work.
4770 * Note that on platforms where #GPid must be explicitly closed
4771 * (see g_spawn_close_pid()) @pid must not be closed while the
4772 * source is still active. Typically, you will want to call
4773 * g_spawn_close_pid() in the callback function for the source.
4775 * GLib supports only a single callback per process id.
4777 * This internally creates a main loop source using
4778 * g_child_watch_source_new() and attaches it to the main loop context
4779 * using g_source_attach(). You can do these steps manually if you
4780 * need greater control.
4782 * Return value: the ID (greater than 0) of the event source.
4785 * Rename to: g_child_watch_add
4788 g_child_watch_add_full (gint priority,
4790 GChildWatchFunc function,
4792 GDestroyNotify notify)
4797 g_return_val_if_fail (function != NULL, 0);
4799 source = g_child_watch_source_new (pid);
4801 if (priority != G_PRIORITY_DEFAULT)
4802 g_source_set_priority (source, priority);
4804 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4805 id = g_source_attach (source, NULL);
4806 g_source_unref (source);
4812 * g_child_watch_add:
4813 * @pid: process id to watch. On POSIX the pid of a child process. On
4814 * Windows a handle for a process (which doesn't have to be a child).
4815 * @function: function to call
4816 * @data: data to pass to @function
4818 * Sets a function to be called when the child indicated by @pid
4819 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4821 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4822 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4823 * the spawn function for the child watching to work.
4825 * Note that on platforms where #GPid must be explicitly closed
4826 * (see g_spawn_close_pid()) @pid must not be closed while the
4827 * source is still active. Typically, you will want to call
4828 * g_spawn_close_pid() in the callback function for the source.
4830 * GLib supports only a single callback per process id.
4832 * This internally creates a main loop source using
4833 * g_child_watch_source_new() and attaches it to the main loop context
4834 * using g_source_attach(). You can do these steps manually if you
4835 * need greater control.
4837 * Return value: the ID (greater than 0) of the event source.
4842 g_child_watch_add (GPid pid,
4843 GChildWatchFunc function,
4846 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4850 /* Idle functions */
4853 g_idle_prepare (GSource *source,
4862 g_idle_check (GSource *source)
4868 g_idle_dispatch (GSource *source,
4869 GSourceFunc callback,
4874 g_warning ("Idle source dispatched without callback\n"
4875 "You must call g_source_set_callback().");
4879 return callback (user_data);
4883 * g_idle_source_new:
4885 * Creates a new idle source.
4887 * The source will not initially be associated with any #GMainContext
4888 * and must be added to one with g_source_attach() before it will be
4889 * executed. Note that the default priority for idle sources is
4890 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4891 * have a default priority of %G_PRIORITY_DEFAULT.
4893 * Return value: the newly-created idle source
4896 g_idle_source_new (void)
4900 source = g_source_new (&g_idle_funcs, sizeof (GSource));
4901 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4908 * @priority: the priority of the idle source. Typically this will be in the
4909 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4910 * @function: function to call
4911 * @data: data to pass to @function
4912 * @notify: function to call when the idle is removed, or %NULL
4914 * Adds a function to be called whenever there are no higher priority
4915 * events pending. If the function returns %FALSE it is automatically
4916 * removed from the list of event sources and will not be called again.
4918 * This internally creates a main loop source using g_idle_source_new()
4919 * and attaches it to the main loop context using g_source_attach().
4920 * You can do these steps manually if you need greater control.
4922 * Return value: the ID (greater than 0) of the event source.
4923 * Rename to: g_idle_add
4926 g_idle_add_full (gint priority,
4927 GSourceFunc function,
4929 GDestroyNotify notify)
4934 g_return_val_if_fail (function != NULL, 0);
4936 source = g_idle_source_new ();
4938 if (priority != G_PRIORITY_DEFAULT_IDLE)
4939 g_source_set_priority (source, priority);
4941 g_source_set_callback (source, function, data, notify);
4942 id = g_source_attach (source, NULL);
4943 g_source_unref (source);
4950 * @function: function to call
4951 * @data: data to pass to @function.
4953 * Adds a function to be called whenever there are no higher priority
4954 * events pending to the default main loop. The function is given the
4955 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4956 * returns %FALSE it is automatically removed from the list of event
4957 * sources and will not be called again.
4959 * This internally creates a main loop source using g_idle_source_new()
4960 * and attaches it to the main loop context using g_source_attach().
4961 * You can do these steps manually if you need greater control.
4963 * Return value: the ID (greater than 0) of the event source.
4966 g_idle_add (GSourceFunc function,
4969 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4973 * g_idle_remove_by_data:
4974 * @data: the data for the idle source's callback.
4976 * Removes the idle function with the given data.
4978 * Return value: %TRUE if an idle source was found and removed.
4981 g_idle_remove_by_data (gpointer data)
4983 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4987 * g_main_context_invoke:
4988 * @context: a #GMainContext, or %NULL
4989 * @function: function to call
4990 * @data: data to pass to @function
4992 * Invokes a function in such a way that @context is owned during the
4993 * invocation of @function.
4995 * If @context is %NULL then the global default main context — as
4996 * returned by g_main_context_default() — is used.
4998 * If @context is owned by the current thread, @function is called
4999 * directly. Otherwise, if @context is the thread-default main context
5000 * of the current thread and g_main_context_acquire() succeeds, then
5001 * @function is called and g_main_context_release() is called
5004 * In any other case, an idle source is created to call @function and
5005 * that source is attached to @context (presumably to be run in another
5006 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
5007 * priority. If you want a different priority, use
5008 * g_main_context_invoke_full().
5010 * Note that, as with normal idle functions, @function should probably
5011 * return %FALSE. If it returns %TRUE, it will be continuously run in a
5012 * loop (and may prevent this call from returning).
5017 g_main_context_invoke (GMainContext *context,
5018 GSourceFunc function,
5021 g_main_context_invoke_full (context,
5023 function, data, NULL);
5027 * g_main_context_invoke_full:
5028 * @context: a #GMainContext, or %NULL
5029 * @priority: the priority at which to run @function
5030 * @function: function to call
5031 * @data: data to pass to @function
5032 * @notify: a function to call when @data is no longer in use, or %NULL.
5034 * Invokes a function in such a way that @context is owned during the
5035 * invocation of @function.
5037 * This function is the same as g_main_context_invoke() except that it
5038 * lets you specify the priority incase @function ends up being
5039 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
5041 * @notify should not assume that it is called from any particular
5042 * thread or with any particular context acquired.
5047 g_main_context_invoke_full (GMainContext *context,
5049 GSourceFunc function,
5051 GDestroyNotify notify)
5053 g_return_if_fail (function != NULL);
5056 context = g_main_context_default ();
5058 if (g_main_context_is_owner (context))
5060 while (function (data));
5067 GMainContext *thread_default;
5069 thread_default = g_main_context_get_thread_default ();
5071 if (!thread_default)
5072 thread_default = g_main_context_default ();
5074 if (thread_default == context && g_main_context_acquire (context))
5076 while (function (data));
5078 g_main_context_release (context);
5087 source = g_idle_source_new ();
5088 g_source_set_priority (source, priority);
5089 g_source_set_callback (source, function, data, notify);
5090 g_source_attach (source, context);
5091 g_source_unref (source);