1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * gmain.c: Main loop abstraction, timeouts, and idle functions
5 * Copyright 1998 Owen Taylor
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the
19 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 * Boston, MA 02111-1307, USA.
24 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
25 * file for a list of people on the GLib Team. See the ChangeLog
26 * files for a list of changes. These files are distributed with
27 * GLib at ftp://ftp.gtk.org/pub/gtk/.
35 #include "glibconfig.h"
37 /* Uncomment the next line (and the corresponding line in gpoll.c) to
38 * enable debugging printouts if the environment variable
39 * G_MAIN_POLL_DEBUG is set to some value.
41 /* #define G_MAIN_POLL_DEBUG */
44 /* Always enable debugging printout on Windows, as it is more often
47 #define G_MAIN_POLL_DEBUG
51 #include "glib-unix.h"
54 #include <sys/eventfd.h>
59 #include <sys/types.h>
62 #ifdef HAVE_SYS_TIME_H
64 #endif /* HAVE_SYS_TIME_H */
67 #endif /* HAVE_UNISTD_H */
74 #endif /* G_OS_WIN32 */
77 #include <sys/socket.h>
79 #endif /* G_OS_BEOS */
84 #include "giochannel.h"
88 #include "gstrfuncs.h"
89 #include "gtestutils.h"
90 #include "gthreadprivate.h"
96 #ifdef G_MAIN_POLL_DEBUG
102 #include "glib-private.h"
106 * @title: The Main Event Loop
107 * @short_description: manages all available sources of events
109 * The main event loop manages all the available sources of events for
110 * GLib and GTK+ applications. These events can come from any number of
111 * different types of sources such as file descriptors (plain files,
112 * pipes or sockets) and timeouts. New types of event sources can also
113 * be added using g_source_attach().
115 * To allow multiple independent sets of sources to be handled in
116 * different threads, each source is associated with a #GMainContext.
117 * A GMainContext can only be running in a single thread, but
118 * sources can be added to it and removed from it from other threads.
120 * Each event source is assigned a priority. The default priority,
121 * #G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
122 * Values greater than 0 denote lower priorities. Events from high priority
123 * sources are always processed before events from lower priority sources.
125 * Idle functions can also be added, and assigned a priority. These will
126 * be run whenever no events with a higher priority are ready to be processed.
128 * The #GMainLoop data type represents a main event loop. A GMainLoop is
129 * created with g_main_loop_new(). After adding the initial event sources,
130 * g_main_loop_run() is called. This continuously checks for new events from
131 * each of the event sources and dispatches them. Finally, the processing of
132 * an event from one of the sources leads to a call to g_main_loop_quit() to
133 * exit the main loop, and g_main_loop_run() returns.
135 * It is possible to create new instances of #GMainLoop recursively.
136 * This is often used in GTK+ applications when showing modal dialog
137 * boxes. Note that event sources are associated with a particular
138 * #GMainContext, and will be checked and dispatched for all main
139 * loops associated with that GMainContext.
141 * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
142 * gtk_main_quit() and gtk_events_pending().
144 * <refsect2><title>Creating new source types</title>
145 * <para>One of the unusual features of the #GMainLoop functionality
146 * is that new types of event source can be created and used in
147 * addition to the builtin type of event source. A new event source
148 * type is used for handling GDK events. A new source type is created
149 * by <firstterm>deriving</firstterm> from the #GSource structure.
150 * The derived type of source is represented by a structure that has
151 * the #GSource structure as a first element, and other elements specific
152 * to the new source type. To create an instance of the new source type,
153 * call g_source_new() passing in the size of the derived structure and
154 * a table of functions. These #GSourceFuncs determine the behavior of
155 * the new source type.</para>
156 * <para>New source types basically interact with the main context
157 * in two ways. Their prepare function in #GSourceFuncs can set a timeout
158 * to determine the maximum amount of time that the main loop will sleep
159 * before checking the source again. In addition, or as well, the source
160 * can add file descriptors to the set that the main context checks using
161 * g_source_add_poll().</para>
163 * <refsect2><title>Customizing the main loop iteration</title>
164 * <para>Single iterations of a #GMainContext can be run with
165 * g_main_context_iteration(). In some cases, more detailed control
166 * of exactly how the details of the main loop work is desired, for
167 * instance, when integrating the #GMainLoop with an external main loop.
168 * In such cases, you can call the component functions of
169 * g_main_context_iteration() directly. These functions are
170 * g_main_context_prepare(), g_main_context_query(),
171 * g_main_context_check() and g_main_context_dispatch().</para>
172 * <para>The operation of these functions can best be seen in terms
173 * of a state diagram, as shown in <xref linkend="mainloop-states"/>.</para>
174 * <figure id="mainloop-states"><title>States of a Main Context</title>
175 * <graphic fileref="mainloop-states.gif" format="GIF"></graphic>
179 * On Unix, the GLib mainloop is incompatible with fork(). Any program
180 * using the mainloop must either exec() or exit() from the child
181 * without returning to the mainloop.
186 typedef struct _GTimeoutSource GTimeoutSource;
187 typedef struct _GChildWatchSource GChildWatchSource;
188 typedef struct _GUnixSignalWatchSource GUnixSignalWatchSource;
189 typedef struct _GPollRec GPollRec;
190 typedef struct _GSourceCallback GSourceCallback;
194 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
195 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
198 typedef struct _GMainWaiter GMainWaiter;
206 typedef struct _GMainDispatch GMainDispatch;
208 struct _GMainDispatch
211 GSList *dispatching_sources; /* stack of current sources */
214 #ifdef G_MAIN_POLL_DEBUG
215 gboolean _g_main_poll_debug = FALSE;
220 /* The following lock is used for both the list of sources
221 * and the list of poll records
231 GPtrArray *pending_dispatches;
232 gint timeout; /* Timeout for current iteration */
235 GSource *source_list;
236 gint in_check_or_prepare;
238 GPollRec *poll_records, *poll_records_tail;
239 guint n_poll_records;
240 GPollFD *cached_poll_array;
241 guint cached_poll_array_size;
247 /* Flag indicating whether the set of fd's changed during a poll */
248 gboolean poll_changed;
253 gboolean time_is_fresh;
256 struct _GSourceCallback
261 GDestroyNotify notify;
266 GMainContext *context;
271 struct _GTimeoutSource
279 struct _GChildWatchSource
286 #else /* G_OS_WIN32 */
287 gboolean child_exited;
288 #endif /* G_OS_WIN32 */
291 struct _GUnixSignalWatchSource
306 struct _GSourcePrivate
308 GSList *child_sources;
309 GSource *parent_source;
312 #define LOCK_CONTEXT(context) g_mutex_lock (&context->mutex)
313 #define UNLOCK_CONTEXT(context) g_mutex_unlock (&context->mutex)
314 #define G_THREAD_SELF g_thread_self ()
316 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
317 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
318 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
320 #define SOURCE_UNREF(source, context) \
322 if ((source)->ref_count > 1) \
323 (source)->ref_count--; \
325 g_source_unref_internal ((source), (context), TRUE); \
329 /* Forward declarations */
331 static void g_source_unref_internal (GSource *source,
332 GMainContext *context,
334 static void g_source_destroy_internal (GSource *source,
335 GMainContext *context,
337 static void g_source_set_priority_unlocked (GSource *source,
338 GMainContext *context,
340 static void g_main_context_poll (GMainContext *context,
345 static void g_main_context_add_poll_unlocked (GMainContext *context,
348 static void g_main_context_remove_poll_unlocked (GMainContext *context,
351 static gboolean g_timeout_prepare (GSource *source,
353 static gboolean g_timeout_check (GSource *source);
354 static gboolean g_timeout_dispatch (GSource *source,
355 GSourceFunc callback,
357 static gboolean g_child_watch_prepare (GSource *source,
359 static gboolean g_child_watch_check (GSource *source);
360 static gboolean g_child_watch_dispatch (GSource *source,
361 GSourceFunc callback,
363 static void g_child_watch_finalize (GSource *source);
365 static void g_unix_signal_handler (int signum);
366 static gboolean g_unix_signal_watch_prepare (GSource *source,
368 static gboolean g_unix_signal_watch_check (GSource *source);
369 static gboolean g_unix_signal_watch_dispatch (GSource *source,
370 GSourceFunc callback,
372 static void g_unix_signal_watch_finalize (GSource *source);
374 static gboolean g_idle_prepare (GSource *source,
376 static gboolean g_idle_check (GSource *source);
377 static gboolean g_idle_dispatch (GSource *source,
378 GSourceFunc callback,
381 static GMainContext *glib_worker_context;
382 static gboolean g_main_context_fork_detected;
384 G_LOCK_DEFINE_STATIC (main_loop);
385 static GMainContext *default_main_context;
390 /* UNIX signals work by marking one of these variables then waking the
391 * worker context to check on them and dispatch accordingly.
393 static volatile gchar unix_signal_pending[NSIG];
394 static volatile gboolean any_unix_signal_pending;
396 /* Guards all the data below */
397 G_LOCK_DEFINE_STATIC (unix_signal_lock);
398 static GSList *unix_signal_watches;
399 static GSList *unix_child_watches;
401 static GSourceFuncs g_unix_signal_funcs =
403 g_unix_signal_watch_prepare,
404 g_unix_signal_watch_check,
405 g_unix_signal_watch_dispatch,
406 g_unix_signal_watch_finalize
408 #endif /* !G_OS_WIN32 */
409 G_LOCK_DEFINE_STATIC (main_context_list);
410 static GSList *main_context_list = NULL;
412 GSourceFuncs g_timeout_funcs =
420 GSourceFuncs g_child_watch_funcs =
422 g_child_watch_prepare,
424 g_child_watch_dispatch,
425 g_child_watch_finalize
428 GSourceFuncs g_idle_funcs =
437 * g_main_context_ref:
438 * @context: a #GMainContext
440 * Increases the reference count on a #GMainContext object by one.
442 * Returns: the @context that was passed in (since 2.6)
445 g_main_context_ref (GMainContext *context)
447 g_return_val_if_fail (context != NULL, NULL);
448 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
450 g_atomic_int_inc (&context->ref_count);
456 poll_rec_list_free (GMainContext *context,
459 g_slice_free_chain (GPollRec, list, next);
463 * g_main_context_unref:
464 * @context: a #GMainContext
466 * Decreases the reference count on a #GMainContext object by one. If
467 * the result is zero, free the context and free all associated memory.
470 g_main_context_unref (GMainContext *context)
473 g_return_if_fail (context != NULL);
474 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
476 if (!g_atomic_int_dec_and_test (&context->ref_count))
479 G_LOCK (main_context_list);
480 main_context_list = g_slist_remove (main_context_list, context);
481 G_UNLOCK (main_context_list);
483 source = context->source_list;
486 GSource *next = source->next;
487 g_source_destroy_internal (source, context, FALSE);
491 g_mutex_clear (&context->mutex);
493 g_ptr_array_free (context->pending_dispatches, TRUE);
494 g_free (context->cached_poll_array);
496 poll_rec_list_free (context, context->poll_records);
498 g_wakeup_free (context->wakeup);
499 g_cond_clear (&context->cond);
506 g_main_context_forked (void)
508 g_main_context_fork_detected = TRUE;
513 * g_main_context_new:
515 * Creates a new #GMainContext structure.
517 * Return value: the new #GMainContext
520 g_main_context_new (void)
522 static gsize initialised;
523 GMainContext *context;
525 g_thread_init_glib ();
527 if (g_once_init_enter (&initialised))
529 #ifdef G_MAIN_POLL_DEBUG
530 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
531 _g_main_poll_debug = TRUE;
535 pthread_atfork (NULL, NULL, g_main_context_forked);
538 g_once_init_leave (&initialised, TRUE);
541 context = g_new0 (GMainContext, 1);
543 g_mutex_init (&context->mutex);
544 g_cond_init (&context->cond);
546 context->owner = NULL;
547 context->waiters = NULL;
549 context->ref_count = 1;
551 context->next_id = 1;
553 context->source_list = NULL;
555 context->poll_func = g_poll;
557 context->cached_poll_array = NULL;
558 context->cached_poll_array_size = 0;
560 context->pending_dispatches = g_ptr_array_new ();
562 context->time_is_fresh = FALSE;
564 context->wakeup = g_wakeup_new ();
565 g_wakeup_get_pollfd (context->wakeup, &context->wake_up_rec);
566 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
568 G_LOCK (main_context_list);
569 main_context_list = g_slist_append (main_context_list, context);
571 #ifdef G_MAIN_POLL_DEBUG
572 if (_g_main_poll_debug)
573 g_print ("created context=%p\n", context);
576 G_UNLOCK (main_context_list);
582 * g_main_context_default:
584 * Returns the global default main context. This is the main context
585 * used for main loop functions when a main loop is not explicitly
586 * specified, and corresponds to the "main" main loop. See also
587 * g_main_context_get_thread_default().
589 * Return value: (transfer none): the global default main context.
592 g_main_context_default (void)
598 if (!default_main_context)
600 default_main_context = g_main_context_new ();
601 #ifdef G_MAIN_POLL_DEBUG
602 if (_g_main_poll_debug)
603 g_print ("default context=%p\n", default_main_context);
607 G_UNLOCK (main_loop);
609 return default_main_context;
612 static GStaticPrivate thread_context_stack = G_STATIC_PRIVATE_INIT;
615 free_context_stack (gpointer data)
617 GQueue *stack = data;
618 GMainContext *context;
620 while (!g_queue_is_empty (stack))
622 context = g_queue_pop_head (stack);
623 g_main_context_release (context);
625 g_main_context_unref (context);
627 g_queue_free (stack);
631 * g_main_context_push_thread_default:
632 * @context: a #GMainContext, or %NULL for the global default context
634 * Acquires @context and sets it as the thread-default context for the
635 * current thread. This will cause certain asynchronous operations
636 * (such as most <link linkend="gio">gio</link>-based I/O) which are
637 * started in this thread to run under @context and deliver their
638 * results to its main loop, rather than running under the global
639 * default context in the main thread. Note that calling this function
640 * changes the context returned by
641 * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
642 * one returned by g_main_context_default(), so it does not affect the
643 * context used by functions like g_idle_add().
645 * Normally you would call this function shortly after creating a new
646 * thread, passing it a #GMainContext which will be run by a
647 * #GMainLoop in that thread, to set a new default context for all
648 * async operations in that thread. (In this case, you don't need to
649 * ever call g_main_context_pop_thread_default().) In some cases
650 * however, you may want to schedule a single operation in a
651 * non-default context, or temporarily use a non-default context in
652 * the main thread. In that case, you can wrap the call to the
653 * asynchronous operation inside a
654 * g_main_context_push_thread_default() /
655 * g_main_context_pop_thread_default() pair, but it is up to you to
656 * ensure that no other asynchronous operations accidentally get
657 * started while the non-default context is active.
659 * Beware that libraries that predate this function may not correctly
660 * handle being used from a thread with a thread-default context. Eg,
661 * see g_file_supports_thread_contexts().
666 g_main_context_push_thread_default (GMainContext *context)
669 gboolean acquired_context;
671 acquired_context = g_main_context_acquire (context);
672 g_return_if_fail (acquired_context);
674 if (context == g_main_context_default ())
677 g_main_context_ref (context);
679 stack = g_static_private_get (&thread_context_stack);
682 stack = g_queue_new ();
683 g_static_private_set (&thread_context_stack, stack,
687 g_queue_push_head (stack, context);
691 * g_main_context_pop_thread_default:
692 * @context: a #GMainContext object, or %NULL
694 * Pops @context off the thread-default context stack (verifying that
695 * it was on the top of the stack).
700 g_main_context_pop_thread_default (GMainContext *context)
704 if (context == g_main_context_default ())
707 stack = g_static_private_get (&thread_context_stack);
709 g_return_if_fail (stack != NULL);
710 g_return_if_fail (g_queue_peek_head (stack) == context);
712 g_queue_pop_head (stack);
714 g_main_context_release (context);
716 g_main_context_unref (context);
720 * g_main_context_get_thread_default:
722 * Gets the thread-default #GMainContext for this thread. Asynchronous
723 * operations that want to be able to be run in contexts other than
724 * the default one should call this method to get a #GMainContext to
725 * add their #GSource<!-- -->s to. (Note that even in single-threaded
726 * programs applications may sometimes want to temporarily push a
727 * non-default context, so it is not safe to assume that this will
728 * always return %NULL if threads are not initialized.)
730 * Returns: (transfer none): the thread-default #GMainContext, or
731 * %NULL if the thread-default context is the global default context.
736 g_main_context_get_thread_default (void)
740 stack = g_static_private_get (&thread_context_stack);
742 return g_queue_peek_head (stack);
747 /* Hooks for adding to the main loop */
751 * @source_funcs: structure containing functions that implement
752 * the sources behavior.
753 * @struct_size: size of the #GSource structure to create.
755 * Creates a new #GSource structure. The size is specified to
756 * allow creating structures derived from #GSource that contain
757 * additional data. The size passed in must be at least
758 * <literal>sizeof (GSource)</literal>.
760 * The source will not initially be associated with any #GMainContext
761 * and must be added to one with g_source_attach() before it will be
764 * Return value: the newly-created #GSource.
767 g_source_new (GSourceFuncs *source_funcs,
772 g_return_val_if_fail (source_funcs != NULL, NULL);
773 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
775 source = (GSource*) g_malloc0 (struct_size);
777 source->source_funcs = source_funcs;
778 source->ref_count = 1;
780 source->priority = G_PRIORITY_DEFAULT;
782 source->flags = G_HOOK_FLAG_ACTIVE;
784 /* NULL/0 initialization for all other fields */
789 /* Holds context's lock
792 g_source_list_add (GSource *source,
793 GMainContext *context)
795 GSource *tmp_source, *last_source;
797 if (source->priv && source->priv->parent_source)
799 /* Put the source immediately before its parent */
800 tmp_source = source->priv->parent_source;
801 last_source = source->priv->parent_source->prev;
806 tmp_source = context->source_list;
807 while (tmp_source && tmp_source->priority <= source->priority)
809 last_source = tmp_source;
810 tmp_source = tmp_source->next;
814 source->next = tmp_source;
816 tmp_source->prev = source;
818 source->prev = last_source;
820 last_source->next = source;
822 context->source_list = source;
825 /* Holds context's lock
828 g_source_list_remove (GSource *source,
829 GMainContext *context)
832 source->prev->next = source->next;
834 context->source_list = source->next;
837 source->next->prev = source->prev;
844 g_source_attach_unlocked (GSource *source,
845 GMainContext *context)
850 source->context = context;
851 result = source->source_id = context->next_id++;
854 g_source_list_add (source, context);
856 tmp_list = source->poll_fds;
859 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
860 tmp_list = tmp_list->next;
865 tmp_list = source->priv->child_sources;
868 g_source_attach_unlocked (tmp_list->data, context);
869 tmp_list = tmp_list->next;
878 * @source: a #GSource
879 * @context: a #GMainContext (if %NULL, the default context will be used)
881 * Adds a #GSource to a @context so that it will be executed within
882 * that context. Remove it by calling g_source_destroy().
884 * Return value: the ID (greater than 0) for the source within the
888 g_source_attach (GSource *source,
889 GMainContext *context)
893 g_return_val_if_fail (source->context == NULL, 0);
894 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
897 context = g_main_context_default ();
899 LOCK_CONTEXT (context);
901 result = g_source_attach_unlocked (source, context);
903 /* If another thread has acquired the context, wake it up since it
904 * might be in poll() right now.
906 if (context->owner && context->owner != G_THREAD_SELF)
907 g_wakeup_signal (context->wakeup);
909 UNLOCK_CONTEXT (context);
915 g_source_destroy_internal (GSource *source,
916 GMainContext *context,
920 LOCK_CONTEXT (context);
922 if (!SOURCE_DESTROYED (source))
925 gpointer old_cb_data;
926 GSourceCallbackFuncs *old_cb_funcs;
928 source->flags &= ~G_HOOK_FLAG_ACTIVE;
930 old_cb_data = source->callback_data;
931 old_cb_funcs = source->callback_funcs;
933 source->callback_data = NULL;
934 source->callback_funcs = NULL;
938 UNLOCK_CONTEXT (context);
939 old_cb_funcs->unref (old_cb_data);
940 LOCK_CONTEXT (context);
943 if (!SOURCE_BLOCKED (source))
945 tmp_list = source->poll_fds;
948 g_main_context_remove_poll_unlocked (context, tmp_list->data);
949 tmp_list = tmp_list->next;
953 if (source->priv && source->priv->child_sources)
955 /* This is safe because even if a child_source finalizer or
956 * closure notify tried to modify source->priv->child_sources
957 * from outside the lock, it would fail since
958 * SOURCE_DESTROYED(source) is now TRUE.
960 tmp_list = source->priv->child_sources;
963 g_source_destroy_internal (tmp_list->data, context, TRUE);
964 g_source_unref_internal (tmp_list->data, context, TRUE);
965 tmp_list = tmp_list->next;
967 g_slist_free (source->priv->child_sources);
968 source->priv->child_sources = NULL;
971 g_source_unref_internal (source, context, TRUE);
975 UNLOCK_CONTEXT (context);
980 * @source: a #GSource
982 * Removes a source from its #GMainContext, if any, and mark it as
983 * destroyed. The source cannot be subsequently added to another
987 g_source_destroy (GSource *source)
989 GMainContext *context;
991 g_return_if_fail (source != NULL);
993 context = source->context;
996 g_source_destroy_internal (source, context, FALSE);
998 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1003 * @source: a #GSource
1005 * Returns the numeric ID for a particular source. The ID of a source
1006 * is a positive integer which is unique within a particular main loop
1007 * context. The reverse
1008 * mapping from ID to source is done by g_main_context_find_source_by_id().
1010 * Return value: the ID (greater than 0) for the source
1013 g_source_get_id (GSource *source)
1017 g_return_val_if_fail (source != NULL, 0);
1018 g_return_val_if_fail (source->context != NULL, 0);
1020 LOCK_CONTEXT (source->context);
1021 result = source->source_id;
1022 UNLOCK_CONTEXT (source->context);
1028 * g_source_get_context:
1029 * @source: a #GSource
1031 * Gets the #GMainContext with which the source is associated.
1032 * Calling this function on a destroyed source is an error.
1034 * Return value: (transfer none): the #GMainContext with which the
1035 * source is associated, or %NULL if the context has not
1036 * yet been added to a source.
1039 g_source_get_context (GSource *source)
1041 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1043 return source->context;
1047 * g_source_add_poll:
1048 * @source:a #GSource
1049 * @fd: a #GPollFD structure holding information about a file
1050 * descriptor to watch.
1052 * Adds a file descriptor to the set of file descriptors polled for
1053 * this source. This is usually combined with g_source_new() to add an
1054 * event source. The event source's check function will typically test
1055 * the @revents field in the #GPollFD struct and return %TRUE if events need
1059 g_source_add_poll (GSource *source,
1062 GMainContext *context;
1064 g_return_if_fail (source != NULL);
1065 g_return_if_fail (fd != NULL);
1066 g_return_if_fail (!SOURCE_DESTROYED (source));
1068 context = source->context;
1071 LOCK_CONTEXT (context);
1073 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1077 if (!SOURCE_BLOCKED (source))
1078 g_main_context_add_poll_unlocked (context, source->priority, fd);
1079 UNLOCK_CONTEXT (context);
1084 * g_source_remove_poll:
1085 * @source:a #GSource
1086 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1088 * Removes a file descriptor from the set of file descriptors polled for
1092 g_source_remove_poll (GSource *source,
1095 GMainContext *context;
1097 g_return_if_fail (source != NULL);
1098 g_return_if_fail (fd != NULL);
1099 g_return_if_fail (!SOURCE_DESTROYED (source));
1101 context = source->context;
1104 LOCK_CONTEXT (context);
1106 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1110 if (!SOURCE_BLOCKED (source))
1111 g_main_context_remove_poll_unlocked (context, fd);
1112 UNLOCK_CONTEXT (context);
1117 * g_source_add_child_source:
1118 * @source:a #GSource
1119 * @child_source: a second #GSource that @source should "poll"
1121 * Adds @child_source to @source as a "polled" source; when @source is
1122 * added to a #GMainContext, @child_source will be automatically added
1123 * with the same priority, when @child_source is triggered, it will
1124 * cause @source to dispatch (in addition to calling its own
1125 * callback), and when @source is destroyed, it will destroy
1126 * @child_source as well. (@source will also still be dispatched if
1127 * its own prepare/check functions indicate that it is ready.)
1129 * If you don't need @child_source to do anything on its own when it
1130 * triggers, you can call g_source_set_dummy_callback() on it to set a
1131 * callback that does nothing (except return %TRUE if appropriate).
1133 * @source will hold a reference on @child_source while @child_source
1134 * is attached to it.
1139 g_source_add_child_source (GSource *source,
1140 GSource *child_source)
1142 GMainContext *context;
1144 g_return_if_fail (source != NULL);
1145 g_return_if_fail (child_source != NULL);
1146 g_return_if_fail (!SOURCE_DESTROYED (source));
1147 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1148 g_return_if_fail (child_source->context == NULL);
1149 g_return_if_fail (child_source->priv == NULL || child_source->priv->parent_source == NULL);
1151 context = source->context;
1154 LOCK_CONTEXT (context);
1157 source->priv = g_slice_new0 (GSourcePrivate);
1158 if (!child_source->priv)
1159 child_source->priv = g_slice_new0 (GSourcePrivate);
1161 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1162 g_source_ref (child_source));
1163 child_source->priv->parent_source = source;
1164 g_source_set_priority_unlocked (child_source, context, source->priority);
1168 UNLOCK_CONTEXT (context);
1169 g_source_attach (child_source, context);
1174 * g_source_remove_child_source:
1175 * @source:a #GSource
1176 * @child_source: a #GSource previously passed to
1177 * g_source_add_child_source().
1179 * Detaches @child_source from @source and destroys it.
1184 g_source_remove_child_source (GSource *source,
1185 GSource *child_source)
1187 GMainContext *context;
1189 g_return_if_fail (source != NULL);
1190 g_return_if_fail (child_source != NULL);
1191 g_return_if_fail (child_source->priv != NULL && child_source->priv->parent_source == source);
1192 g_return_if_fail (!SOURCE_DESTROYED (source));
1193 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1195 context = source->context;
1198 LOCK_CONTEXT (context);
1200 source->priv->child_sources = g_slist_remove (source->priv->child_sources, child_source);
1201 g_source_destroy_internal (child_source, context, TRUE);
1202 g_source_unref_internal (child_source, context, TRUE);
1205 UNLOCK_CONTEXT (context);
1209 * g_source_set_callback_indirect:
1210 * @source: the source
1211 * @callback_data: pointer to callback data "object"
1212 * @callback_funcs: functions for reference counting @callback_data
1213 * and getting the callback and data
1215 * Sets the callback function storing the data as a refcounted callback
1216 * "object". This is used internally. Note that calling
1217 * g_source_set_callback_indirect() assumes
1218 * an initial reference count on @callback_data, and thus
1219 * @callback_funcs->unref will eventually be called once more
1220 * than @callback_funcs->ref.
1223 g_source_set_callback_indirect (GSource *source,
1224 gpointer callback_data,
1225 GSourceCallbackFuncs *callback_funcs)
1227 GMainContext *context;
1228 gpointer old_cb_data;
1229 GSourceCallbackFuncs *old_cb_funcs;
1231 g_return_if_fail (source != NULL);
1232 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1234 context = source->context;
1237 LOCK_CONTEXT (context);
1239 old_cb_data = source->callback_data;
1240 old_cb_funcs = source->callback_funcs;
1242 source->callback_data = callback_data;
1243 source->callback_funcs = callback_funcs;
1246 UNLOCK_CONTEXT (context);
1249 old_cb_funcs->unref (old_cb_data);
1253 g_source_callback_ref (gpointer cb_data)
1255 GSourceCallback *callback = cb_data;
1257 callback->ref_count++;
1262 g_source_callback_unref (gpointer cb_data)
1264 GSourceCallback *callback = cb_data;
1266 callback->ref_count--;
1267 if (callback->ref_count == 0)
1269 if (callback->notify)
1270 callback->notify (callback->data);
1276 g_source_callback_get (gpointer cb_data,
1281 GSourceCallback *callback = cb_data;
1283 *func = callback->func;
1284 *data = callback->data;
1287 static GSourceCallbackFuncs g_source_callback_funcs = {
1288 g_source_callback_ref,
1289 g_source_callback_unref,
1290 g_source_callback_get,
1294 * g_source_set_callback:
1295 * @source: the source
1296 * @func: a callback function
1297 * @data: the data to pass to callback function
1298 * @notify: a function to call when @data is no longer in use, or %NULL.
1300 * Sets the callback function for a source. The callback for a source is
1301 * called from the source's dispatch function.
1303 * The exact type of @func depends on the type of source; ie. you
1304 * should not count on @func being called with @data as its first
1307 * Typically, you won't use this function. Instead use functions specific
1308 * to the type of source you are using.
1311 g_source_set_callback (GSource *source,
1314 GDestroyNotify notify)
1316 GSourceCallback *new_callback;
1318 g_return_if_fail (source != NULL);
1320 new_callback = g_new (GSourceCallback, 1);
1322 new_callback->ref_count = 1;
1323 new_callback->func = func;
1324 new_callback->data = data;
1325 new_callback->notify = notify;
1327 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1332 * g_source_set_funcs:
1333 * @source: a #GSource
1334 * @funcs: the new #GSourceFuncs
1336 * Sets the source functions (can be used to override
1337 * default implementations) of an unattached source.
1342 g_source_set_funcs (GSource *source,
1343 GSourceFuncs *funcs)
1345 g_return_if_fail (source != NULL);
1346 g_return_if_fail (source->context == NULL);
1347 g_return_if_fail (source->ref_count > 0);
1348 g_return_if_fail (funcs != NULL);
1350 source->source_funcs = funcs;
1354 g_source_set_priority_unlocked (GSource *source,
1355 GMainContext *context,
1360 source->priority = priority;
1364 /* Remove the source from the context's source and then
1365 * add it back so it is sorted in the correct place
1367 g_source_list_remove (source, source->context);
1368 g_source_list_add (source, source->context);
1370 if (!SOURCE_BLOCKED (source))
1372 tmp_list = source->poll_fds;
1375 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1376 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1378 tmp_list = tmp_list->next;
1383 if (source->priv && source->priv->child_sources)
1385 tmp_list = source->priv->child_sources;
1388 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1389 tmp_list = tmp_list->next;
1395 * g_source_set_priority:
1396 * @source: a #GSource
1397 * @priority: the new priority.
1399 * Sets the priority of a source. While the main loop is being run, a
1400 * source will be dispatched if it is ready to be dispatched and no
1401 * sources at a higher (numerically smaller) priority are ready to be
1405 g_source_set_priority (GSource *source,
1408 GMainContext *context;
1410 g_return_if_fail (source != NULL);
1412 context = source->context;
1415 LOCK_CONTEXT (context);
1416 g_source_set_priority_unlocked (source, context, priority);
1418 UNLOCK_CONTEXT (source->context);
1422 * g_source_get_priority:
1423 * @source: a #GSource
1425 * Gets the priority of a source.
1427 * Return value: the priority of the source
1430 g_source_get_priority (GSource *source)
1432 g_return_val_if_fail (source != NULL, 0);
1434 return source->priority;
1438 * g_source_set_can_recurse:
1439 * @source: a #GSource
1440 * @can_recurse: whether recursion is allowed for this source
1442 * Sets whether a source can be called recursively. If @can_recurse is
1443 * %TRUE, then while the source is being dispatched then this source
1444 * will be processed normally. Otherwise, all processing of this
1445 * source is blocked until the dispatch function returns.
1448 g_source_set_can_recurse (GSource *source,
1449 gboolean can_recurse)
1451 GMainContext *context;
1453 g_return_if_fail (source != NULL);
1455 context = source->context;
1458 LOCK_CONTEXT (context);
1461 source->flags |= G_SOURCE_CAN_RECURSE;
1463 source->flags &= ~G_SOURCE_CAN_RECURSE;
1466 UNLOCK_CONTEXT (context);
1470 * g_source_get_can_recurse:
1471 * @source: a #GSource
1473 * Checks whether a source is allowed to be called recursively.
1474 * see g_source_set_can_recurse().
1476 * Return value: whether recursion is allowed.
1479 g_source_get_can_recurse (GSource *source)
1481 g_return_val_if_fail (source != NULL, FALSE);
1483 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1488 * g_source_set_name:
1489 * @source: a #GSource
1490 * @name: debug name for the source
1492 * Sets a name for the source, used in debugging and profiling.
1493 * The name defaults to #NULL.
1495 * The source name should describe in a human-readable way
1496 * what the source does. For example, "X11 event queue"
1497 * or "GTK+ repaint idle handler" or whatever it is.
1499 * It is permitted to call this function multiple times, but is not
1500 * recommended due to the potential performance impact. For example,
1501 * one could change the name in the "check" function of a #GSourceFuncs
1502 * to include details like the event type in the source name.
1507 g_source_set_name (GSource *source,
1510 g_return_if_fail (source != NULL);
1512 /* setting back to NULL is allowed, just because it's
1513 * weird if get_name can return NULL but you can't
1517 g_free (source->name);
1518 source->name = g_strdup (name);
1522 * g_source_get_name:
1523 * @source: a #GSource
1525 * Gets a name for the source, used in debugging and profiling.
1526 * The name may be #NULL if it has never been set with
1527 * g_source_set_name().
1529 * Return value: the name of the source
1533 g_source_get_name (GSource *source)
1535 g_return_val_if_fail (source != NULL, NULL);
1537 return source->name;
1541 * g_source_set_name_by_id:
1542 * @tag: a #GSource ID
1543 * @name: debug name for the source
1545 * Sets the name of a source using its ID.
1547 * This is a convenience utility to set source names from the return
1548 * value of g_idle_add(), g_timeout_add(), etc.
1553 g_source_set_name_by_id (guint tag,
1558 g_return_if_fail (tag > 0);
1560 source = g_main_context_find_source_by_id (NULL, tag);
1564 g_source_set_name (source, name);
1570 * @source: a #GSource
1572 * Increases the reference count on a source by one.
1574 * Return value: @source
1577 g_source_ref (GSource *source)
1579 GMainContext *context;
1581 g_return_val_if_fail (source != NULL, NULL);
1583 context = source->context;
1586 LOCK_CONTEXT (context);
1588 source->ref_count++;
1591 UNLOCK_CONTEXT (context);
1596 /* g_source_unref() but possible to call within context lock
1599 g_source_unref_internal (GSource *source,
1600 GMainContext *context,
1603 gpointer old_cb_data = NULL;
1604 GSourceCallbackFuncs *old_cb_funcs = NULL;
1606 g_return_if_fail (source != NULL);
1608 if (!have_lock && context)
1609 LOCK_CONTEXT (context);
1611 source->ref_count--;
1612 if (source->ref_count == 0)
1614 old_cb_data = source->callback_data;
1615 old_cb_funcs = source->callback_funcs;
1617 source->callback_data = NULL;
1618 source->callback_funcs = NULL;
1622 if (!SOURCE_DESTROYED (source))
1623 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
1624 g_source_list_remove (source, context);
1627 if (source->source_funcs->finalize)
1630 UNLOCK_CONTEXT (context);
1631 source->source_funcs->finalize (source);
1633 LOCK_CONTEXT (context);
1636 g_free (source->name);
1637 source->name = NULL;
1639 g_slist_free (source->poll_fds);
1640 source->poll_fds = NULL;
1644 g_slice_free (GSourcePrivate, source->priv);
1645 source->priv = NULL;
1651 if (!have_lock && context)
1652 UNLOCK_CONTEXT (context);
1657 UNLOCK_CONTEXT (context);
1659 old_cb_funcs->unref (old_cb_data);
1662 LOCK_CONTEXT (context);
1668 * @source: a #GSource
1670 * Decreases the reference count of a source by one. If the
1671 * resulting reference count is zero the source and associated
1672 * memory will be destroyed.
1675 g_source_unref (GSource *source)
1677 g_return_if_fail (source != NULL);
1679 g_source_unref_internal (source, source->context, FALSE);
1683 * g_main_context_find_source_by_id:
1684 * @context: a #GMainContext (if %NULL, the default context will be used)
1685 * @source_id: the source ID, as returned by g_source_get_id().
1687 * Finds a #GSource given a pair of context and ID.
1689 * Return value: (transfer none): the #GSource if found, otherwise, %NULL
1692 g_main_context_find_source_by_id (GMainContext *context,
1697 g_return_val_if_fail (source_id > 0, NULL);
1699 if (context == NULL)
1700 context = g_main_context_default ();
1702 LOCK_CONTEXT (context);
1704 source = context->source_list;
1707 if (!SOURCE_DESTROYED (source) &&
1708 source->source_id == source_id)
1710 source = source->next;
1713 UNLOCK_CONTEXT (context);
1719 * g_main_context_find_source_by_funcs_user_data:
1720 * @context: a #GMainContext (if %NULL, the default context will be used).
1721 * @funcs: the @source_funcs passed to g_source_new().
1722 * @user_data: the user data from the callback.
1724 * Finds a source with the given source functions and user data. If
1725 * multiple sources exist with the same source function and user data,
1726 * the first one found will be returned.
1728 * Return value: (transfer none): the source, if one was found, otherwise %NULL
1731 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1732 GSourceFuncs *funcs,
1737 g_return_val_if_fail (funcs != NULL, NULL);
1739 if (context == NULL)
1740 context = g_main_context_default ();
1742 LOCK_CONTEXT (context);
1744 source = context->source_list;
1747 if (!SOURCE_DESTROYED (source) &&
1748 source->source_funcs == funcs &&
1749 source->callback_funcs)
1751 GSourceFunc callback;
1752 gpointer callback_data;
1754 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1756 if (callback_data == user_data)
1759 source = source->next;
1762 UNLOCK_CONTEXT (context);
1768 * g_main_context_find_source_by_user_data:
1769 * @context: a #GMainContext
1770 * @user_data: the user_data for the callback.
1772 * Finds a source with the given user data for the callback. If
1773 * multiple sources exist with the same user data, the first
1774 * one found will be returned.
1776 * Return value: (transfer none): the source, if one was found, otherwise %NULL
1779 g_main_context_find_source_by_user_data (GMainContext *context,
1784 if (context == NULL)
1785 context = g_main_context_default ();
1787 LOCK_CONTEXT (context);
1789 source = context->source_list;
1792 if (!SOURCE_DESTROYED (source) &&
1793 source->callback_funcs)
1795 GSourceFunc callback;
1796 gpointer callback_data = NULL;
1798 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1800 if (callback_data == user_data)
1803 source = source->next;
1806 UNLOCK_CONTEXT (context);
1813 * @tag: the ID of the source to remove.
1815 * Removes the source with the given id from the default main context.
1817 * a #GSource is given by g_source_get_id(), or will be returned by the
1818 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1819 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1820 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1822 * See also g_source_destroy(). You must use g_source_destroy() for sources
1823 * added to a non-default main context.
1825 * Return value: %TRUE if the source was found and removed.
1828 g_source_remove (guint tag)
1832 g_return_val_if_fail (tag > 0, FALSE);
1834 source = g_main_context_find_source_by_id (NULL, tag);
1836 g_source_destroy (source);
1838 return source != NULL;
1842 * g_source_remove_by_user_data:
1843 * @user_data: the user_data for the callback.
1845 * Removes a source from the default main loop context given the user
1846 * data for the callback. If multiple sources exist with the same user
1847 * data, only one will be destroyed.
1849 * Return value: %TRUE if a source was found and removed.
1852 g_source_remove_by_user_data (gpointer user_data)
1856 source = g_main_context_find_source_by_user_data (NULL, user_data);
1859 g_source_destroy (source);
1867 * g_source_remove_by_funcs_user_data:
1868 * @funcs: The @source_funcs passed to g_source_new()
1869 * @user_data: the user data for the callback
1871 * Removes a source from the default main loop context given the
1872 * source functions and user data. If multiple sources exist with the
1873 * same source functions and user data, only one will be destroyed.
1875 * Return value: %TRUE if a source was found and removed.
1878 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1883 g_return_val_if_fail (funcs != NULL, FALSE);
1885 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1888 g_source_destroy (source);
1896 * g_get_current_time:
1897 * @result: #GTimeVal structure in which to store current time.
1899 * Equivalent to the UNIX gettimeofday() function, but portable.
1901 * You may find g_get_real_time() to be more convenient.
1904 g_get_current_time (GTimeVal *result)
1909 g_return_if_fail (result != NULL);
1911 /*this is required on alpha, there the timeval structs are int's
1912 not longs and a cast only would fail horribly*/
1913 gettimeofday (&r, NULL);
1914 result->tv_sec = r.tv_sec;
1915 result->tv_usec = r.tv_usec;
1920 g_return_if_fail (result != NULL);
1922 GetSystemTimeAsFileTime (&ft);
1923 memmove (&time64, &ft, sizeof (FILETIME));
1925 /* Convert from 100s of nanoseconds since 1601-01-01
1926 * to Unix epoch. Yes, this is Y2038 unsafe.
1928 time64 -= G_GINT64_CONSTANT (116444736000000000);
1931 result->tv_sec = time64 / 1000000;
1932 result->tv_usec = time64 % 1000000;
1939 * Queries the system wall-clock time.
1941 * This call is functionally equivalent to g_get_current_time() except
1942 * that the return value is often more convenient than dealing with a
1945 * You should only use this call if you are actually interested in the real
1946 * wall-clock time. g_get_monotonic_time() is probably more useful for
1947 * measuring intervals.
1949 * Returns: the number of microseconds since January 1, 1970 UTC.
1954 g_get_real_time (void)
1958 g_get_current_time (&tv);
1960 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
1964 * g_get_monotonic_time:
1966 * Queries the system monotonic time, if available.
1968 * On POSIX systems with clock_gettime() and %CLOCK_MONOTONIC this call
1969 * is a very shallow wrapper for that. Otherwise, we make a best effort
1970 * that probably involves returning the wall clock time (with at least
1971 * microsecond accuracy, subject to the limitations of the OS kernel).
1973 * It's important to note that POSIX %CLOCK_MONOTONIC does not count
1974 * time spent while the machine is suspended.
1976 * On Windows, "limitations of the OS kernel" is a rather substantial
1977 * statement. Depending on the configuration of the system, the wall
1978 * clock time is updated as infrequently as 64 times a second (which
1979 * is approximately every 16ms).
1981 * Returns: the monotonic time, in microseconds
1986 g_get_monotonic_time (void)
1988 #ifdef HAVE_CLOCK_GETTIME
1989 /* librt clock_gettime() is our first choice */
1991 #ifdef HAVE_MONOTONIC_CLOCK
1992 static volatile gsize clockid = 0;
1994 static clockid_t clockid = CLOCK_REALTIME;
1998 #ifdef HAVE_MONOTONIC_CLOCK
1999 if (g_once_init_enter (&clockid))
2001 clockid_t best_clockid;
2003 if (sysconf (_SC_MONOTONIC_CLOCK) >= 0)
2004 best_clockid = CLOCK_MONOTONIC;
2006 best_clockid = CLOCK_REALTIME;
2007 g_once_init_leave (&clockid, (gsize)best_clockid);
2011 clock_gettime (clockid, &ts);
2013 /* In theory monotonic time can have any epoch.
2015 * glib presently assumes the following:
2017 * 1) The epoch comes some time after the birth of Jesus of Nazareth, but
2018 * not more than 10000 years later.
2020 * 2) The current time also falls sometime within this range.
2022 * These two reasonable assumptions leave us with a maximum deviation from
2023 * the epoch of 10000 years, or 315569520000000000 seconds.
2025 * If we restrict ourselves to this range then the number of microseconds
2026 * will always fit well inside the constraints of a int64 (by a factor of
2029 * If you actually hit the following assertion, probably you should file a
2030 * bug against your operating system for being excessively silly.
2032 g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts.tv_sec &&
2033 ts.tv_sec < G_GINT64_CONSTANT (315569520000000000));
2035 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2038 /* It may look like we are discarding accuracy on Windows (since its
2039 * current time is expressed in 100s of nanoseconds) but according to
2040 * many sources, the time is only updated 64 times per second, so
2041 * microsecond accuracy is more than enough.
2046 g_get_current_time (&tv);
2048 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2054 g_main_dispatch_free (gpointer dispatch)
2056 g_slice_free (GMainDispatch, dispatch);
2059 /* Running the main loop */
2061 static GMainDispatch *
2064 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
2065 GMainDispatch *dispatch = g_static_private_get (&depth_private);
2068 dispatch = g_slice_new0 (GMainDispatch);
2069 g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
2078 * Returns the depth of the stack of calls to
2079 * g_main_context_dispatch() on any #GMainContext in the current thread.
2080 * That is, when called from the toplevel, it gives 0. When
2081 * called from within a callback from g_main_context_iteration()
2082 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2083 * a callback to a recursive call to g_main_context_iteration(),
2084 * it returns 2. And so forth.
2086 * This function is useful in a situation like the following:
2087 * Imagine an extremely simple "garbage collected" system.
2090 * static GList *free_list;
2093 * allocate_memory (gsize size)
2095 * gpointer result = g_malloc (size);
2096 * free_list = g_list_prepend (free_list, result);
2101 * free_allocated_memory (void)
2104 * for (l = free_list; l; l = l->next);
2106 * g_list_free (free_list);
2114 * g_main_context_iteration (NULL, TRUE);
2115 * free_allocated_memory();
2119 * This works from an application, however, if you want to do the same
2120 * thing from a library, it gets more difficult, since you no longer
2121 * control the main loop. You might think you can simply use an idle
2122 * function to make the call to free_allocated_memory(), but that
2123 * doesn't work, since the idle function could be called from a
2124 * recursive callback. This can be fixed by using g_main_depth()
2128 * allocate_memory (gsize size)
2130 * FreeListBlock *block = g_new (FreeListBlock, 1);
2131 * block->mem = g_malloc (size);
2132 * block->depth = g_main_depth ();
2133 * free_list = g_list_prepend (free_list, block);
2134 * return block->mem;
2138 * free_allocated_memory (void)
2142 * int depth = g_main_depth ();
2143 * for (l = free_list; l; );
2145 * GList *next = l->next;
2146 * FreeListBlock *block = l->data;
2147 * if (block->depth > depth)
2149 * g_free (block->mem);
2151 * free_list = g_list_delete_link (free_list, l);
2159 * There is a temptation to use g_main_depth() to solve
2160 * problems with reentrancy. For instance, while waiting for data
2161 * to be received from the network in response to a menu item,
2162 * the menu item might be selected again. It might seem that
2163 * one could make the menu item's callback return immediately
2164 * and do nothing if g_main_depth() returns a value greater than 1.
2165 * However, this should be avoided since the user then sees selecting
2166 * the menu item do nothing. Furthermore, you'll find yourself adding
2167 * these checks all over your code, since there are doubtless many,
2168 * many things that the user could do. Instead, you can use the
2169 * following techniques:
2174 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
2175 * the user from interacting with elements while the main
2176 * loop is recursing.
2181 * Avoid main loop recursion in situations where you can't handle
2182 * arbitrary callbacks. Instead, structure your code so that you
2183 * simply return to the main loop and then get called again when
2184 * there is more work to do.
2189 * Return value: The main loop recursion level in the current thread
2194 GMainDispatch *dispatch = get_dispatch ();
2195 return dispatch->depth;
2199 * g_main_current_source:
2201 * Returns the currently firing source for this thread.
2203 * Return value: (transfer none): The currently firing source or %NULL.
2208 g_main_current_source (void)
2210 GMainDispatch *dispatch = get_dispatch ();
2211 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
2215 * g_source_is_destroyed:
2216 * @source: a #GSource
2218 * Returns whether @source has been destroyed.
2220 * This is important when you operate upon your objects
2221 * from within idle handlers, but may have freed the object
2222 * before the dispatch of your idle handler.
2226 * idle_callback (gpointer data)
2228 * SomeWidget *self = data;
2230 * GDK_THREADS_ENTER (<!-- -->);
2231 * /<!-- -->* do stuff with self *<!-- -->/
2232 * self->idle_id = 0;
2233 * GDK_THREADS_LEAVE (<!-- -->);
2239 * some_widget_do_stuff_later (SomeWidget *self)
2241 * self->idle_id = g_idle_add (idle_callback, self);
2245 * some_widget_finalize (GObject *object)
2247 * SomeWidget *self = SOME_WIDGET (object);
2249 * if (self->idle_id)
2250 * g_source_remove (self->idle_id);
2252 * G_OBJECT_CLASS (parent_class)->finalize (object);
2256 * This will fail in a multi-threaded application if the
2257 * widget is destroyed before the idle handler fires due
2258 * to the use after free in the callback. A solution, to
2259 * this particular problem, is to check to if the source
2260 * has already been destroy within the callback.
2264 * idle_callback (gpointer data)
2266 * SomeWidget *self = data;
2268 * GDK_THREADS_ENTER ();
2269 * if (!g_source_is_destroyed (g_main_current_source ()))
2271 * /<!-- -->* do stuff with self *<!-- -->/
2273 * GDK_THREADS_LEAVE ();
2279 * Return value: %TRUE if the source has been destroyed
2284 g_source_is_destroyed (GSource *source)
2286 return SOURCE_DESTROYED (source);
2289 /* Temporarily remove all this source's file descriptors from the
2290 * poll(), so that if data comes available for one of the file descriptors
2291 * we don't continually spin in the poll()
2293 /* HOLDS: source->context's lock */
2295 block_source (GSource *source)
2299 g_return_if_fail (!SOURCE_BLOCKED (source));
2301 tmp_list = source->poll_fds;
2304 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2305 tmp_list = tmp_list->next;
2309 /* HOLDS: source->context's lock */
2311 unblock_source (GSource *source)
2315 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
2316 g_return_if_fail (!SOURCE_DESTROYED (source));
2318 tmp_list = source->poll_fds;
2321 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2322 tmp_list = tmp_list->next;
2326 /* HOLDS: context's lock */
2328 g_main_dispatch (GMainContext *context)
2330 GMainDispatch *current = get_dispatch ();
2333 for (i = 0; i < context->pending_dispatches->len; i++)
2335 GSource *source = context->pending_dispatches->pdata[i];
2337 context->pending_dispatches->pdata[i] = NULL;
2340 source->flags &= ~G_SOURCE_READY;
2342 if (!SOURCE_DESTROYED (source))
2344 gboolean was_in_call;
2345 gpointer user_data = NULL;
2346 GSourceFunc callback = NULL;
2347 GSourceCallbackFuncs *cb_funcs;
2349 gboolean need_destroy;
2351 gboolean (*dispatch) (GSource *,
2354 GSList current_source_link;
2356 dispatch = source->source_funcs->dispatch;
2357 cb_funcs = source->callback_funcs;
2358 cb_data = source->callback_data;
2361 cb_funcs->ref (cb_data);
2363 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2364 block_source (source);
2366 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2367 source->flags |= G_HOOK_FLAG_IN_CALL;
2370 cb_funcs->get (cb_data, source, &callback, &user_data);
2372 UNLOCK_CONTEXT (context);
2375 /* The on-stack allocation of the GSList is unconventional, but
2376 * we know that the lifetime of the link is bounded to this
2377 * function as the link is kept in a thread specific list and
2378 * not manipulated outside of this function and its descendants.
2379 * Avoiding the overhead of a g_slist_alloc() is useful as many
2380 * applications do little more than dispatch events.
2382 * This is a performance hack - do not revert to g_slist_prepend()!
2384 current_source_link.data = source;
2385 current_source_link.next = current->dispatching_sources;
2386 current->dispatching_sources = ¤t_source_link;
2387 need_destroy = ! dispatch (source,
2390 g_assert (current->dispatching_sources == ¤t_source_link);
2391 current->dispatching_sources = current_source_link.next;
2395 cb_funcs->unref (cb_data);
2397 LOCK_CONTEXT (context);
2400 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2402 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2403 !SOURCE_DESTROYED (source))
2404 unblock_source (source);
2406 /* Note: this depends on the fact that we can't switch
2407 * sources from one main context to another
2409 if (need_destroy && !SOURCE_DESTROYED (source))
2411 g_assert (source->context == context);
2412 g_source_destroy_internal (source, context, TRUE);
2416 SOURCE_UNREF (source, context);
2419 g_ptr_array_set_size (context->pending_dispatches, 0);
2422 /* Holds context's lock */
2423 static inline GSource *
2424 next_valid_source (GMainContext *context,
2427 GSource *new_source = source ? source->next : context->source_list;
2431 if (!SOURCE_DESTROYED (new_source))
2433 new_source->ref_count++;
2437 new_source = new_source->next;
2441 SOURCE_UNREF (source, context);
2447 * g_main_context_acquire:
2448 * @context: a #GMainContext
2450 * Tries to become the owner of the specified context.
2451 * If some other thread is the owner of the context,
2452 * returns %FALSE immediately. Ownership is properly
2453 * recursive: the owner can require ownership again
2454 * and will release ownership when g_main_context_release()
2455 * is called as many times as g_main_context_acquire().
2457 * You must be the owner of a context before you
2458 * can call g_main_context_prepare(), g_main_context_query(),
2459 * g_main_context_check(), g_main_context_dispatch().
2461 * Return value: %TRUE if the operation succeeded, and
2462 * this thread is now the owner of @context.
2465 g_main_context_acquire (GMainContext *context)
2467 gboolean result = FALSE;
2468 GThread *self = G_THREAD_SELF;
2470 if (context == NULL)
2471 context = g_main_context_default ();
2473 LOCK_CONTEXT (context);
2475 if (!context->owner)
2477 context->owner = self;
2478 g_assert (context->owner_count == 0);
2481 if (context->owner == self)
2483 context->owner_count++;
2487 UNLOCK_CONTEXT (context);
2493 * g_main_context_release:
2494 * @context: a #GMainContext
2496 * Releases ownership of a context previously acquired by this thread
2497 * with g_main_context_acquire(). If the context was acquired multiple
2498 * times, the ownership will be released only when g_main_context_release()
2499 * is called as many times as it was acquired.
2502 g_main_context_release (GMainContext *context)
2504 if (context == NULL)
2505 context = g_main_context_default ();
2507 LOCK_CONTEXT (context);
2509 context->owner_count--;
2510 if (context->owner_count == 0)
2512 context->owner = NULL;
2514 if (context->waiters)
2516 GMainWaiter *waiter = context->waiters->data;
2517 gboolean loop_internal_waiter = (waiter->mutex == &context->mutex);
2518 context->waiters = g_slist_delete_link (context->waiters,
2520 if (!loop_internal_waiter)
2521 g_mutex_lock (waiter->mutex);
2523 g_cond_signal (waiter->cond);
2525 if (!loop_internal_waiter)
2526 g_mutex_unlock (waiter->mutex);
2530 UNLOCK_CONTEXT (context);
2534 * g_main_context_wait:
2535 * @context: a #GMainContext
2536 * @cond: a condition variable
2537 * @mutex: a mutex, currently held
2539 * Tries to become the owner of the specified context,
2540 * as with g_main_context_acquire(). But if another thread
2541 * is the owner, atomically drop @mutex and wait on @cond until
2542 * that owner releases ownership or until @cond is signaled, then
2543 * try again (once) to become the owner.
2545 * Return value: %TRUE if the operation succeeded, and
2546 * this thread is now the owner of @context.
2549 g_main_context_wait (GMainContext *context,
2553 gboolean result = FALSE;
2554 GThread *self = G_THREAD_SELF;
2555 gboolean loop_internal_waiter;
2557 if (context == NULL)
2558 context = g_main_context_default ();
2560 loop_internal_waiter = (mutex == &context->mutex);
2562 if (!loop_internal_waiter)
2563 LOCK_CONTEXT (context);
2565 if (context->owner && context->owner != self)
2570 waiter.mutex = mutex;
2572 context->waiters = g_slist_append (context->waiters, &waiter);
2574 if (!loop_internal_waiter)
2575 UNLOCK_CONTEXT (context);
2576 g_cond_wait (cond, mutex);
2577 if (!loop_internal_waiter)
2578 LOCK_CONTEXT (context);
2580 context->waiters = g_slist_remove (context->waiters, &waiter);
2583 if (!context->owner)
2585 context->owner = self;
2586 g_assert (context->owner_count == 0);
2589 if (context->owner == self)
2591 context->owner_count++;
2595 if (!loop_internal_waiter)
2596 UNLOCK_CONTEXT (context);
2602 * g_main_context_prepare:
2603 * @context: a #GMainContext
2604 * @priority: location to store priority of highest priority
2605 * source already ready.
2607 * Prepares to poll sources within a main loop. The resulting information
2608 * for polling is determined by calling g_main_context_query ().
2610 * Return value: %TRUE if some source is ready to be dispatched
2614 g_main_context_prepare (GMainContext *context,
2619 gint current_priority = G_MAXINT;
2622 if (context == NULL)
2623 context = g_main_context_default ();
2625 LOCK_CONTEXT (context);
2627 context->time_is_fresh = FALSE;
2629 if (context->in_check_or_prepare)
2631 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2632 "prepare() member.");
2633 UNLOCK_CONTEXT (context);
2638 /* If recursing, finish up current dispatch, before starting over */
2639 if (context->pending_dispatches)
2642 g_main_dispatch (context, ¤t_time);
2644 UNLOCK_CONTEXT (context);
2649 /* If recursing, clear list of pending dispatches */
2651 for (i = 0; i < context->pending_dispatches->len; i++)
2653 if (context->pending_dispatches->pdata[i])
2654 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2656 g_ptr_array_set_size (context->pending_dispatches, 0);
2658 /* Prepare all sources */
2660 context->timeout = -1;
2662 source = next_valid_source (context, NULL);
2665 gint source_timeout = -1;
2667 if ((n_ready > 0) && (source->priority > current_priority))
2669 SOURCE_UNREF (source, context);
2672 if (SOURCE_BLOCKED (source))
2675 if (!(source->flags & G_SOURCE_READY))
2678 gboolean (*prepare) (GSource *source,
2681 prepare = source->source_funcs->prepare;
2682 context->in_check_or_prepare++;
2683 UNLOCK_CONTEXT (context);
2685 result = (*prepare) (source, &source_timeout);
2687 LOCK_CONTEXT (context);
2688 context->in_check_or_prepare--;
2692 GSource *ready_source = source;
2694 while (ready_source)
2696 ready_source->flags |= G_SOURCE_READY;
2697 ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2702 if (source->flags & G_SOURCE_READY)
2705 current_priority = source->priority;
2706 context->timeout = 0;
2709 if (source_timeout >= 0)
2711 if (context->timeout < 0)
2712 context->timeout = source_timeout;
2714 context->timeout = MIN (context->timeout, source_timeout);
2718 source = next_valid_source (context, source);
2721 UNLOCK_CONTEXT (context);
2724 *priority = current_priority;
2726 return (n_ready > 0);
2730 * g_main_context_query:
2731 * @context: a #GMainContext
2732 * @max_priority: maximum priority source to check
2733 * @timeout_: (out): location to store timeout to be used in polling
2734 * @fds: (out caller-allocates) (array length=n_fds): location to
2735 * store #GPollFD records that need to be polled.
2736 * @n_fds: length of @fds.
2738 * Determines information necessary to poll this main loop.
2740 * Return value: the number of records actually stored in @fds,
2741 * or, if more than @n_fds records need to be stored, the number
2742 * of records that need to be stored.
2745 g_main_context_query (GMainContext *context,
2754 LOCK_CONTEXT (context);
2756 pollrec = context->poll_records;
2758 while (pollrec && max_priority >= pollrec->priority)
2760 /* We need to include entries with fd->events == 0 in the array because
2761 * otherwise if the application changes fd->events behind our back and
2762 * makes it non-zero, we'll be out of sync when we check the fds[] array.
2763 * (Changing fd->events after adding an FD wasn't an anticipated use of
2764 * this API, but it occurs in practice.) */
2767 fds[n_poll].fd = pollrec->fd->fd;
2768 /* In direct contradiction to the Unix98 spec, IRIX runs into
2769 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2770 * flags in the events field of the pollfd while it should
2771 * just ignoring them. So we mask them out here.
2773 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2774 fds[n_poll].revents = 0;
2777 pollrec = pollrec->next;
2781 context->poll_changed = FALSE;
2785 *timeout = context->timeout;
2787 context->time_is_fresh = FALSE;
2790 UNLOCK_CONTEXT (context);
2796 * g_main_context_check:
2797 * @context: a #GMainContext
2798 * @max_priority: the maximum numerical priority of sources to check
2799 * @fds: (array length=n_fds): array of #GPollFD's that was passed to
2800 * the last call to g_main_context_query()
2801 * @n_fds: return value of g_main_context_query()
2803 * Passes the results of polling back to the main loop.
2805 * Return value: %TRUE if some sources are ready to be dispatched.
2808 g_main_context_check (GMainContext *context,
2818 LOCK_CONTEXT (context);
2820 if (context->in_check_or_prepare)
2822 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2823 "prepare() member.");
2824 UNLOCK_CONTEXT (context);
2828 if (context->wake_up_rec.events)
2829 g_wakeup_acknowledge (context->wakeup);
2831 /* If the set of poll file descriptors changed, bail out
2832 * and let the main loop rerun
2834 if (context->poll_changed)
2836 UNLOCK_CONTEXT (context);
2840 pollrec = context->poll_records;
2844 if (pollrec->fd->events)
2845 pollrec->fd->revents = fds[i].revents;
2847 pollrec = pollrec->next;
2851 source = next_valid_source (context, NULL);
2854 if ((n_ready > 0) && (source->priority > max_priority))
2856 SOURCE_UNREF (source, context);
2859 if (SOURCE_BLOCKED (source))
2862 if (!(source->flags & G_SOURCE_READY))
2865 gboolean (*check) (GSource *source);
2867 check = source->source_funcs->check;
2869 context->in_check_or_prepare++;
2870 UNLOCK_CONTEXT (context);
2872 result = (*check) (source);
2874 LOCK_CONTEXT (context);
2875 context->in_check_or_prepare--;
2879 GSource *ready_source = source;
2881 while (ready_source)
2883 ready_source->flags |= G_SOURCE_READY;
2884 ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2889 if (source->flags & G_SOURCE_READY)
2891 source->ref_count++;
2892 g_ptr_array_add (context->pending_dispatches, source);
2896 /* never dispatch sources with less priority than the first
2897 * one we choose to dispatch
2899 max_priority = source->priority;
2903 source = next_valid_source (context, source);
2906 UNLOCK_CONTEXT (context);
2912 * g_main_context_dispatch:
2913 * @context: a #GMainContext
2915 * Dispatches all pending sources.
2918 g_main_context_dispatch (GMainContext *context)
2920 LOCK_CONTEXT (context);
2922 if (context->pending_dispatches->len > 0)
2924 g_main_dispatch (context);
2927 UNLOCK_CONTEXT (context);
2930 /* HOLDS context lock */
2932 g_main_context_iterate (GMainContext *context,
2939 gboolean some_ready;
2940 gint nfds, allocated_nfds;
2941 GPollFD *fds = NULL;
2943 UNLOCK_CONTEXT (context);
2945 if (!g_main_context_acquire (context))
2947 gboolean got_ownership;
2949 LOCK_CONTEXT (context);
2954 got_ownership = g_main_context_wait (context,
2962 LOCK_CONTEXT (context);
2964 if (!context->cached_poll_array)
2966 context->cached_poll_array_size = context->n_poll_records;
2967 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2970 allocated_nfds = context->cached_poll_array_size;
2971 fds = context->cached_poll_array;
2973 UNLOCK_CONTEXT (context);
2975 g_main_context_prepare (context, &max_priority);
2977 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
2978 allocated_nfds)) > allocated_nfds)
2980 LOCK_CONTEXT (context);
2982 context->cached_poll_array_size = allocated_nfds = nfds;
2983 context->cached_poll_array = fds = g_new (GPollFD, nfds);
2984 UNLOCK_CONTEXT (context);
2990 g_assert (!g_main_context_fork_detected);
2991 g_main_context_poll (context, timeout, max_priority, fds, nfds);
2993 some_ready = g_main_context_check (context, max_priority, fds, nfds);
2996 g_main_context_dispatch (context);
2998 g_main_context_release (context);
3000 LOCK_CONTEXT (context);
3006 * g_main_context_pending:
3007 * @context: a #GMainContext (if %NULL, the default context will be used)
3009 * Checks if any sources have pending events for the given context.
3011 * Return value: %TRUE if events are pending.
3014 g_main_context_pending (GMainContext *context)
3019 context = g_main_context_default();
3021 LOCK_CONTEXT (context);
3022 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3023 UNLOCK_CONTEXT (context);
3029 * g_main_context_iteration:
3030 * @context: a #GMainContext (if %NULL, the default context will be used)
3031 * @may_block: whether the call may block.
3033 * Runs a single iteration for the given main loop. This involves
3034 * checking to see if any event sources are ready to be processed,
3035 * then if no events sources are ready and @may_block is %TRUE, waiting
3036 * for a source to become ready, then dispatching the highest priority
3037 * events sources that are ready. Otherwise, if @may_block is %FALSE
3038 * sources are not waited to become ready, only those highest priority
3039 * events sources will be dispatched (if any), that are ready at this
3040 * given moment without further waiting.
3042 * Note that even when @may_block is %TRUE, it is still possible for
3043 * g_main_context_iteration() to return %FALSE, since the the wait may
3044 * be interrupted for other reasons than an event source becoming ready.
3046 * Return value: %TRUE if events were dispatched.
3049 g_main_context_iteration (GMainContext *context, gboolean may_block)
3054 context = g_main_context_default();
3056 LOCK_CONTEXT (context);
3057 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3058 UNLOCK_CONTEXT (context);
3065 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
3066 * @is_running: set to %TRUE to indicate that the loop is running. This
3067 * is not very important since calling g_main_loop_run() will set this to
3070 * Creates a new #GMainLoop structure.
3072 * Return value: a new #GMainLoop.
3075 g_main_loop_new (GMainContext *context,
3076 gboolean is_running)
3081 context = g_main_context_default();
3083 g_main_context_ref (context);
3085 loop = g_new0 (GMainLoop, 1);
3086 loop->context = context;
3087 loop->is_running = is_running != FALSE;
3088 loop->ref_count = 1;
3095 * @loop: a #GMainLoop
3097 * Increases the reference count on a #GMainLoop object by one.
3099 * Return value: @loop
3102 g_main_loop_ref (GMainLoop *loop)
3104 g_return_val_if_fail (loop != NULL, NULL);
3105 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3107 g_atomic_int_inc (&loop->ref_count);
3113 * g_main_loop_unref:
3114 * @loop: a #GMainLoop
3116 * Decreases the reference count on a #GMainLoop object by one. If
3117 * the result is zero, free the loop and free all associated memory.
3120 g_main_loop_unref (GMainLoop *loop)
3122 g_return_if_fail (loop != NULL);
3123 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3125 if (!g_atomic_int_dec_and_test (&loop->ref_count))
3128 g_main_context_unref (loop->context);
3134 * @loop: a #GMainLoop
3136 * Runs a main loop until g_main_loop_quit() is called on the loop.
3137 * If this is called for the thread of the loop's #GMainContext,
3138 * it will process events from the loop, otherwise it will
3142 g_main_loop_run (GMainLoop *loop)
3144 GThread *self = G_THREAD_SELF;
3146 g_return_if_fail (loop != NULL);
3147 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3149 if (!g_main_context_acquire (loop->context))
3151 gboolean got_ownership = FALSE;
3153 /* Another thread owns this context */
3154 LOCK_CONTEXT (loop->context);
3156 g_atomic_int_inc (&loop->ref_count);
3158 if (!loop->is_running)
3159 loop->is_running = TRUE;
3161 while (loop->is_running && !got_ownership)
3162 got_ownership = g_main_context_wait (loop->context,
3163 &loop->context->cond,
3164 &loop->context->mutex);
3166 if (!loop->is_running)
3168 UNLOCK_CONTEXT (loop->context);
3170 g_main_context_release (loop->context);
3171 g_main_loop_unref (loop);
3175 g_assert (got_ownership);
3178 LOCK_CONTEXT (loop->context);
3180 if (loop->context->in_check_or_prepare)
3182 g_warning ("g_main_loop_run(): called recursively from within a source's "
3183 "check() or prepare() member, iteration not possible.");
3187 g_atomic_int_inc (&loop->ref_count);
3188 loop->is_running = TRUE;
3189 while (loop->is_running)
3190 g_main_context_iterate (loop->context, TRUE, TRUE, self);
3192 UNLOCK_CONTEXT (loop->context);
3194 g_main_context_release (loop->context);
3196 g_main_loop_unref (loop);
3201 * @loop: a #GMainLoop
3203 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3204 * for the loop will return.
3206 * Note that sources that have already been dispatched when
3207 * g_main_loop_quit() is called will still be executed.
3210 g_main_loop_quit (GMainLoop *loop)
3212 g_return_if_fail (loop != NULL);
3213 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3215 LOCK_CONTEXT (loop->context);
3216 loop->is_running = FALSE;
3217 g_wakeup_signal (loop->context->wakeup);
3219 g_cond_broadcast (&loop->context->cond);
3221 UNLOCK_CONTEXT (loop->context);
3225 * g_main_loop_is_running:
3226 * @loop: a #GMainLoop.
3228 * Checks to see if the main loop is currently being run via g_main_loop_run().
3230 * Return value: %TRUE if the mainloop is currently being run.
3233 g_main_loop_is_running (GMainLoop *loop)
3235 g_return_val_if_fail (loop != NULL, FALSE);
3236 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3238 return loop->is_running;
3242 * g_main_loop_get_context:
3243 * @loop: a #GMainLoop.
3245 * Returns the #GMainContext of @loop.
3247 * Return value: (transfer none): the #GMainContext of @loop
3250 g_main_loop_get_context (GMainLoop *loop)
3252 g_return_val_if_fail (loop != NULL, NULL);
3253 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3255 return loop->context;
3258 /* HOLDS: context's lock */
3260 g_main_context_poll (GMainContext *context,
3266 #ifdef G_MAIN_POLL_DEBUG
3272 GPollFunc poll_func;
3274 if (n_fds || timeout != 0)
3276 #ifdef G_MAIN_POLL_DEBUG
3277 if (_g_main_poll_debug)
3279 g_print ("polling context=%p n=%d timeout=%d\n",
3280 context, n_fds, timeout);
3281 poll_timer = g_timer_new ();
3285 LOCK_CONTEXT (context);
3287 poll_func = context->poll_func;
3289 UNLOCK_CONTEXT (context);
3290 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3293 g_warning ("poll(2) failed due to: %s.",
3294 g_strerror (errno));
3296 /* If g_poll () returns -1, it has already called g_warning() */
3300 #ifdef G_MAIN_POLL_DEBUG
3301 if (_g_main_poll_debug)
3303 LOCK_CONTEXT (context);
3305 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3308 g_timer_elapsed (poll_timer, NULL));
3309 g_timer_destroy (poll_timer);
3310 pollrec = context->poll_records;
3312 while (pollrec != NULL)
3317 if (fds[i].fd == pollrec->fd->fd &&
3318 pollrec->fd->events &&
3321 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3322 if (fds[i].revents & G_IO_IN)
3324 if (fds[i].revents & G_IO_OUT)
3326 if (fds[i].revents & G_IO_PRI)
3328 if (fds[i].revents & G_IO_ERR)
3330 if (fds[i].revents & G_IO_HUP)
3332 if (fds[i].revents & G_IO_NVAL)
3338 pollrec = pollrec->next;
3342 UNLOCK_CONTEXT (context);
3345 } /* if (n_fds || timeout != 0) */
3349 * g_main_context_add_poll:
3350 * @context: a #GMainContext (or %NULL for the default context)
3351 * @fd: a #GPollFD structure holding information about a file
3352 * descriptor to watch.
3353 * @priority: the priority for this file descriptor which should be
3354 * the same as the priority used for g_source_attach() to ensure that the
3355 * file descriptor is polled whenever the results may be needed.
3357 * Adds a file descriptor to the set of file descriptors polled for
3358 * this context. This will very seldom be used directly. Instead
3359 * a typical event source will use g_source_add_poll() instead.
3362 g_main_context_add_poll (GMainContext *context,
3367 context = g_main_context_default ();
3369 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3370 g_return_if_fail (fd);
3372 LOCK_CONTEXT (context);
3373 g_main_context_add_poll_unlocked (context, priority, fd);
3374 UNLOCK_CONTEXT (context);
3377 /* HOLDS: main_loop_lock */
3379 g_main_context_add_poll_unlocked (GMainContext *context,
3383 GPollRec *prevrec, *nextrec;
3384 GPollRec *newrec = g_slice_new (GPollRec);
3386 /* This file descriptor may be checked before we ever poll */
3389 newrec->priority = priority;
3391 prevrec = context->poll_records_tail;
3393 while (prevrec && priority < prevrec->priority)
3396 prevrec = prevrec->prev;
3400 prevrec->next = newrec;
3402 context->poll_records = newrec;
3404 newrec->prev = prevrec;
3405 newrec->next = nextrec;
3408 nextrec->prev = newrec;
3410 context->poll_records_tail = newrec;
3412 context->n_poll_records++;
3414 context->poll_changed = TRUE;
3416 /* Now wake up the main loop if it is waiting in the poll() */
3417 g_wakeup_signal (context->wakeup);
3421 * g_main_context_remove_poll:
3422 * @context:a #GMainContext
3423 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3425 * Removes file descriptor from the set of file descriptors to be
3426 * polled for a particular context.
3429 g_main_context_remove_poll (GMainContext *context,
3433 context = g_main_context_default ();
3435 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3436 g_return_if_fail (fd);
3438 LOCK_CONTEXT (context);
3439 g_main_context_remove_poll_unlocked (context, fd);
3440 UNLOCK_CONTEXT (context);
3444 g_main_context_remove_poll_unlocked (GMainContext *context,
3447 GPollRec *pollrec, *prevrec, *nextrec;
3450 pollrec = context->poll_records;
3454 nextrec = pollrec->next;
3455 if (pollrec->fd == fd)
3457 if (prevrec != NULL)
3458 prevrec->next = nextrec;
3460 context->poll_records = nextrec;
3462 if (nextrec != NULL)
3463 nextrec->prev = prevrec;
3465 context->poll_records_tail = prevrec;
3467 g_slice_free (GPollRec, pollrec);
3469 context->n_poll_records--;
3476 context->poll_changed = TRUE;
3478 /* Now wake up the main loop if it is waiting in the poll() */
3479 g_wakeup_signal (context->wakeup);
3483 * g_source_get_current_time:
3484 * @source: a #GSource
3485 * @timeval: #GTimeVal structure in which to store current time.
3487 * This function ignores @source and is otherwise the same as
3488 * g_get_current_time().
3490 * Deprecated: 2.28: use g_source_get_time() instead
3493 g_source_get_current_time (GSource *source,
3496 g_get_current_time (timeval);
3500 * g_source_get_time:
3501 * @source: a #GSource
3503 * Gets the time to be used when checking this source. The advantage of
3504 * calling this function over calling g_get_monotonic_time() directly is
3505 * that when checking multiple sources, GLib can cache a single value
3506 * instead of having to repeatedly get the system monotonic time.
3508 * The time here is the system monotonic time, if available, or some
3509 * other reasonable alternative otherwise. See g_get_monotonic_time().
3511 * Returns: the monotonic time in microseconds
3516 g_source_get_time (GSource *source)
3518 GMainContext *context;
3521 g_return_val_if_fail (source->context != NULL, 0);
3523 context = source->context;
3525 LOCK_CONTEXT (context);
3527 if (!context->time_is_fresh)
3529 context->time = g_get_monotonic_time ();
3530 context->time_is_fresh = TRUE;
3533 result = context->time;
3535 UNLOCK_CONTEXT (context);
3541 * g_main_context_set_poll_func:
3542 * @context: a #GMainContext
3543 * @func: the function to call to poll all file descriptors
3545 * Sets the function to use to handle polling of file descriptors. It
3546 * will be used instead of the poll() system call
3547 * (or GLib's replacement function, which is used where
3548 * poll() isn't available).
3550 * This function could possibly be used to integrate the GLib event
3551 * loop with an external event loop.
3554 g_main_context_set_poll_func (GMainContext *context,
3558 context = g_main_context_default ();
3560 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3562 LOCK_CONTEXT (context);
3565 context->poll_func = func;
3567 context->poll_func = g_poll;
3569 UNLOCK_CONTEXT (context);
3573 * g_main_context_get_poll_func:
3574 * @context: a #GMainContext
3576 * Gets the poll function set by g_main_context_set_poll_func().
3578 * Return value: the poll function
3581 g_main_context_get_poll_func (GMainContext *context)
3586 context = g_main_context_default ();
3588 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3590 LOCK_CONTEXT (context);
3591 result = context->poll_func;
3592 UNLOCK_CONTEXT (context);
3598 * g_main_context_wakeup:
3599 * @context: a #GMainContext
3601 * If @context is currently waiting in a poll(), interrupt
3602 * the poll(), and continue the iteration process.
3605 g_main_context_wakeup (GMainContext *context)
3608 context = g_main_context_default ();
3610 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3612 g_wakeup_signal (context->wakeup);
3616 * g_main_context_is_owner:
3617 * @context: a #GMainContext
3619 * Determines whether this thread holds the (recursive)
3620 * ownership of this #GMainContext. This is useful to
3621 * know before waiting on another thread that may be
3622 * blocking to get ownership of @context.
3624 * Returns: %TRUE if current thread is owner of @context.
3629 g_main_context_is_owner (GMainContext *context)
3634 context = g_main_context_default ();
3636 LOCK_CONTEXT (context);
3637 is_owner = context->owner == G_THREAD_SELF;
3638 UNLOCK_CONTEXT (context);
3646 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3647 gint64 current_time)
3649 timeout_source->expiration = current_time +
3650 (guint64) timeout_source->interval * 1000;
3652 if (timeout_source->seconds)
3655 static gint timer_perturb = -1;
3657 if (timer_perturb == -1)
3660 * we want a per machine/session unique 'random' value; try the dbus
3661 * address first, that has a UUID in it. If there is no dbus, use the
3662 * hostname for hashing.
3664 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3665 if (!session_bus_address)
3666 session_bus_address = g_getenv ("HOSTNAME");
3667 if (session_bus_address)
3668 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
3673 /* We want the microseconds part of the timeout to land on the
3674 * 'timer_perturb' mark, but we need to make sure we don't try to
3675 * set the timeout in the past. We do this by ensuring that we
3676 * always only *increase* the expiration time by adding a full
3677 * second in the case that the microsecond portion decreases.
3679 timeout_source->expiration -= timer_perturb;
3681 remainder = timeout_source->expiration % 1000000;
3682 if (remainder >= 1000000/4)
3683 timeout_source->expiration += 1000000;
3685 timeout_source->expiration -= remainder;
3686 timeout_source->expiration += timer_perturb;
3691 g_timeout_prepare (GSource *source,
3694 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3695 gint64 now = g_source_get_time (source);
3697 if (now < timeout_source->expiration)
3699 /* Round up to ensure that we don't try again too early */
3700 *timeout = (timeout_source->expiration - now + 999) / 1000;
3709 g_timeout_check (GSource *source)
3711 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3712 gint64 now = g_source_get_time (source);
3714 return timeout_source->expiration <= now;
3718 g_timeout_dispatch (GSource *source,
3719 GSourceFunc callback,
3722 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3727 g_warning ("Timeout source dispatched without callback\n"
3728 "You must call g_source_set_callback().");
3732 again = callback (user_data);
3735 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
3741 * g_timeout_source_new:
3742 * @interval: the timeout interval in milliseconds.
3744 * Creates a new timeout source.
3746 * The source will not initially be associated with any #GMainContext
3747 * and must be added to one with g_source_attach() before it will be
3750 * The interval given is in terms of monotonic time, not wall clock
3751 * time. See g_get_monotonic_time().
3753 * Return value: the newly-created timeout source
3756 g_timeout_source_new (guint interval)
3758 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3759 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3761 timeout_source->interval = interval;
3762 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3768 * g_timeout_source_new_seconds:
3769 * @interval: the timeout interval in seconds
3771 * Creates a new timeout source.
3773 * The source will not initially be associated with any #GMainContext
3774 * and must be added to one with g_source_attach() before it will be
3777 * The scheduling granularity/accuracy of this timeout source will be
3780 * The interval given in terms of monotonic time, not wall clock time.
3781 * See g_get_monotonic_time().
3783 * Return value: the newly-created timeout source
3788 g_timeout_source_new_seconds (guint interval)
3790 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3791 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3793 timeout_source->interval = 1000 * interval;
3794 timeout_source->seconds = TRUE;
3796 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3803 * g_timeout_add_full:
3804 * @priority: the priority of the timeout source. Typically this will be in
3805 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3806 * @interval: the time between calls to the function, in milliseconds
3807 * (1/1000ths of a second)
3808 * @function: function to call
3809 * @data: data to pass to @function
3810 * @notify: function to call when the timeout is removed, or %NULL
3812 * Sets a function to be called at regular intervals, with the given
3813 * priority. The function is called repeatedly until it returns
3814 * %FALSE, at which point the timeout is automatically destroyed and
3815 * the function will not be called again. The @notify function is
3816 * called when the timeout is destroyed. The first call to the
3817 * function will be at the end of the first @interval.
3819 * Note that timeout functions may be delayed, due to the processing of other
3820 * event sources. Thus they should not be relied on for precise timing.
3821 * After each call to the timeout function, the time of the next
3822 * timeout is recalculated based on the current time and the given interval
3823 * (it does not try to 'catch up' time lost in delays).
3825 * This internally creates a main loop source using g_timeout_source_new()
3826 * and attaches it to the main loop context using g_source_attach(). You can
3827 * do these steps manually if you need greater control.
3829 * The interval given in terms of monotonic time, not wall clock time.
3830 * See g_get_monotonic_time().
3832 * Return value: the ID (greater than 0) of the event source.
3833 * Rename to: g_timeout_add
3836 g_timeout_add_full (gint priority,
3838 GSourceFunc function,
3840 GDestroyNotify notify)
3845 g_return_val_if_fail (function != NULL, 0);
3847 source = g_timeout_source_new (interval);
3849 if (priority != G_PRIORITY_DEFAULT)
3850 g_source_set_priority (source, priority);
3852 g_source_set_callback (source, function, data, notify);
3853 id = g_source_attach (source, NULL);
3854 g_source_unref (source);
3861 * @interval: the time between calls to the function, in milliseconds
3862 * (1/1000ths of a second)
3863 * @function: function to call
3864 * @data: data to pass to @function
3866 * Sets a function to be called at regular intervals, with the default
3867 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
3868 * until it returns %FALSE, at which point the timeout is automatically
3869 * destroyed and the function will not be called again. The first call
3870 * to the function will be at the end of the first @interval.
3872 * Note that timeout functions may be delayed, due to the processing of other
3873 * event sources. Thus they should not be relied on for precise timing.
3874 * After each call to the timeout function, the time of the next
3875 * timeout is recalculated based on the current time and the given interval
3876 * (it does not try to 'catch up' time lost in delays).
3878 * If you want to have a timer in the "seconds" range and do not care
3879 * about the exact time of the first call of the timer, use the
3880 * g_timeout_add_seconds() function; this function allows for more
3881 * optimizations and more efficient system power usage.
3883 * This internally creates a main loop source using g_timeout_source_new()
3884 * and attaches it to the main loop context using g_source_attach(). You can
3885 * do these steps manually if you need greater control.
3887 * The interval given is in terms of monotonic time, not wall clock
3888 * time. See g_get_monotonic_time().
3890 * Return value: the ID (greater than 0) of the event source.
3893 g_timeout_add (guint32 interval,
3894 GSourceFunc function,
3897 return g_timeout_add_full (G_PRIORITY_DEFAULT,
3898 interval, function, data, NULL);
3902 * g_timeout_add_seconds_full:
3903 * @priority: the priority of the timeout source. Typically this will be in
3904 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3905 * @interval: the time between calls to the function, in seconds
3906 * @function: function to call
3907 * @data: data to pass to @function
3908 * @notify: function to call when the timeout is removed, or %NULL
3910 * Sets a function to be called at regular intervals, with @priority.
3911 * The function is called repeatedly until it returns %FALSE, at which
3912 * point the timeout is automatically destroyed and the function will
3913 * not be called again.
3915 * Unlike g_timeout_add(), this function operates at whole second granularity.
3916 * The initial starting point of the timer is determined by the implementation
3917 * and the implementation is expected to group multiple timers together so that
3918 * they fire all at the same time.
3919 * To allow this grouping, the @interval to the first timer is rounded
3920 * and can deviate up to one second from the specified interval.
3921 * Subsequent timer iterations will generally run at the specified interval.
3923 * Note that timeout functions may be delayed, due to the processing of other
3924 * event sources. Thus they should not be relied on for precise timing.
3925 * After each call to the timeout function, the time of the next
3926 * timeout is recalculated based on the current time and the given @interval
3928 * If you want timing more precise than whole seconds, use g_timeout_add()
3931 * The grouping of timers to fire at the same time results in a more power
3932 * and CPU efficient behavior so if your timer is in multiples of seconds
3933 * and you don't require the first timer exactly one second from now, the
3934 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
3936 * This internally creates a main loop source using
3937 * g_timeout_source_new_seconds() and attaches it to the main loop context
3938 * using g_source_attach(). You can do these steps manually if you need
3941 * The interval given is in terms of monotonic time, not wall clock
3942 * time. See g_get_monotonic_time().
3944 * Return value: the ID (greater than 0) of the event source.
3946 * Rename to: g_timeout_add_seconds
3950 g_timeout_add_seconds_full (gint priority,
3952 GSourceFunc function,
3954 GDestroyNotify notify)
3959 g_return_val_if_fail (function != NULL, 0);
3961 source = g_timeout_source_new_seconds (interval);
3963 if (priority != G_PRIORITY_DEFAULT)
3964 g_source_set_priority (source, priority);
3966 g_source_set_callback (source, function, data, notify);
3967 id = g_source_attach (source, NULL);
3968 g_source_unref (source);
3974 * g_timeout_add_seconds:
3975 * @interval: the time between calls to the function, in seconds
3976 * @function: function to call
3977 * @data: data to pass to @function
3979 * Sets a function to be called at regular intervals with the default
3980 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
3981 * it returns %FALSE, at which point the timeout is automatically destroyed
3982 * and the function will not be called again.
3984 * This internally creates a main loop source using
3985 * g_timeout_source_new_seconds() and attaches it to the main loop context
3986 * using g_source_attach(). You can do these steps manually if you need
3987 * greater control. Also see g_timeout_add_seconds_full().
3989 * Note that the first call of the timer may not be precise for timeouts
3990 * of one second. If you need finer precision and have such a timeout,
3991 * you may want to use g_timeout_add() instead.
3993 * The interval given is in terms of monotonic time, not wall clock
3994 * time. See g_get_monotonic_time().
3996 * Return value: the ID (greater than 0) of the event source.
4001 g_timeout_add_seconds (guint interval,
4002 GSourceFunc function,
4005 g_return_val_if_fail (function != NULL, 0);
4007 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4010 /* Child watch functions */
4015 g_child_watch_prepare (GSource *source,
4023 g_child_watch_check (GSource *source)
4025 GChildWatchSource *child_watch_source;
4026 gboolean child_exited;
4028 child_watch_source = (GChildWatchSource *) source;
4030 child_exited = child_watch_source->poll.revents & G_IO_IN;
4037 * Note: We do _not_ check for the special value of STILL_ACTIVE
4038 * since we know that the process has exited and doing so runs into
4039 * problems if the child process "happens to return STILL_ACTIVE(259)"
4040 * as Microsoft's Platform SDK puts it.
4042 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4044 gchar *emsg = g_win32_error_message (GetLastError ());
4045 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4048 child_watch_source->child_status = -1;
4051 child_watch_source->child_status = child_status;
4054 return child_exited;
4058 g_child_watch_finalize (GSource *source)
4062 #else /* G_OS_WIN32 */
4065 wake_source (GSource *source)
4067 GMainContext *context;
4069 /* This should be thread-safe:
4071 * - if the source is currently being added to a context, that
4072 * context will be woken up anyway
4074 * - if the source is currently being destroyed, we simply need not
4077 * - the memory for the source will remain valid until after the
4078 * source finalize function was called (which would remove the
4079 * source from the global list which we are currently holding the
4082 * - the GMainContext will either be NULL or point to a live
4085 * - the GMainContext will remain valid since we hold the
4086 * main_context_list lock
4088 * Since we are holding a lot of locks here, don't try to enter any
4089 * more GMainContext functions for fear of dealock -- just hit the
4090 * GWakeup and run. Even if that's safe now, it could easily become
4091 * unsafe with some very minor changes in the future, and signal
4092 * handling is not the most well-tested codepath.
4094 G_LOCK(main_context_list);
4095 context = source->context;
4097 g_wakeup_signal (context->wakeup);
4098 G_UNLOCK(main_context_list);
4102 dispatch_unix_signals (void)
4106 /* clear this first incase another one arrives while we're processing */
4107 any_unix_signal_pending = FALSE;
4109 G_LOCK(unix_signal_lock);
4111 /* handle GChildWatchSource instances */
4112 if (unix_signal_pending[SIGCHLD])
4114 unix_signal_pending[SIGCHLD] = FALSE;
4116 /* The only way we can do this is to scan all of the children.
4118 * The docs promise that we will not reap children that we are not
4119 * explicitly watching, so that ties our hands from calling
4120 * waitpid(-1). We also can't use siginfo's si_pid field since if
4121 * multiple SIGCHLD arrive at the same time, one of them can be
4122 * dropped (since a given UNIX signal can only be pending once).
4124 for (node = unix_child_watches; node; node = node->next)
4126 GChildWatchSource *source = node->data;
4128 if (!source->child_exited)
4130 if (waitpid (source->pid, &source->child_status, WNOHANG) > 0)
4132 source->child_exited = TRUE;
4134 wake_source ((GSource *) source);
4140 /* handle GUnixSignalWatchSource instances */
4141 for (node = unix_signal_watches; node; node = node->next)
4143 GUnixSignalWatchSource *source = node->data;
4145 if (!source->pending)
4147 if (unix_signal_pending[source->signum])
4149 unix_signal_pending[source->signum] = FALSE;
4150 source->pending = TRUE;
4152 wake_source ((GSource *) source);
4157 G_UNLOCK(unix_signal_lock);
4161 g_child_watch_prepare (GSource *source,
4164 GChildWatchSource *child_watch_source;
4166 child_watch_source = (GChildWatchSource *) source;
4168 return child_watch_source->child_exited;
4172 g_child_watch_check (GSource *source)
4174 GChildWatchSource *child_watch_source;
4176 child_watch_source = (GChildWatchSource *) source;
4178 return child_watch_source->child_exited;
4182 g_unix_signal_watch_prepare (GSource *source,
4185 GUnixSignalWatchSource *unix_signal_source;
4187 unix_signal_source = (GUnixSignalWatchSource *) source;
4189 return unix_signal_source->pending;
4193 g_unix_signal_watch_check (GSource *source)
4195 GUnixSignalWatchSource *unix_signal_source;
4197 unix_signal_source = (GUnixSignalWatchSource *) source;
4199 return unix_signal_source->pending;
4203 g_unix_signal_watch_dispatch (GSource *source,
4204 GSourceFunc callback,
4207 GUnixSignalWatchSource *unix_signal_source;
4209 unix_signal_source = (GUnixSignalWatchSource *) source;
4213 g_warning ("Unix signal source dispatched without callback\n"
4214 "You must call g_source_set_callback().");
4218 (callback) (user_data);
4220 unix_signal_source->pending = FALSE;
4226 ensure_unix_signal_handler_installed_unlocked (int signum)
4228 static sigset_t installed_signal_mask;
4229 static gboolean initialized;
4230 struct sigaction action;
4234 sigemptyset (&installed_signal_mask);
4235 g_get_worker_context ();
4239 if (sigismember (&installed_signal_mask, signum))
4242 sigaddset (&installed_signal_mask, signum);
4244 action.sa_handler = g_unix_signal_handler;
4245 sigemptyset (&action.sa_mask);
4246 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4247 sigaction (signum, &action, NULL);
4251 _g_main_create_unix_signal_watch (int signum)
4254 GUnixSignalWatchSource *unix_signal_source;
4256 source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
4257 unix_signal_source = (GUnixSignalWatchSource *) source;
4259 unix_signal_source->signum = signum;
4260 unix_signal_source->pending = FALSE;
4262 G_LOCK (unix_signal_lock);
4263 ensure_unix_signal_handler_installed_unlocked (signum);
4264 unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
4265 if (unix_signal_pending[signum])
4266 unix_signal_source->pending = TRUE;
4267 unix_signal_pending[signum] = FALSE;
4268 G_UNLOCK (unix_signal_lock);
4274 g_unix_signal_watch_finalize (GSource *source)
4276 G_LOCK (unix_signal_lock);
4277 unix_signal_watches = g_slist_remove (unix_signal_watches, source);
4278 G_UNLOCK (unix_signal_lock);
4282 g_child_watch_finalize (GSource *source)
4284 G_LOCK (unix_signal_lock);
4285 unix_child_watches = g_slist_remove (unix_child_watches, source);
4286 G_UNLOCK (unix_signal_lock);
4289 #endif /* G_OS_WIN32 */
4292 g_child_watch_dispatch (GSource *source,
4293 GSourceFunc callback,
4296 GChildWatchSource *child_watch_source;
4297 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
4299 child_watch_source = (GChildWatchSource *) source;
4303 g_warning ("Child watch source dispatched without callback\n"
4304 "You must call g_source_set_callback().");
4308 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
4310 /* We never keep a child watch source around as the child is gone */
4317 g_unix_signal_handler (int signum)
4319 unix_signal_pending[signum] = TRUE;
4320 any_unix_signal_pending = TRUE;
4322 g_wakeup_signal (glib_worker_context->wakeup);
4325 #endif /* !G_OS_WIN32 */
4328 * g_child_watch_source_new:
4329 * @pid: process to watch. On POSIX the pid of a child process. On
4330 * Windows a handle for a process (which doesn't have to be a child).
4332 * Creates a new child_watch source.
4334 * The source will not initially be associated with any #GMainContext
4335 * and must be added to one with g_source_attach() before it will be
4338 * Note that child watch sources can only be used in conjunction with
4339 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4342 * Note that on platforms where #GPid must be explicitly closed
4343 * (see g_spawn_close_pid()) @pid must not be closed while the
4344 * source is still active. Typically, you will want to call
4345 * g_spawn_close_pid() in the callback function for the source.
4347 * Note further that using g_child_watch_source_new() is not
4348 * compatible with calling <literal>waitpid(-1)</literal> in
4349 * the application. Calling waitpid() for individual pids will
4352 * Return value: the newly-created child watch source
4357 g_child_watch_source_new (GPid pid)
4359 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4360 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4362 child_watch_source->pid = pid;
4365 child_watch_source->poll.fd = (gintptr) pid;
4366 child_watch_source->poll.events = G_IO_IN;
4368 g_source_add_poll (source, &child_watch_source->poll);
4369 #else /* G_OS_WIN32 */
4370 G_LOCK (unix_signal_lock);
4371 ensure_unix_signal_handler_installed_unlocked (SIGCHLD);
4372 unix_child_watches = g_slist_prepend (unix_child_watches, child_watch_source);
4373 if (waitpid (pid, &child_watch_source->child_status, WNOHANG) > 0)
4374 child_watch_source->child_exited = TRUE;
4375 G_UNLOCK (unix_signal_lock);
4376 #endif /* G_OS_WIN32 */
4382 * g_child_watch_add_full:
4383 * @priority: the priority of the idle source. Typically this will be in the
4384 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4385 * @pid: process to watch. On POSIX the pid of a child process. On
4386 * Windows a handle for a process (which doesn't have to be a child).
4387 * @function: function to call
4388 * @data: data to pass to @function
4389 * @notify: function to call when the idle is removed, or %NULL
4391 * Sets a function to be called when the child indicated by @pid
4392 * exits, at the priority @priority.
4394 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4395 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4396 * the spawn function for the child watching to work.
4398 * Note that on platforms where #GPid must be explicitly closed
4399 * (see g_spawn_close_pid()) @pid must not be closed while the
4400 * source is still active. Typically, you will want to call
4401 * g_spawn_close_pid() in the callback function for the source.
4403 * GLib supports only a single callback per process id.
4405 * This internally creates a main loop source using
4406 * g_child_watch_source_new() and attaches it to the main loop context
4407 * using g_source_attach(). You can do these steps manually if you
4408 * need greater control.
4410 * Return value: the ID (greater than 0) of the event source.
4412 * Rename to: g_child_watch_add
4416 g_child_watch_add_full (gint priority,
4418 GChildWatchFunc function,
4420 GDestroyNotify notify)
4425 g_return_val_if_fail (function != NULL, 0);
4427 source = g_child_watch_source_new (pid);
4429 if (priority != G_PRIORITY_DEFAULT)
4430 g_source_set_priority (source, priority);
4432 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4433 id = g_source_attach (source, NULL);
4434 g_source_unref (source);
4440 * g_child_watch_add:
4441 * @pid: process id to watch. On POSIX the pid of a child process. On
4442 * Windows a handle for a process (which doesn't have to be a child).
4443 * @function: function to call
4444 * @data: data to pass to @function
4446 * Sets a function to be called when the child indicated by @pid
4447 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4449 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4450 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4451 * the spawn function for the child watching to work.
4453 * Note that on platforms where #GPid must be explicitly closed
4454 * (see g_spawn_close_pid()) @pid must not be closed while the
4455 * source is still active. Typically, you will want to call
4456 * g_spawn_close_pid() in the callback function for the source.
4458 * GLib supports only a single callback per process id.
4460 * This internally creates a main loop source using
4461 * g_child_watch_source_new() and attaches it to the main loop context
4462 * using g_source_attach(). You can do these steps manually if you
4463 * need greater control.
4465 * Return value: the ID (greater than 0) of the event source.
4470 g_child_watch_add (GPid pid,
4471 GChildWatchFunc function,
4474 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4478 /* Idle functions */
4481 g_idle_prepare (GSource *source,
4490 g_idle_check (GSource *source)
4496 g_idle_dispatch (GSource *source,
4497 GSourceFunc callback,
4502 g_warning ("Idle source dispatched without callback\n"
4503 "You must call g_source_set_callback().");
4507 return callback (user_data);
4511 * g_idle_source_new:
4513 * Creates a new idle source.
4515 * The source will not initially be associated with any #GMainContext
4516 * and must be added to one with g_source_attach() before it will be
4517 * executed. Note that the default priority for idle sources is
4518 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4519 * have a default priority of %G_PRIORITY_DEFAULT.
4521 * Return value: the newly-created idle source
4524 g_idle_source_new (void)
4528 source = g_source_new (&g_idle_funcs, sizeof (GSource));
4529 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4536 * @priority: the priority of the idle source. Typically this will be in the
4537 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4538 * @function: function to call
4539 * @data: data to pass to @function
4540 * @notify: function to call when the idle is removed, or %NULL
4542 * Adds a function to be called whenever there are no higher priority
4543 * events pending. If the function returns %FALSE it is automatically
4544 * removed from the list of event sources and will not be called again.
4546 * This internally creates a main loop source using g_idle_source_new()
4547 * and attaches it to the main loop context using g_source_attach().
4548 * You can do these steps manually if you need greater control.
4550 * Return value: the ID (greater than 0) of the event source.
4551 * Rename to: g_idle_add
4554 g_idle_add_full (gint priority,
4555 GSourceFunc function,
4557 GDestroyNotify notify)
4562 g_return_val_if_fail (function != NULL, 0);
4564 source = g_idle_source_new ();
4566 if (priority != G_PRIORITY_DEFAULT_IDLE)
4567 g_source_set_priority (source, priority);
4569 g_source_set_callback (source, function, data, notify);
4570 id = g_source_attach (source, NULL);
4571 g_source_unref (source);
4578 * @function: function to call
4579 * @data: data to pass to @function.
4581 * Adds a function to be called whenever there are no higher priority
4582 * events pending to the default main loop. The function is given the
4583 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4584 * returns %FALSE it is automatically removed from the list of event
4585 * sources and will not be called again.
4587 * This internally creates a main loop source using g_idle_source_new()
4588 * and attaches it to the main loop context using g_source_attach().
4589 * You can do these steps manually if you need greater control.
4591 * Return value: the ID (greater than 0) of the event source.
4594 g_idle_add (GSourceFunc function,
4597 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4601 * g_idle_remove_by_data:
4602 * @data: the data for the idle source's callback.
4604 * Removes the idle function with the given data.
4606 * Return value: %TRUE if an idle source was found and removed.
4609 g_idle_remove_by_data (gpointer data)
4611 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4615 * g_main_context_invoke:
4616 * @context: (allow-none): a #GMainContext, or %NULL
4617 * @function: function to call
4618 * @data: data to pass to @function
4620 * Invokes a function in such a way that @context is owned during the
4621 * invocation of @function.
4623 * If @context is %NULL then the global default main context — as
4624 * returned by g_main_context_default() — is used.
4626 * If @context is owned by the current thread, @function is called
4627 * directly. Otherwise, if @context is the thread-default main context
4628 * of the current thread and g_main_context_acquire() succeeds, then
4629 * @function is called and g_main_context_release() is called
4632 * In any other case, an idle source is created to call @function and
4633 * that source is attached to @context (presumably to be run in another
4634 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
4635 * priority. If you want a different priority, use
4636 * g_main_context_invoke_full().
4638 * Note that, as with normal idle functions, @function should probably
4639 * return %FALSE. If it returns %TRUE, it will be continuously run in a
4640 * loop (and may prevent this call from returning).
4645 g_main_context_invoke (GMainContext *context,
4646 GSourceFunc function,
4649 g_main_context_invoke_full (context,
4651 function, data, NULL);
4655 * g_main_context_invoke_full:
4656 * @context: (allow-none): a #GMainContext, or %NULL
4657 * @priority: the priority at which to run @function
4658 * @function: function to call
4659 * @data: data to pass to @function
4660 * @notify: a function to call when @data is no longer in use, or %NULL.
4662 * Invokes a function in such a way that @context is owned during the
4663 * invocation of @function.
4665 * This function is the same as g_main_context_invoke() except that it
4666 * lets you specify the priority incase @function ends up being
4667 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
4669 * @notify should not assume that it is called from any particular
4670 * thread or with any particular context acquired.
4675 g_main_context_invoke_full (GMainContext *context,
4677 GSourceFunc function,
4679 GDestroyNotify notify)
4681 g_return_if_fail (function != NULL);
4684 context = g_main_context_default ();
4686 if (g_main_context_is_owner (context))
4688 while (function (data));
4695 GMainContext *thread_default;
4697 thread_default = g_main_context_get_thread_default ();
4699 if (!thread_default)
4700 thread_default = g_main_context_default ();
4702 if (thread_default == context && g_main_context_acquire (context))
4704 while (function (data));
4706 g_main_context_release (context);
4715 source = g_idle_source_new ();
4716 g_source_set_priority (source, priority);
4717 g_source_set_callback (source, function, data, notify);
4718 g_source_attach (source, context);
4719 g_source_unref (source);
4725 glib_worker_main (gpointer data)
4729 g_main_context_iteration (glib_worker_context, TRUE);
4732 if (any_unix_signal_pending)
4733 dispatch_unix_signals ();
4737 return NULL; /* worst GCC warning message ever... */
4741 g_get_worker_context (void)
4743 static gsize initialised;
4745 g_thread_init_glib ();
4747 if (g_once_init_enter (&initialised))
4749 GError *error = NULL;
4751 glib_worker_context = g_main_context_new ();
4752 if (g_thread_new ("gmain", glib_worker_main, NULL, FALSE, &error) == NULL)
4753 g_error ("Creating GLib worker thread failed: %s\n", error->message);
4755 g_once_init_leave (&initialised, TRUE);
4758 return glib_worker_context;