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_static_mutex_lock (&context->mutex)
313 #define UNLOCK_CONTEXT(context) g_static_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_static_mutex_free (&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);
500 if (context->cond != NULL)
501 g_cond_free (context->cond);
508 g_main_context_forked (void)
510 g_main_context_fork_detected = TRUE;
515 * g_main_context_new:
517 * Creates a new #GMainContext structure.
519 * Return value: the new #GMainContext
522 g_main_context_new (void)
524 static gsize initialised;
525 GMainContext *context;
527 g_thread_init_glib ();
529 if (g_once_init_enter (&initialised))
531 #ifdef G_MAIN_POLL_DEBUG
532 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
533 _g_main_poll_debug = TRUE;
537 pthread_atfork (NULL, NULL, g_main_context_forked);
540 g_once_init_leave (&initialised, TRUE);
543 context = g_new0 (GMainContext, 1);
545 g_static_mutex_init (&context->mutex);
547 context->owner = NULL;
548 context->waiters = NULL;
550 context->ref_count = 1;
552 context->next_id = 1;
554 context->source_list = NULL;
556 context->poll_func = g_poll;
558 context->cached_poll_array = NULL;
559 context->cached_poll_array_size = 0;
561 context->pending_dispatches = g_ptr_array_new ();
563 context->time_is_fresh = FALSE;
565 context->wakeup = g_wakeup_new ();
566 g_wakeup_get_pollfd (context->wakeup, &context->wake_up_rec);
567 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
569 G_LOCK (main_context_list);
570 main_context_list = g_slist_append (main_context_list, context);
572 #ifdef G_MAIN_POLL_DEBUG
573 if (_g_main_poll_debug)
574 g_print ("created context=%p\n", context);
577 G_UNLOCK (main_context_list);
583 * g_main_context_default:
585 * Returns the global default main context. This is the main context
586 * used for main loop functions when a main loop is not explicitly
587 * specified, and corresponds to the "main" main loop. See also
588 * g_main_context_get_thread_default().
590 * Return value: (transfer none): the global default main context.
593 g_main_context_default (void)
599 if (!default_main_context)
601 default_main_context = g_main_context_new ();
602 #ifdef G_MAIN_POLL_DEBUG
603 if (_g_main_poll_debug)
604 g_print ("default context=%p\n", default_main_context);
608 G_UNLOCK (main_loop);
610 return default_main_context;
613 static GStaticPrivate thread_context_stack = G_STATIC_PRIVATE_INIT;
616 free_context_stack (gpointer data)
618 GQueue *stack = data;
619 GMainContext *context;
621 while (!g_queue_is_empty (stack))
623 context = g_queue_pop_head (stack);
624 g_main_context_release (context);
626 g_main_context_unref (context);
628 g_queue_free (stack);
632 * g_main_context_push_thread_default:
633 * @context: a #GMainContext, or %NULL for the global default context
635 * Acquires @context and sets it as the thread-default context for the
636 * current thread. This will cause certain asynchronous operations
637 * (such as most <link linkend="gio">gio</link>-based I/O) which are
638 * started in this thread to run under @context and deliver their
639 * results to its main loop, rather than running under the global
640 * default context in the main thread. Note that calling this function
641 * changes the context returned by
642 * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
643 * one returned by g_main_context_default(), so it does not affect the
644 * context used by functions like g_idle_add().
646 * Normally you would call this function shortly after creating a new
647 * thread, passing it a #GMainContext which will be run by a
648 * #GMainLoop in that thread, to set a new default context for all
649 * async operations in that thread. (In this case, you don't need to
650 * ever call g_main_context_pop_thread_default().) In some cases
651 * however, you may want to schedule a single operation in a
652 * non-default context, or temporarily use a non-default context in
653 * the main thread. In that case, you can wrap the call to the
654 * asynchronous operation inside a
655 * g_main_context_push_thread_default() /
656 * g_main_context_pop_thread_default() pair, but it is up to you to
657 * ensure that no other asynchronous operations accidentally get
658 * started while the non-default context is active.
660 * Beware that libraries that predate this function may not correctly
661 * handle being used from a thread with a thread-default context. Eg,
662 * see g_file_supports_thread_contexts().
667 g_main_context_push_thread_default (GMainContext *context)
670 gboolean acquired_context;
672 acquired_context = g_main_context_acquire (context);
673 g_return_if_fail (acquired_context);
675 if (context == g_main_context_default ())
678 g_main_context_ref (context);
680 stack = g_static_private_get (&thread_context_stack);
683 stack = g_queue_new ();
684 g_static_private_set (&thread_context_stack, stack,
688 g_queue_push_head (stack, context);
692 * g_main_context_pop_thread_default:
693 * @context: a #GMainContext object, or %NULL
695 * Pops @context off the thread-default context stack (verifying that
696 * it was on the top of the stack).
701 g_main_context_pop_thread_default (GMainContext *context)
705 if (context == g_main_context_default ())
708 stack = g_static_private_get (&thread_context_stack);
710 g_return_if_fail (stack != NULL);
711 g_return_if_fail (g_queue_peek_head (stack) == context);
713 g_queue_pop_head (stack);
715 g_main_context_release (context);
717 g_main_context_unref (context);
721 * g_main_context_get_thread_default:
723 * Gets the thread-default #GMainContext for this thread. Asynchronous
724 * operations that want to be able to be run in contexts other than
725 * the default one should call this method to get a #GMainContext to
726 * add their #GSource<!-- -->s to. (Note that even in single-threaded
727 * programs applications may sometimes want to temporarily push a
728 * non-default context, so it is not safe to assume that this will
729 * always return %NULL if threads are not initialized.)
731 * Returns: (transfer none): the thread-default #GMainContext, or
732 * %NULL if the thread-default context is the global default context.
737 g_main_context_get_thread_default (void)
741 stack = g_static_private_get (&thread_context_stack);
743 return g_queue_peek_head (stack);
748 /* Hooks for adding to the main loop */
752 * @source_funcs: structure containing functions that implement
753 * the sources behavior.
754 * @struct_size: size of the #GSource structure to create.
756 * Creates a new #GSource structure. The size is specified to
757 * allow creating structures derived from #GSource that contain
758 * additional data. The size passed in must be at least
759 * <literal>sizeof (GSource)</literal>.
761 * The source will not initially be associated with any #GMainContext
762 * and must be added to one with g_source_attach() before it will be
765 * Return value: the newly-created #GSource.
768 g_source_new (GSourceFuncs *source_funcs,
773 g_return_val_if_fail (source_funcs != NULL, NULL);
774 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
776 source = (GSource*) g_malloc0 (struct_size);
778 source->source_funcs = source_funcs;
779 source->ref_count = 1;
781 source->priority = G_PRIORITY_DEFAULT;
783 source->flags = G_HOOK_FLAG_ACTIVE;
785 /* NULL/0 initialization for all other fields */
790 /* Holds context's lock
793 g_source_list_add (GSource *source,
794 GMainContext *context)
796 GSource *tmp_source, *last_source;
798 if (source->priv && source->priv->parent_source)
800 /* Put the source immediately before its parent */
801 tmp_source = source->priv->parent_source;
802 last_source = source->priv->parent_source->prev;
807 tmp_source = context->source_list;
808 while (tmp_source && tmp_source->priority <= source->priority)
810 last_source = tmp_source;
811 tmp_source = tmp_source->next;
815 source->next = tmp_source;
817 tmp_source->prev = source;
819 source->prev = last_source;
821 last_source->next = source;
823 context->source_list = source;
826 /* Holds context's lock
829 g_source_list_remove (GSource *source,
830 GMainContext *context)
833 source->prev->next = source->next;
835 context->source_list = source->next;
838 source->next->prev = source->prev;
845 g_source_attach_unlocked (GSource *source,
846 GMainContext *context)
851 source->context = context;
852 result = source->source_id = context->next_id++;
855 g_source_list_add (source, context);
857 tmp_list = source->poll_fds;
860 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
861 tmp_list = tmp_list->next;
866 tmp_list = source->priv->child_sources;
869 g_source_attach_unlocked (tmp_list->data, context);
870 tmp_list = tmp_list->next;
879 * @source: a #GSource
880 * @context: a #GMainContext (if %NULL, the default context will be used)
882 * Adds a #GSource to a @context so that it will be executed within
883 * that context. Remove it by calling g_source_destroy().
885 * Return value: the ID (greater than 0) for the source within the
889 g_source_attach (GSource *source,
890 GMainContext *context)
894 g_return_val_if_fail (source->context == NULL, 0);
895 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
898 context = g_main_context_default ();
900 LOCK_CONTEXT (context);
902 result = g_source_attach_unlocked (source, context);
904 /* If another thread has acquired the context, wake it up since it
905 * might be in poll() right now.
907 if (context->owner && context->owner != G_THREAD_SELF)
908 g_wakeup_signal (context->wakeup);
910 UNLOCK_CONTEXT (context);
916 g_source_destroy_internal (GSource *source,
917 GMainContext *context,
921 LOCK_CONTEXT (context);
923 if (!SOURCE_DESTROYED (source))
926 gpointer old_cb_data;
927 GSourceCallbackFuncs *old_cb_funcs;
929 source->flags &= ~G_HOOK_FLAG_ACTIVE;
931 old_cb_data = source->callback_data;
932 old_cb_funcs = source->callback_funcs;
934 source->callback_data = NULL;
935 source->callback_funcs = NULL;
939 UNLOCK_CONTEXT (context);
940 old_cb_funcs->unref (old_cb_data);
941 LOCK_CONTEXT (context);
944 if (!SOURCE_BLOCKED (source))
946 tmp_list = source->poll_fds;
949 g_main_context_remove_poll_unlocked (context, tmp_list->data);
950 tmp_list = tmp_list->next;
954 if (source->priv && source->priv->child_sources)
956 /* This is safe because even if a child_source finalizer or
957 * closure notify tried to modify source->priv->child_sources
958 * from outside the lock, it would fail since
959 * SOURCE_DESTROYED(source) is now TRUE.
961 tmp_list = source->priv->child_sources;
964 g_source_destroy_internal (tmp_list->data, context, TRUE);
965 g_source_unref_internal (tmp_list->data, context, TRUE);
966 tmp_list = tmp_list->next;
968 g_slist_free (source->priv->child_sources);
969 source->priv->child_sources = NULL;
972 g_source_unref_internal (source, context, TRUE);
976 UNLOCK_CONTEXT (context);
981 * @source: a #GSource
983 * Removes a source from its #GMainContext, if any, and mark it as
984 * destroyed. The source cannot be subsequently added to another
988 g_source_destroy (GSource *source)
990 GMainContext *context;
992 g_return_if_fail (source != NULL);
994 context = source->context;
997 g_source_destroy_internal (source, context, FALSE);
999 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1004 * @source: a #GSource
1006 * Returns the numeric ID for a particular source. The ID of a source
1007 * is a positive integer which is unique within a particular main loop
1008 * context. The reverse
1009 * mapping from ID to source is done by g_main_context_find_source_by_id().
1011 * Return value: the ID (greater than 0) for the source
1014 g_source_get_id (GSource *source)
1018 g_return_val_if_fail (source != NULL, 0);
1019 g_return_val_if_fail (source->context != NULL, 0);
1021 LOCK_CONTEXT (source->context);
1022 result = source->source_id;
1023 UNLOCK_CONTEXT (source->context);
1029 * g_source_get_context:
1030 * @source: a #GSource
1032 * Gets the #GMainContext with which the source is associated.
1033 * Calling this function on a destroyed source is an error.
1035 * Return value: (transfer none): the #GMainContext with which the
1036 * source is associated, or %NULL if the context has not
1037 * yet been added to a source.
1040 g_source_get_context (GSource *source)
1042 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1044 return source->context;
1048 * g_source_add_poll:
1049 * @source:a #GSource
1050 * @fd: a #GPollFD structure holding information about a file
1051 * descriptor to watch.
1053 * Adds a file descriptor to the set of file descriptors polled for
1054 * this source. This is usually combined with g_source_new() to add an
1055 * event source. The event source's check function will typically test
1056 * the @revents field in the #GPollFD struct and return %TRUE if events need
1060 g_source_add_poll (GSource *source,
1063 GMainContext *context;
1065 g_return_if_fail (source != NULL);
1066 g_return_if_fail (fd != NULL);
1067 g_return_if_fail (!SOURCE_DESTROYED (source));
1069 context = source->context;
1072 LOCK_CONTEXT (context);
1074 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1078 if (!SOURCE_BLOCKED (source))
1079 g_main_context_add_poll_unlocked (context, source->priority, fd);
1080 UNLOCK_CONTEXT (context);
1085 * g_source_remove_poll:
1086 * @source:a #GSource
1087 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1089 * Removes a file descriptor from the set of file descriptors polled for
1093 g_source_remove_poll (GSource *source,
1096 GMainContext *context;
1098 g_return_if_fail (source != NULL);
1099 g_return_if_fail (fd != NULL);
1100 g_return_if_fail (!SOURCE_DESTROYED (source));
1102 context = source->context;
1105 LOCK_CONTEXT (context);
1107 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1111 if (!SOURCE_BLOCKED (source))
1112 g_main_context_remove_poll_unlocked (context, fd);
1113 UNLOCK_CONTEXT (context);
1118 * g_source_add_child_source:
1119 * @source:a #GSource
1120 * @child_source: a second #GSource that @source should "poll"
1122 * Adds @child_source to @source as a "polled" source; when @source is
1123 * added to a #GMainContext, @child_source will be automatically added
1124 * with the same priority, when @child_source is triggered, it will
1125 * cause @source to dispatch (in addition to calling its own
1126 * callback), and when @source is destroyed, it will destroy
1127 * @child_source as well. (@source will also still be dispatched if
1128 * its own prepare/check functions indicate that it is ready.)
1130 * If you don't need @child_source to do anything on its own when it
1131 * triggers, you can call g_source_set_dummy_callback() on it to set a
1132 * callback that does nothing (except return %TRUE if appropriate).
1134 * @source will hold a reference on @child_source while @child_source
1135 * is attached to it.
1140 g_source_add_child_source (GSource *source,
1141 GSource *child_source)
1143 GMainContext *context;
1145 g_return_if_fail (source != NULL);
1146 g_return_if_fail (child_source != NULL);
1147 g_return_if_fail (!SOURCE_DESTROYED (source));
1148 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1149 g_return_if_fail (child_source->context == NULL);
1150 g_return_if_fail (child_source->priv == NULL || child_source->priv->parent_source == NULL);
1152 context = source->context;
1155 LOCK_CONTEXT (context);
1158 source->priv = g_slice_new0 (GSourcePrivate);
1159 if (!child_source->priv)
1160 child_source->priv = g_slice_new0 (GSourcePrivate);
1162 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1163 g_source_ref (child_source));
1164 child_source->priv->parent_source = source;
1165 g_source_set_priority_unlocked (child_source, context, source->priority);
1169 UNLOCK_CONTEXT (context);
1170 g_source_attach (child_source, context);
1175 * g_source_remove_child_source:
1176 * @source:a #GSource
1177 * @child_source: a #GSource previously passed to
1178 * g_source_add_child_source().
1180 * Detaches @child_source from @source and destroys it.
1185 g_source_remove_child_source (GSource *source,
1186 GSource *child_source)
1188 GMainContext *context;
1190 g_return_if_fail (source != NULL);
1191 g_return_if_fail (child_source != NULL);
1192 g_return_if_fail (child_source->priv != NULL && child_source->priv->parent_source == source);
1193 g_return_if_fail (!SOURCE_DESTROYED (source));
1194 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1196 context = source->context;
1199 LOCK_CONTEXT (context);
1201 source->priv->child_sources = g_slist_remove (source->priv->child_sources, child_source);
1202 g_source_destroy_internal (child_source, context, TRUE);
1203 g_source_unref_internal (child_source, context, TRUE);
1206 UNLOCK_CONTEXT (context);
1210 * g_source_set_callback_indirect:
1211 * @source: the source
1212 * @callback_data: pointer to callback data "object"
1213 * @callback_funcs: functions for reference counting @callback_data
1214 * and getting the callback and data
1216 * Sets the callback function storing the data as a refcounted callback
1217 * "object". This is used internally. Note that calling
1218 * g_source_set_callback_indirect() assumes
1219 * an initial reference count on @callback_data, and thus
1220 * @callback_funcs->unref will eventually be called once more
1221 * than @callback_funcs->ref.
1224 g_source_set_callback_indirect (GSource *source,
1225 gpointer callback_data,
1226 GSourceCallbackFuncs *callback_funcs)
1228 GMainContext *context;
1229 gpointer old_cb_data;
1230 GSourceCallbackFuncs *old_cb_funcs;
1232 g_return_if_fail (source != NULL);
1233 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1235 context = source->context;
1238 LOCK_CONTEXT (context);
1240 old_cb_data = source->callback_data;
1241 old_cb_funcs = source->callback_funcs;
1243 source->callback_data = callback_data;
1244 source->callback_funcs = callback_funcs;
1247 UNLOCK_CONTEXT (context);
1250 old_cb_funcs->unref (old_cb_data);
1254 g_source_callback_ref (gpointer cb_data)
1256 GSourceCallback *callback = cb_data;
1258 callback->ref_count++;
1263 g_source_callback_unref (gpointer cb_data)
1265 GSourceCallback *callback = cb_data;
1267 callback->ref_count--;
1268 if (callback->ref_count == 0)
1270 if (callback->notify)
1271 callback->notify (callback->data);
1277 g_source_callback_get (gpointer cb_data,
1282 GSourceCallback *callback = cb_data;
1284 *func = callback->func;
1285 *data = callback->data;
1288 static GSourceCallbackFuncs g_source_callback_funcs = {
1289 g_source_callback_ref,
1290 g_source_callback_unref,
1291 g_source_callback_get,
1295 * g_source_set_callback:
1296 * @source: the source
1297 * @func: a callback function
1298 * @data: the data to pass to callback function
1299 * @notify: a function to call when @data is no longer in use, or %NULL.
1301 * Sets the callback function for a source. The callback for a source is
1302 * called from the source's dispatch function.
1304 * The exact type of @func depends on the type of source; ie. you
1305 * should not count on @func being called with @data as its first
1308 * Typically, you won't use this function. Instead use functions specific
1309 * to the type of source you are using.
1312 g_source_set_callback (GSource *source,
1315 GDestroyNotify notify)
1317 GSourceCallback *new_callback;
1319 g_return_if_fail (source != NULL);
1321 new_callback = g_new (GSourceCallback, 1);
1323 new_callback->ref_count = 1;
1324 new_callback->func = func;
1325 new_callback->data = data;
1326 new_callback->notify = notify;
1328 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1333 * g_source_set_funcs:
1334 * @source: a #GSource
1335 * @funcs: the new #GSourceFuncs
1337 * Sets the source functions (can be used to override
1338 * default implementations) of an unattached source.
1343 g_source_set_funcs (GSource *source,
1344 GSourceFuncs *funcs)
1346 g_return_if_fail (source != NULL);
1347 g_return_if_fail (source->context == NULL);
1348 g_return_if_fail (source->ref_count > 0);
1349 g_return_if_fail (funcs != NULL);
1351 source->source_funcs = funcs;
1355 g_source_set_priority_unlocked (GSource *source,
1356 GMainContext *context,
1361 source->priority = priority;
1365 /* Remove the source from the context's source and then
1366 * add it back so it is sorted in the correct place
1368 g_source_list_remove (source, source->context);
1369 g_source_list_add (source, source->context);
1371 if (!SOURCE_BLOCKED (source))
1373 tmp_list = source->poll_fds;
1376 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1377 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1379 tmp_list = tmp_list->next;
1384 if (source->priv && source->priv->child_sources)
1386 tmp_list = source->priv->child_sources;
1389 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1390 tmp_list = tmp_list->next;
1396 * g_source_set_priority:
1397 * @source: a #GSource
1398 * @priority: the new priority.
1400 * Sets the priority of a source. While the main loop is being run, a
1401 * source will be dispatched if it is ready to be dispatched and no
1402 * sources at a higher (numerically smaller) priority are ready to be
1406 g_source_set_priority (GSource *source,
1409 GMainContext *context;
1411 g_return_if_fail (source != NULL);
1413 context = source->context;
1416 LOCK_CONTEXT (context);
1417 g_source_set_priority_unlocked (source, context, priority);
1419 UNLOCK_CONTEXT (source->context);
1423 * g_source_get_priority:
1424 * @source: a #GSource
1426 * Gets the priority of a source.
1428 * Return value: the priority of the source
1431 g_source_get_priority (GSource *source)
1433 g_return_val_if_fail (source != NULL, 0);
1435 return source->priority;
1439 * g_source_set_can_recurse:
1440 * @source: a #GSource
1441 * @can_recurse: whether recursion is allowed for this source
1443 * Sets whether a source can be called recursively. If @can_recurse is
1444 * %TRUE, then while the source is being dispatched then this source
1445 * will be processed normally. Otherwise, all processing of this
1446 * source is blocked until the dispatch function returns.
1449 g_source_set_can_recurse (GSource *source,
1450 gboolean can_recurse)
1452 GMainContext *context;
1454 g_return_if_fail (source != NULL);
1456 context = source->context;
1459 LOCK_CONTEXT (context);
1462 source->flags |= G_SOURCE_CAN_RECURSE;
1464 source->flags &= ~G_SOURCE_CAN_RECURSE;
1467 UNLOCK_CONTEXT (context);
1471 * g_source_get_can_recurse:
1472 * @source: a #GSource
1474 * Checks whether a source is allowed to be called recursively.
1475 * see g_source_set_can_recurse().
1477 * Return value: whether recursion is allowed.
1480 g_source_get_can_recurse (GSource *source)
1482 g_return_val_if_fail (source != NULL, FALSE);
1484 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1489 * g_source_set_name:
1490 * @source: a #GSource
1491 * @name: debug name for the source
1493 * Sets a name for the source, used in debugging and profiling.
1494 * The name defaults to #NULL.
1496 * The source name should describe in a human-readable way
1497 * what the source does. For example, "X11 event queue"
1498 * or "GTK+ repaint idle handler" or whatever it is.
1500 * It is permitted to call this function multiple times, but is not
1501 * recommended due to the potential performance impact. For example,
1502 * one could change the name in the "check" function of a #GSourceFuncs
1503 * to include details like the event type in the source name.
1508 g_source_set_name (GSource *source,
1511 g_return_if_fail (source != NULL);
1513 /* setting back to NULL is allowed, just because it's
1514 * weird if get_name can return NULL but you can't
1518 g_free (source->name);
1519 source->name = g_strdup (name);
1523 * g_source_get_name:
1524 * @source: a #GSource
1526 * Gets a name for the source, used in debugging and profiling.
1527 * The name may be #NULL if it has never been set with
1528 * g_source_set_name().
1530 * Return value: the name of the source
1534 g_source_get_name (GSource *source)
1536 g_return_val_if_fail (source != NULL, NULL);
1538 return source->name;
1542 * g_source_set_name_by_id:
1543 * @tag: a #GSource ID
1544 * @name: debug name for the source
1546 * Sets the name of a source using its ID.
1548 * This is a convenience utility to set source names from the return
1549 * value of g_idle_add(), g_timeout_add(), etc.
1554 g_source_set_name_by_id (guint tag,
1559 g_return_if_fail (tag > 0);
1561 source = g_main_context_find_source_by_id (NULL, tag);
1565 g_source_set_name (source, name);
1571 * @source: a #GSource
1573 * Increases the reference count on a source by one.
1575 * Return value: @source
1578 g_source_ref (GSource *source)
1580 GMainContext *context;
1582 g_return_val_if_fail (source != NULL, NULL);
1584 context = source->context;
1587 LOCK_CONTEXT (context);
1589 source->ref_count++;
1592 UNLOCK_CONTEXT (context);
1597 /* g_source_unref() but possible to call within context lock
1600 g_source_unref_internal (GSource *source,
1601 GMainContext *context,
1604 gpointer old_cb_data = NULL;
1605 GSourceCallbackFuncs *old_cb_funcs = NULL;
1607 g_return_if_fail (source != NULL);
1609 if (!have_lock && context)
1610 LOCK_CONTEXT (context);
1612 source->ref_count--;
1613 if (source->ref_count == 0)
1615 old_cb_data = source->callback_data;
1616 old_cb_funcs = source->callback_funcs;
1618 source->callback_data = NULL;
1619 source->callback_funcs = NULL;
1623 if (!SOURCE_DESTROYED (source))
1624 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
1625 g_source_list_remove (source, context);
1628 if (source->source_funcs->finalize)
1631 UNLOCK_CONTEXT (context);
1632 source->source_funcs->finalize (source);
1634 LOCK_CONTEXT (context);
1637 g_free (source->name);
1638 source->name = NULL;
1640 g_slist_free (source->poll_fds);
1641 source->poll_fds = NULL;
1645 g_slice_free (GSourcePrivate, source->priv);
1646 source->priv = NULL;
1652 if (!have_lock && context)
1653 UNLOCK_CONTEXT (context);
1658 UNLOCK_CONTEXT (context);
1660 old_cb_funcs->unref (old_cb_data);
1663 LOCK_CONTEXT (context);
1669 * @source: a #GSource
1671 * Decreases the reference count of a source by one. If the
1672 * resulting reference count is zero the source and associated
1673 * memory will be destroyed.
1676 g_source_unref (GSource *source)
1678 g_return_if_fail (source != NULL);
1680 g_source_unref_internal (source, source->context, FALSE);
1684 * g_main_context_find_source_by_id:
1685 * @context: a #GMainContext (if %NULL, the default context will be used)
1686 * @source_id: the source ID, as returned by g_source_get_id().
1688 * Finds a #GSource given a pair of context and ID.
1690 * Return value: (transfer none): the #GSource if found, otherwise, %NULL
1693 g_main_context_find_source_by_id (GMainContext *context,
1698 g_return_val_if_fail (source_id > 0, NULL);
1700 if (context == NULL)
1701 context = g_main_context_default ();
1703 LOCK_CONTEXT (context);
1705 source = context->source_list;
1708 if (!SOURCE_DESTROYED (source) &&
1709 source->source_id == source_id)
1711 source = source->next;
1714 UNLOCK_CONTEXT (context);
1720 * g_main_context_find_source_by_funcs_user_data:
1721 * @context: a #GMainContext (if %NULL, the default context will be used).
1722 * @funcs: the @source_funcs passed to g_source_new().
1723 * @user_data: the user data from the callback.
1725 * Finds a source with the given source functions and user data. If
1726 * multiple sources exist with the same source function and user data,
1727 * the first one found will be returned.
1729 * Return value: (transfer none): the source, if one was found, otherwise %NULL
1732 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1733 GSourceFuncs *funcs,
1738 g_return_val_if_fail (funcs != NULL, NULL);
1740 if (context == NULL)
1741 context = g_main_context_default ();
1743 LOCK_CONTEXT (context);
1745 source = context->source_list;
1748 if (!SOURCE_DESTROYED (source) &&
1749 source->source_funcs == funcs &&
1750 source->callback_funcs)
1752 GSourceFunc callback;
1753 gpointer callback_data;
1755 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1757 if (callback_data == user_data)
1760 source = source->next;
1763 UNLOCK_CONTEXT (context);
1769 * g_main_context_find_source_by_user_data:
1770 * @context: a #GMainContext
1771 * @user_data: the user_data for the callback.
1773 * Finds a source with the given user data for the callback. If
1774 * multiple sources exist with the same user data, the first
1775 * one found will be returned.
1777 * Return value: (transfer none): the source, if one was found, otherwise %NULL
1780 g_main_context_find_source_by_user_data (GMainContext *context,
1785 if (context == NULL)
1786 context = g_main_context_default ();
1788 LOCK_CONTEXT (context);
1790 source = context->source_list;
1793 if (!SOURCE_DESTROYED (source) &&
1794 source->callback_funcs)
1796 GSourceFunc callback;
1797 gpointer callback_data = NULL;
1799 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1801 if (callback_data == user_data)
1804 source = source->next;
1807 UNLOCK_CONTEXT (context);
1814 * @tag: the ID of the source to remove.
1816 * Removes the source with the given id from the default main context.
1818 * a #GSource is given by g_source_get_id(), or will be returned by the
1819 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1820 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1821 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1823 * See also g_source_destroy(). You must use g_source_destroy() for sources
1824 * added to a non-default main context.
1826 * Return value: %TRUE if the source was found and removed.
1829 g_source_remove (guint tag)
1833 g_return_val_if_fail (tag > 0, FALSE);
1835 source = g_main_context_find_source_by_id (NULL, tag);
1837 g_source_destroy (source);
1839 return source != NULL;
1843 * g_source_remove_by_user_data:
1844 * @user_data: the user_data for the callback.
1846 * Removes a source from the default main loop context given the user
1847 * data for the callback. If multiple sources exist with the same user
1848 * data, only one will be destroyed.
1850 * Return value: %TRUE if a source was found and removed.
1853 g_source_remove_by_user_data (gpointer user_data)
1857 source = g_main_context_find_source_by_user_data (NULL, user_data);
1860 g_source_destroy (source);
1868 * g_source_remove_by_funcs_user_data:
1869 * @funcs: The @source_funcs passed to g_source_new()
1870 * @user_data: the user data for the callback
1872 * Removes a source from the default main loop context given the
1873 * source functions and user data. If multiple sources exist with the
1874 * same source functions and user data, only one will be destroyed.
1876 * Return value: %TRUE if a source was found and removed.
1879 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1884 g_return_val_if_fail (funcs != NULL, FALSE);
1886 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1889 g_source_destroy (source);
1897 * g_get_current_time:
1898 * @result: #GTimeVal structure in which to store current time.
1900 * Equivalent to the UNIX gettimeofday() function, but portable.
1902 * You may find g_get_real_time() to be more convenient.
1905 g_get_current_time (GTimeVal *result)
1910 g_return_if_fail (result != NULL);
1912 /*this is required on alpha, there the timeval structs are int's
1913 not longs and a cast only would fail horribly*/
1914 gettimeofday (&r, NULL);
1915 result->tv_sec = r.tv_sec;
1916 result->tv_usec = r.tv_usec;
1921 g_return_if_fail (result != NULL);
1923 GetSystemTimeAsFileTime (&ft);
1924 memmove (&time64, &ft, sizeof (FILETIME));
1926 /* Convert from 100s of nanoseconds since 1601-01-01
1927 * to Unix epoch. Yes, this is Y2038 unsafe.
1929 time64 -= G_GINT64_CONSTANT (116444736000000000);
1932 result->tv_sec = time64 / 1000000;
1933 result->tv_usec = time64 % 1000000;
1940 * Queries the system wall-clock time.
1942 * This call is functionally equivalent to g_get_current_time() except
1943 * that the return value is often more convenient than dealing with a
1946 * You should only use this call if you are actually interested in the real
1947 * wall-clock time. g_get_monotonic_time() is probably more useful for
1948 * measuring intervals.
1950 * Returns: the number of microseconds since January 1, 1970 UTC.
1955 g_get_real_time (void)
1959 g_get_current_time (&tv);
1961 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
1965 * g_get_monotonic_time:
1967 * Queries the system monotonic time, if available.
1969 * On POSIX systems with clock_gettime() and %CLOCK_MONOTONIC this call
1970 * is a very shallow wrapper for that. Otherwise, we make a best effort
1971 * that probably involves returning the wall clock time (with at least
1972 * microsecond accuracy, subject to the limitations of the OS kernel).
1974 * It's important to note that POSIX %CLOCK_MONOTONIC does not count
1975 * time spent while the machine is suspended.
1977 * On Windows, "limitations of the OS kernel" is a rather substantial
1978 * statement. Depending on the configuration of the system, the wall
1979 * clock time is updated as infrequently as 64 times a second (which
1980 * is approximately every 16ms).
1982 * Returns: the monotonic time, in microseconds
1987 g_get_monotonic_time (void)
1989 #ifdef HAVE_CLOCK_GETTIME
1990 /* librt clock_gettime() is our first choice */
1992 #ifdef HAVE_MONOTONIC_CLOCK
1993 static volatile gsize clockid = 0;
1995 static clockid_t clockid = CLOCK_REALTIME;
1999 #ifdef HAVE_MONOTONIC_CLOCK
2000 if (g_once_init_enter (&clockid))
2002 clockid_t best_clockid;
2004 if (sysconf (_SC_MONOTONIC_CLOCK) >= 0)
2005 best_clockid = CLOCK_MONOTONIC;
2007 best_clockid = CLOCK_REALTIME;
2008 g_once_init_leave (&clockid, (gsize)best_clockid);
2012 clock_gettime (clockid, &ts);
2014 /* In theory monotonic time can have any epoch.
2016 * glib presently assumes the following:
2018 * 1) The epoch comes some time after the birth of Jesus of Nazareth, but
2019 * not more than 10000 years later.
2021 * 2) The current time also falls sometime within this range.
2023 * These two reasonable assumptions leave us with a maximum deviation from
2024 * the epoch of 10000 years, or 315569520000000000 seconds.
2026 * If we restrict ourselves to this range then the number of microseconds
2027 * will always fit well inside the constraints of a int64 (by a factor of
2030 * If you actually hit the following assertion, probably you should file a
2031 * bug against your operating system for being excessively silly.
2033 g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts.tv_sec &&
2034 ts.tv_sec < G_GINT64_CONSTANT (315569520000000000));
2036 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2039 /* It may look like we are discarding accuracy on Windows (since its
2040 * current time is expressed in 100s of nanoseconds) but according to
2041 * many sources, the time is only updated 64 times per second, so
2042 * microsecond accuracy is more than enough.
2047 g_get_current_time (&tv);
2049 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2055 g_main_dispatch_free (gpointer dispatch)
2057 g_slice_free (GMainDispatch, dispatch);
2060 /* Running the main loop */
2062 static GMainDispatch *
2065 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
2066 GMainDispatch *dispatch = g_static_private_get (&depth_private);
2069 dispatch = g_slice_new0 (GMainDispatch);
2070 g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
2079 * Returns the depth of the stack of calls to
2080 * g_main_context_dispatch() on any #GMainContext in the current thread.
2081 * That is, when called from the toplevel, it gives 0. When
2082 * called from within a callback from g_main_context_iteration()
2083 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2084 * a callback to a recursive call to g_main_context_iteration(),
2085 * it returns 2. And so forth.
2087 * This function is useful in a situation like the following:
2088 * Imagine an extremely simple "garbage collected" system.
2091 * static GList *free_list;
2094 * allocate_memory (gsize size)
2096 * gpointer result = g_malloc (size);
2097 * free_list = g_list_prepend (free_list, result);
2102 * free_allocated_memory (void)
2105 * for (l = free_list; l; l = l->next);
2107 * g_list_free (free_list);
2115 * g_main_context_iteration (NULL, TRUE);
2116 * free_allocated_memory();
2120 * This works from an application, however, if you want to do the same
2121 * thing from a library, it gets more difficult, since you no longer
2122 * control the main loop. You might think you can simply use an idle
2123 * function to make the call to free_allocated_memory(), but that
2124 * doesn't work, since the idle function could be called from a
2125 * recursive callback. This can be fixed by using g_main_depth()
2129 * allocate_memory (gsize size)
2131 * FreeListBlock *block = g_new (FreeListBlock, 1);
2132 * block->mem = g_malloc (size);
2133 * block->depth = g_main_depth ();
2134 * free_list = g_list_prepend (free_list, block);
2135 * return block->mem;
2139 * free_allocated_memory (void)
2143 * int depth = g_main_depth ();
2144 * for (l = free_list; l; );
2146 * GList *next = l->next;
2147 * FreeListBlock *block = l->data;
2148 * if (block->depth > depth)
2150 * g_free (block->mem);
2152 * free_list = g_list_delete_link (free_list, l);
2160 * There is a temptation to use g_main_depth() to solve
2161 * problems with reentrancy. For instance, while waiting for data
2162 * to be received from the network in response to a menu item,
2163 * the menu item might be selected again. It might seem that
2164 * one could make the menu item's callback return immediately
2165 * and do nothing if g_main_depth() returns a value greater than 1.
2166 * However, this should be avoided since the user then sees selecting
2167 * the menu item do nothing. Furthermore, you'll find yourself adding
2168 * these checks all over your code, since there are doubtless many,
2169 * many things that the user could do. Instead, you can use the
2170 * following techniques:
2175 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
2176 * the user from interacting with elements while the main
2177 * loop is recursing.
2182 * Avoid main loop recursion in situations where you can't handle
2183 * arbitrary callbacks. Instead, structure your code so that you
2184 * simply return to the main loop and then get called again when
2185 * there is more work to do.
2190 * Return value: The main loop recursion level in the current thread
2195 GMainDispatch *dispatch = get_dispatch ();
2196 return dispatch->depth;
2200 * g_main_current_source:
2202 * Returns the currently firing source for this thread.
2204 * Return value: (transfer none): The currently firing source or %NULL.
2209 g_main_current_source (void)
2211 GMainDispatch *dispatch = get_dispatch ();
2212 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
2216 * g_source_is_destroyed:
2217 * @source: a #GSource
2219 * Returns whether @source has been destroyed.
2221 * This is important when you operate upon your objects
2222 * from within idle handlers, but may have freed the object
2223 * before the dispatch of your idle handler.
2227 * idle_callback (gpointer data)
2229 * SomeWidget *self = data;
2231 * GDK_THREADS_ENTER (<!-- -->);
2232 * /<!-- -->* do stuff with self *<!-- -->/
2233 * self->idle_id = 0;
2234 * GDK_THREADS_LEAVE (<!-- -->);
2240 * some_widget_do_stuff_later (SomeWidget *self)
2242 * self->idle_id = g_idle_add (idle_callback, self);
2246 * some_widget_finalize (GObject *object)
2248 * SomeWidget *self = SOME_WIDGET (object);
2250 * if (self->idle_id)
2251 * g_source_remove (self->idle_id);
2253 * G_OBJECT_CLASS (parent_class)->finalize (object);
2257 * This will fail in a multi-threaded application if the
2258 * widget is destroyed before the idle handler fires due
2259 * to the use after free in the callback. A solution, to
2260 * this particular problem, is to check to if the source
2261 * has already been destroy within the callback.
2265 * idle_callback (gpointer data)
2267 * SomeWidget *self = data;
2269 * GDK_THREADS_ENTER ();
2270 * if (!g_source_is_destroyed (g_main_current_source ()))
2272 * /<!-- -->* do stuff with self *<!-- -->/
2274 * GDK_THREADS_LEAVE ();
2280 * Return value: %TRUE if the source has been destroyed
2285 g_source_is_destroyed (GSource *source)
2287 return SOURCE_DESTROYED (source);
2290 /* Temporarily remove all this source's file descriptors from the
2291 * poll(), so that if data comes available for one of the file descriptors
2292 * we don't continually spin in the poll()
2294 /* HOLDS: source->context's lock */
2296 block_source (GSource *source)
2300 g_return_if_fail (!SOURCE_BLOCKED (source));
2302 tmp_list = source->poll_fds;
2305 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2306 tmp_list = tmp_list->next;
2310 /* HOLDS: source->context's lock */
2312 unblock_source (GSource *source)
2316 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
2317 g_return_if_fail (!SOURCE_DESTROYED (source));
2319 tmp_list = source->poll_fds;
2322 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2323 tmp_list = tmp_list->next;
2327 /* HOLDS: context's lock */
2329 g_main_dispatch (GMainContext *context)
2331 GMainDispatch *current = get_dispatch ();
2334 for (i = 0; i < context->pending_dispatches->len; i++)
2336 GSource *source = context->pending_dispatches->pdata[i];
2338 context->pending_dispatches->pdata[i] = NULL;
2341 source->flags &= ~G_SOURCE_READY;
2343 if (!SOURCE_DESTROYED (source))
2345 gboolean was_in_call;
2346 gpointer user_data = NULL;
2347 GSourceFunc callback = NULL;
2348 GSourceCallbackFuncs *cb_funcs;
2350 gboolean need_destroy;
2352 gboolean (*dispatch) (GSource *,
2355 GSList current_source_link;
2357 dispatch = source->source_funcs->dispatch;
2358 cb_funcs = source->callback_funcs;
2359 cb_data = source->callback_data;
2362 cb_funcs->ref (cb_data);
2364 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2365 block_source (source);
2367 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2368 source->flags |= G_HOOK_FLAG_IN_CALL;
2371 cb_funcs->get (cb_data, source, &callback, &user_data);
2373 UNLOCK_CONTEXT (context);
2376 /* The on-stack allocation of the GSList is unconventional, but
2377 * we know that the lifetime of the link is bounded to this
2378 * function as the link is kept in a thread specific list and
2379 * not manipulated outside of this function and its descendants.
2380 * Avoiding the overhead of a g_slist_alloc() is useful as many
2381 * applications do little more than dispatch events.
2383 * This is a performance hack - do not revert to g_slist_prepend()!
2385 current_source_link.data = source;
2386 current_source_link.next = current->dispatching_sources;
2387 current->dispatching_sources = ¤t_source_link;
2388 need_destroy = ! dispatch (source,
2391 g_assert (current->dispatching_sources == ¤t_source_link);
2392 current->dispatching_sources = current_source_link.next;
2396 cb_funcs->unref (cb_data);
2398 LOCK_CONTEXT (context);
2401 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2403 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2404 !SOURCE_DESTROYED (source))
2405 unblock_source (source);
2407 /* Note: this depends on the fact that we can't switch
2408 * sources from one main context to another
2410 if (need_destroy && !SOURCE_DESTROYED (source))
2412 g_assert (source->context == context);
2413 g_source_destroy_internal (source, context, TRUE);
2417 SOURCE_UNREF (source, context);
2420 g_ptr_array_set_size (context->pending_dispatches, 0);
2423 /* Holds context's lock */
2424 static inline GSource *
2425 next_valid_source (GMainContext *context,
2428 GSource *new_source = source ? source->next : context->source_list;
2432 if (!SOURCE_DESTROYED (new_source))
2434 new_source->ref_count++;
2438 new_source = new_source->next;
2442 SOURCE_UNREF (source, context);
2448 * g_main_context_acquire:
2449 * @context: a #GMainContext
2451 * Tries to become the owner of the specified context.
2452 * If some other thread is the owner of the context,
2453 * returns %FALSE immediately. Ownership is properly
2454 * recursive: the owner can require ownership again
2455 * and will release ownership when g_main_context_release()
2456 * is called as many times as g_main_context_acquire().
2458 * You must be the owner of a context before you
2459 * can call g_main_context_prepare(), g_main_context_query(),
2460 * g_main_context_check(), g_main_context_dispatch().
2462 * Return value: %TRUE if the operation succeeded, and
2463 * this thread is now the owner of @context.
2466 g_main_context_acquire (GMainContext *context)
2468 gboolean result = FALSE;
2469 GThread *self = G_THREAD_SELF;
2471 if (context == NULL)
2472 context = g_main_context_default ();
2474 LOCK_CONTEXT (context);
2476 if (!context->owner)
2478 context->owner = self;
2479 g_assert (context->owner_count == 0);
2482 if (context->owner == self)
2484 context->owner_count++;
2488 UNLOCK_CONTEXT (context);
2494 * g_main_context_release:
2495 * @context: a #GMainContext
2497 * Releases ownership of a context previously acquired by this thread
2498 * with g_main_context_acquire(). If the context was acquired multiple
2499 * times, the ownership will be released only when g_main_context_release()
2500 * is called as many times as it was acquired.
2503 g_main_context_release (GMainContext *context)
2505 if (context == NULL)
2506 context = g_main_context_default ();
2508 LOCK_CONTEXT (context);
2510 context->owner_count--;
2511 if (context->owner_count == 0)
2513 context->owner = NULL;
2515 if (context->waiters)
2517 GMainWaiter *waiter = context->waiters->data;
2518 gboolean loop_internal_waiter =
2519 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
2520 context->waiters = g_slist_delete_link (context->waiters,
2522 if (!loop_internal_waiter)
2523 g_mutex_lock (waiter->mutex);
2525 g_cond_signal (waiter->cond);
2527 if (!loop_internal_waiter)
2528 g_mutex_unlock (waiter->mutex);
2532 UNLOCK_CONTEXT (context);
2536 * g_main_context_wait:
2537 * @context: a #GMainContext
2538 * @cond: a condition variable
2539 * @mutex: a mutex, currently held
2541 * Tries to become the owner of the specified context,
2542 * as with g_main_context_acquire(). But if another thread
2543 * is the owner, atomically drop @mutex and wait on @cond until
2544 * that owner releases ownership or until @cond is signaled, then
2545 * try again (once) to become the owner.
2547 * Return value: %TRUE if the operation succeeded, and
2548 * this thread is now the owner of @context.
2551 g_main_context_wait (GMainContext *context,
2555 gboolean result = FALSE;
2556 GThread *self = G_THREAD_SELF;
2557 gboolean loop_internal_waiter;
2559 if (context == NULL)
2560 context = g_main_context_default ();
2562 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2564 if (!loop_internal_waiter)
2565 LOCK_CONTEXT (context);
2567 if (context->owner && context->owner != self)
2572 waiter.mutex = mutex;
2574 context->waiters = g_slist_append (context->waiters, &waiter);
2576 if (!loop_internal_waiter)
2577 UNLOCK_CONTEXT (context);
2578 g_cond_wait (cond, mutex);
2579 if (!loop_internal_waiter)
2580 LOCK_CONTEXT (context);
2582 context->waiters = g_slist_remove (context->waiters, &waiter);
2585 if (!context->owner)
2587 context->owner = self;
2588 g_assert (context->owner_count == 0);
2591 if (context->owner == self)
2593 context->owner_count++;
2597 if (!loop_internal_waiter)
2598 UNLOCK_CONTEXT (context);
2604 * g_main_context_prepare:
2605 * @context: a #GMainContext
2606 * @priority: location to store priority of highest priority
2607 * source already ready.
2609 * Prepares to poll sources within a main loop. The resulting information
2610 * for polling is determined by calling g_main_context_query ().
2612 * Return value: %TRUE if some source is ready to be dispatched
2616 g_main_context_prepare (GMainContext *context,
2621 gint current_priority = G_MAXINT;
2624 if (context == NULL)
2625 context = g_main_context_default ();
2627 LOCK_CONTEXT (context);
2629 context->time_is_fresh = FALSE;
2631 if (context->in_check_or_prepare)
2633 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2634 "prepare() member.");
2635 UNLOCK_CONTEXT (context);
2640 /* If recursing, finish up current dispatch, before starting over */
2641 if (context->pending_dispatches)
2644 g_main_dispatch (context, ¤t_time);
2646 UNLOCK_CONTEXT (context);
2651 /* If recursing, clear list of pending dispatches */
2653 for (i = 0; i < context->pending_dispatches->len; i++)
2655 if (context->pending_dispatches->pdata[i])
2656 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2658 g_ptr_array_set_size (context->pending_dispatches, 0);
2660 /* Prepare all sources */
2662 context->timeout = -1;
2664 source = next_valid_source (context, NULL);
2667 gint source_timeout = -1;
2669 if ((n_ready > 0) && (source->priority > current_priority))
2671 SOURCE_UNREF (source, context);
2674 if (SOURCE_BLOCKED (source))
2677 if (!(source->flags & G_SOURCE_READY))
2680 gboolean (*prepare) (GSource *source,
2683 prepare = source->source_funcs->prepare;
2684 context->in_check_or_prepare++;
2685 UNLOCK_CONTEXT (context);
2687 result = (*prepare) (source, &source_timeout);
2689 LOCK_CONTEXT (context);
2690 context->in_check_or_prepare--;
2694 GSource *ready_source = source;
2696 while (ready_source)
2698 ready_source->flags |= G_SOURCE_READY;
2699 ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2704 if (source->flags & G_SOURCE_READY)
2707 current_priority = source->priority;
2708 context->timeout = 0;
2711 if (source_timeout >= 0)
2713 if (context->timeout < 0)
2714 context->timeout = source_timeout;
2716 context->timeout = MIN (context->timeout, source_timeout);
2720 source = next_valid_source (context, source);
2723 UNLOCK_CONTEXT (context);
2726 *priority = current_priority;
2728 return (n_ready > 0);
2732 * g_main_context_query:
2733 * @context: a #GMainContext
2734 * @max_priority: maximum priority source to check
2735 * @timeout_: (out): location to store timeout to be used in polling
2736 * @fds: (out caller-allocates) (array length=n_fds): location to
2737 * store #GPollFD records that need to be polled.
2738 * @n_fds: length of @fds.
2740 * Determines information necessary to poll this main loop.
2742 * Return value: the number of records actually stored in @fds,
2743 * or, if more than @n_fds records need to be stored, the number
2744 * of records that need to be stored.
2747 g_main_context_query (GMainContext *context,
2756 LOCK_CONTEXT (context);
2758 pollrec = context->poll_records;
2760 while (pollrec && max_priority >= pollrec->priority)
2762 /* We need to include entries with fd->events == 0 in the array because
2763 * otherwise if the application changes fd->events behind our back and
2764 * makes it non-zero, we'll be out of sync when we check the fds[] array.
2765 * (Changing fd->events after adding an FD wasn't an anticipated use of
2766 * this API, but it occurs in practice.) */
2769 fds[n_poll].fd = pollrec->fd->fd;
2770 /* In direct contradiction to the Unix98 spec, IRIX runs into
2771 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2772 * flags in the events field of the pollfd while it should
2773 * just ignoring them. So we mask them out here.
2775 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2776 fds[n_poll].revents = 0;
2779 pollrec = pollrec->next;
2783 context->poll_changed = FALSE;
2787 *timeout = context->timeout;
2789 context->time_is_fresh = FALSE;
2792 UNLOCK_CONTEXT (context);
2798 * g_main_context_check:
2799 * @context: a #GMainContext
2800 * @max_priority: the maximum numerical priority of sources to check
2801 * @fds: (array length=n_fds): array of #GPollFD's that was passed to
2802 * the last call to g_main_context_query()
2803 * @n_fds: return value of g_main_context_query()
2805 * Passes the results of polling back to the main loop.
2807 * Return value: %TRUE if some sources are ready to be dispatched.
2810 g_main_context_check (GMainContext *context,
2820 LOCK_CONTEXT (context);
2822 if (context->in_check_or_prepare)
2824 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2825 "prepare() member.");
2826 UNLOCK_CONTEXT (context);
2830 if (context->wake_up_rec.events)
2831 g_wakeup_acknowledge (context->wakeup);
2833 /* If the set of poll file descriptors changed, bail out
2834 * and let the main loop rerun
2836 if (context->poll_changed)
2838 UNLOCK_CONTEXT (context);
2842 pollrec = context->poll_records;
2846 if (pollrec->fd->events)
2847 pollrec->fd->revents = fds[i].revents;
2849 pollrec = pollrec->next;
2853 source = next_valid_source (context, NULL);
2856 if ((n_ready > 0) && (source->priority > max_priority))
2858 SOURCE_UNREF (source, context);
2861 if (SOURCE_BLOCKED (source))
2864 if (!(source->flags & G_SOURCE_READY))
2867 gboolean (*check) (GSource *source);
2869 check = source->source_funcs->check;
2871 context->in_check_or_prepare++;
2872 UNLOCK_CONTEXT (context);
2874 result = (*check) (source);
2876 LOCK_CONTEXT (context);
2877 context->in_check_or_prepare--;
2881 GSource *ready_source = source;
2883 while (ready_source)
2885 ready_source->flags |= G_SOURCE_READY;
2886 ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2891 if (source->flags & G_SOURCE_READY)
2893 source->ref_count++;
2894 g_ptr_array_add (context->pending_dispatches, source);
2898 /* never dispatch sources with less priority than the first
2899 * one we choose to dispatch
2901 max_priority = source->priority;
2905 source = next_valid_source (context, source);
2908 UNLOCK_CONTEXT (context);
2914 * g_main_context_dispatch:
2915 * @context: a #GMainContext
2917 * Dispatches all pending sources.
2920 g_main_context_dispatch (GMainContext *context)
2922 LOCK_CONTEXT (context);
2924 if (context->pending_dispatches->len > 0)
2926 g_main_dispatch (context);
2929 UNLOCK_CONTEXT (context);
2932 /* HOLDS context lock */
2934 g_main_context_iterate (GMainContext *context,
2941 gboolean some_ready;
2942 gint nfds, allocated_nfds;
2943 GPollFD *fds = NULL;
2945 UNLOCK_CONTEXT (context);
2947 if (!g_main_context_acquire (context))
2949 gboolean got_ownership;
2951 LOCK_CONTEXT (context);
2957 context->cond = g_cond_new ();
2959 got_ownership = g_main_context_wait (context,
2961 g_static_mutex_get_mutex (&context->mutex));
2967 LOCK_CONTEXT (context);
2969 if (!context->cached_poll_array)
2971 context->cached_poll_array_size = context->n_poll_records;
2972 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2975 allocated_nfds = context->cached_poll_array_size;
2976 fds = context->cached_poll_array;
2978 UNLOCK_CONTEXT (context);
2980 g_main_context_prepare (context, &max_priority);
2982 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
2983 allocated_nfds)) > allocated_nfds)
2985 LOCK_CONTEXT (context);
2987 context->cached_poll_array_size = allocated_nfds = nfds;
2988 context->cached_poll_array = fds = g_new (GPollFD, nfds);
2989 UNLOCK_CONTEXT (context);
2995 g_assert (!g_main_context_fork_detected);
2996 g_main_context_poll (context, timeout, max_priority, fds, nfds);
2998 some_ready = g_main_context_check (context, max_priority, fds, nfds);
3001 g_main_context_dispatch (context);
3003 g_main_context_release (context);
3005 LOCK_CONTEXT (context);
3011 * g_main_context_pending:
3012 * @context: a #GMainContext (if %NULL, the default context will be used)
3014 * Checks if any sources have pending events for the given context.
3016 * Return value: %TRUE if events are pending.
3019 g_main_context_pending (GMainContext *context)
3024 context = g_main_context_default();
3026 LOCK_CONTEXT (context);
3027 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3028 UNLOCK_CONTEXT (context);
3034 * g_main_context_iteration:
3035 * @context: a #GMainContext (if %NULL, the default context will be used)
3036 * @may_block: whether the call may block.
3038 * Runs a single iteration for the given main loop. This involves
3039 * checking to see if any event sources are ready to be processed,
3040 * then if no events sources are ready and @may_block is %TRUE, waiting
3041 * for a source to become ready, then dispatching the highest priority
3042 * events sources that are ready. Otherwise, if @may_block is %FALSE
3043 * sources are not waited to become ready, only those highest priority
3044 * events sources will be dispatched (if any), that are ready at this
3045 * given moment without further waiting.
3047 * Note that even when @may_block is %TRUE, it is still possible for
3048 * g_main_context_iteration() to return %FALSE, since the the wait may
3049 * be interrupted for other reasons than an event source becoming ready.
3051 * Return value: %TRUE if events were dispatched.
3054 g_main_context_iteration (GMainContext *context, gboolean may_block)
3059 context = g_main_context_default();
3061 LOCK_CONTEXT (context);
3062 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3063 UNLOCK_CONTEXT (context);
3070 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
3071 * @is_running: set to %TRUE to indicate that the loop is running. This
3072 * is not very important since calling g_main_loop_run() will set this to
3075 * Creates a new #GMainLoop structure.
3077 * Return value: a new #GMainLoop.
3080 g_main_loop_new (GMainContext *context,
3081 gboolean is_running)
3086 context = g_main_context_default();
3088 g_main_context_ref (context);
3090 loop = g_new0 (GMainLoop, 1);
3091 loop->context = context;
3092 loop->is_running = is_running != FALSE;
3093 loop->ref_count = 1;
3100 * @loop: a #GMainLoop
3102 * Increases the reference count on a #GMainLoop object by one.
3104 * Return value: @loop
3107 g_main_loop_ref (GMainLoop *loop)
3109 g_return_val_if_fail (loop != NULL, NULL);
3110 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3112 g_atomic_int_inc (&loop->ref_count);
3118 * g_main_loop_unref:
3119 * @loop: a #GMainLoop
3121 * Decreases the reference count on a #GMainLoop object by one. If
3122 * the result is zero, free the loop and free all associated memory.
3125 g_main_loop_unref (GMainLoop *loop)
3127 g_return_if_fail (loop != NULL);
3128 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3130 if (!g_atomic_int_dec_and_test (&loop->ref_count))
3133 g_main_context_unref (loop->context);
3139 * @loop: a #GMainLoop
3141 * Runs a main loop until g_main_loop_quit() is called on the loop.
3142 * If this is called for the thread of the loop's #GMainContext,
3143 * it will process events from the loop, otherwise it will
3147 g_main_loop_run (GMainLoop *loop)
3149 GThread *self = G_THREAD_SELF;
3151 g_return_if_fail (loop != NULL);
3152 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3154 if (!g_main_context_acquire (loop->context))
3156 gboolean got_ownership = FALSE;
3158 /* Another thread owns this context */
3159 LOCK_CONTEXT (loop->context);
3161 g_atomic_int_inc (&loop->ref_count);
3163 if (!loop->is_running)
3164 loop->is_running = TRUE;
3166 if (!loop->context->cond)
3167 loop->context->cond = g_cond_new ();
3169 while (loop->is_running && !got_ownership)
3170 got_ownership = g_main_context_wait (loop->context,
3171 loop->context->cond,
3172 g_static_mutex_get_mutex (&loop->context->mutex));
3174 if (!loop->is_running)
3176 UNLOCK_CONTEXT (loop->context);
3178 g_main_context_release (loop->context);
3179 g_main_loop_unref (loop);
3183 g_assert (got_ownership);
3186 LOCK_CONTEXT (loop->context);
3188 if (loop->context->in_check_or_prepare)
3190 g_warning ("g_main_loop_run(): called recursively from within a source's "
3191 "check() or prepare() member, iteration not possible.");
3195 g_atomic_int_inc (&loop->ref_count);
3196 loop->is_running = TRUE;
3197 while (loop->is_running)
3198 g_main_context_iterate (loop->context, TRUE, TRUE, self);
3200 UNLOCK_CONTEXT (loop->context);
3202 g_main_context_release (loop->context);
3204 g_main_loop_unref (loop);
3209 * @loop: a #GMainLoop
3211 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3212 * for the loop will return.
3214 * Note that sources that have already been dispatched when
3215 * g_main_loop_quit() is called will still be executed.
3218 g_main_loop_quit (GMainLoop *loop)
3220 g_return_if_fail (loop != NULL);
3221 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3223 LOCK_CONTEXT (loop->context);
3224 loop->is_running = FALSE;
3225 g_wakeup_signal (loop->context->wakeup);
3227 if (loop->context->cond)
3228 g_cond_broadcast (loop->context->cond);
3230 UNLOCK_CONTEXT (loop->context);
3234 * g_main_loop_is_running:
3235 * @loop: a #GMainLoop.
3237 * Checks to see if the main loop is currently being run via g_main_loop_run().
3239 * Return value: %TRUE if the mainloop is currently being run.
3242 g_main_loop_is_running (GMainLoop *loop)
3244 g_return_val_if_fail (loop != NULL, FALSE);
3245 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3247 return loop->is_running;
3251 * g_main_loop_get_context:
3252 * @loop: a #GMainLoop.
3254 * Returns the #GMainContext of @loop.
3256 * Return value: (transfer none): the #GMainContext of @loop
3259 g_main_loop_get_context (GMainLoop *loop)
3261 g_return_val_if_fail (loop != NULL, NULL);
3262 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3264 return loop->context;
3267 /* HOLDS: context's lock */
3269 g_main_context_poll (GMainContext *context,
3275 #ifdef G_MAIN_POLL_DEBUG
3281 GPollFunc poll_func;
3283 if (n_fds || timeout != 0)
3285 #ifdef G_MAIN_POLL_DEBUG
3286 if (_g_main_poll_debug)
3288 g_print ("polling context=%p n=%d timeout=%d\n",
3289 context, n_fds, timeout);
3290 poll_timer = g_timer_new ();
3294 LOCK_CONTEXT (context);
3296 poll_func = context->poll_func;
3298 UNLOCK_CONTEXT (context);
3299 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3302 g_warning ("poll(2) failed due to: %s.",
3303 g_strerror (errno));
3305 /* If g_poll () returns -1, it has already called g_warning() */
3309 #ifdef G_MAIN_POLL_DEBUG
3310 if (_g_main_poll_debug)
3312 LOCK_CONTEXT (context);
3314 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3317 g_timer_elapsed (poll_timer, NULL));
3318 g_timer_destroy (poll_timer);
3319 pollrec = context->poll_records;
3321 while (pollrec != NULL)
3326 if (fds[i].fd == pollrec->fd->fd &&
3327 pollrec->fd->events &&
3330 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3331 if (fds[i].revents & G_IO_IN)
3333 if (fds[i].revents & G_IO_OUT)
3335 if (fds[i].revents & G_IO_PRI)
3337 if (fds[i].revents & G_IO_ERR)
3339 if (fds[i].revents & G_IO_HUP)
3341 if (fds[i].revents & G_IO_NVAL)
3347 pollrec = pollrec->next;
3351 UNLOCK_CONTEXT (context);
3354 } /* if (n_fds || timeout != 0) */
3358 * g_main_context_add_poll:
3359 * @context: a #GMainContext (or %NULL for the default context)
3360 * @fd: a #GPollFD structure holding information about a file
3361 * descriptor to watch.
3362 * @priority: the priority for this file descriptor which should be
3363 * the same as the priority used for g_source_attach() to ensure that the
3364 * file descriptor is polled whenever the results may be needed.
3366 * Adds a file descriptor to the set of file descriptors polled for
3367 * this context. This will very seldom be used directly. Instead
3368 * a typical event source will use g_source_add_poll() instead.
3371 g_main_context_add_poll (GMainContext *context,
3376 context = g_main_context_default ();
3378 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3379 g_return_if_fail (fd);
3381 LOCK_CONTEXT (context);
3382 g_main_context_add_poll_unlocked (context, priority, fd);
3383 UNLOCK_CONTEXT (context);
3386 /* HOLDS: main_loop_lock */
3388 g_main_context_add_poll_unlocked (GMainContext *context,
3392 GPollRec *prevrec, *nextrec;
3393 GPollRec *newrec = g_slice_new (GPollRec);
3395 /* This file descriptor may be checked before we ever poll */
3398 newrec->priority = priority;
3400 prevrec = context->poll_records_tail;
3402 while (prevrec && priority < prevrec->priority)
3405 prevrec = prevrec->prev;
3409 prevrec->next = newrec;
3411 context->poll_records = newrec;
3413 newrec->prev = prevrec;
3414 newrec->next = nextrec;
3417 nextrec->prev = newrec;
3419 context->poll_records_tail = newrec;
3421 context->n_poll_records++;
3423 context->poll_changed = TRUE;
3425 /* Now wake up the main loop if it is waiting in the poll() */
3426 g_wakeup_signal (context->wakeup);
3430 * g_main_context_remove_poll:
3431 * @context:a #GMainContext
3432 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3434 * Removes file descriptor from the set of file descriptors to be
3435 * polled for a particular context.
3438 g_main_context_remove_poll (GMainContext *context,
3442 context = g_main_context_default ();
3444 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3445 g_return_if_fail (fd);
3447 LOCK_CONTEXT (context);
3448 g_main_context_remove_poll_unlocked (context, fd);
3449 UNLOCK_CONTEXT (context);
3453 g_main_context_remove_poll_unlocked (GMainContext *context,
3456 GPollRec *pollrec, *prevrec, *nextrec;
3459 pollrec = context->poll_records;
3463 nextrec = pollrec->next;
3464 if (pollrec->fd == fd)
3466 if (prevrec != NULL)
3467 prevrec->next = nextrec;
3469 context->poll_records = nextrec;
3471 if (nextrec != NULL)
3472 nextrec->prev = prevrec;
3474 context->poll_records_tail = prevrec;
3476 g_slice_free (GPollRec, pollrec);
3478 context->n_poll_records--;
3485 context->poll_changed = TRUE;
3487 /* Now wake up the main loop if it is waiting in the poll() */
3488 g_wakeup_signal (context->wakeup);
3492 * g_source_get_current_time:
3493 * @source: a #GSource
3494 * @timeval: #GTimeVal structure in which to store current time.
3496 * This function ignores @source and is otherwise the same as
3497 * g_get_current_time().
3499 * Deprecated: 2.28: use g_source_get_time() instead
3502 g_source_get_current_time (GSource *source,
3505 g_get_current_time (timeval);
3509 * g_source_get_time:
3510 * @source: a #GSource
3512 * Gets the time to be used when checking this source. The advantage of
3513 * calling this function over calling g_get_monotonic_time() directly is
3514 * that when checking multiple sources, GLib can cache a single value
3515 * instead of having to repeatedly get the system monotonic time.
3517 * The time here is the system monotonic time, if available, or some
3518 * other reasonable alternative otherwise. See g_get_monotonic_time().
3520 * Returns: the monotonic time in microseconds
3525 g_source_get_time (GSource *source)
3527 GMainContext *context;
3530 g_return_val_if_fail (source->context != NULL, 0);
3532 context = source->context;
3534 LOCK_CONTEXT (context);
3536 if (!context->time_is_fresh)
3538 context->time = g_get_monotonic_time ();
3539 context->time_is_fresh = TRUE;
3542 result = context->time;
3544 UNLOCK_CONTEXT (context);
3550 * g_main_context_set_poll_func:
3551 * @context: a #GMainContext
3552 * @func: the function to call to poll all file descriptors
3554 * Sets the function to use to handle polling of file descriptors. It
3555 * will be used instead of the poll() system call
3556 * (or GLib's replacement function, which is used where
3557 * poll() isn't available).
3559 * This function could possibly be used to integrate the GLib event
3560 * loop with an external event loop.
3563 g_main_context_set_poll_func (GMainContext *context,
3567 context = g_main_context_default ();
3569 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3571 LOCK_CONTEXT (context);
3574 context->poll_func = func;
3576 context->poll_func = g_poll;
3578 UNLOCK_CONTEXT (context);
3582 * g_main_context_get_poll_func:
3583 * @context: a #GMainContext
3585 * Gets the poll function set by g_main_context_set_poll_func().
3587 * Return value: the poll function
3590 g_main_context_get_poll_func (GMainContext *context)
3595 context = g_main_context_default ();
3597 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3599 LOCK_CONTEXT (context);
3600 result = context->poll_func;
3601 UNLOCK_CONTEXT (context);
3607 * g_main_context_wakeup:
3608 * @context: a #GMainContext
3610 * If @context is currently waiting in a poll(), interrupt
3611 * the poll(), and continue the iteration process.
3614 g_main_context_wakeup (GMainContext *context)
3617 context = g_main_context_default ();
3619 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3621 g_wakeup_signal (context->wakeup);
3625 * g_main_context_is_owner:
3626 * @context: a #GMainContext
3628 * Determines whether this thread holds the (recursive)
3629 * ownership of this #GMainContext. This is useful to
3630 * know before waiting on another thread that may be
3631 * blocking to get ownership of @context.
3633 * Returns: %TRUE if current thread is owner of @context.
3638 g_main_context_is_owner (GMainContext *context)
3643 context = g_main_context_default ();
3645 LOCK_CONTEXT (context);
3646 is_owner = context->owner == G_THREAD_SELF;
3647 UNLOCK_CONTEXT (context);
3655 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3656 gint64 current_time)
3658 timeout_source->expiration = current_time +
3659 (guint64) timeout_source->interval * 1000;
3661 if (timeout_source->seconds)
3664 static gint timer_perturb = -1;
3666 if (timer_perturb == -1)
3669 * we want a per machine/session unique 'random' value; try the dbus
3670 * address first, that has a UUID in it. If there is no dbus, use the
3671 * hostname for hashing.
3673 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3674 if (!session_bus_address)
3675 session_bus_address = g_getenv ("HOSTNAME");
3676 if (session_bus_address)
3677 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
3682 /* We want the microseconds part of the timeout to land on the
3683 * 'timer_perturb' mark, but we need to make sure we don't try to
3684 * set the timeout in the past. We do this by ensuring that we
3685 * always only *increase* the expiration time by adding a full
3686 * second in the case that the microsecond portion decreases.
3688 timeout_source->expiration -= timer_perturb;
3690 remainder = timeout_source->expiration % 1000000;
3691 if (remainder >= 1000000/4)
3692 timeout_source->expiration += 1000000;
3694 timeout_source->expiration -= remainder;
3695 timeout_source->expiration += timer_perturb;
3700 g_timeout_prepare (GSource *source,
3703 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3704 gint64 now = g_source_get_time (source);
3706 if (now < timeout_source->expiration)
3708 /* Round up to ensure that we don't try again too early */
3709 *timeout = (timeout_source->expiration - now + 999) / 1000;
3718 g_timeout_check (GSource *source)
3720 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3721 gint64 now = g_source_get_time (source);
3723 return timeout_source->expiration <= now;
3727 g_timeout_dispatch (GSource *source,
3728 GSourceFunc callback,
3731 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3736 g_warning ("Timeout source dispatched without callback\n"
3737 "You must call g_source_set_callback().");
3741 again = callback (user_data);
3744 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
3750 * g_timeout_source_new:
3751 * @interval: the timeout interval in milliseconds.
3753 * Creates a new timeout source.
3755 * The source will not initially be associated with any #GMainContext
3756 * and must be added to one with g_source_attach() before it will be
3759 * The interval given is in terms of monotonic time, not wall clock
3760 * time. See g_get_monotonic_time().
3762 * Return value: the newly-created timeout source
3765 g_timeout_source_new (guint interval)
3767 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3768 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3770 timeout_source->interval = interval;
3771 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3777 * g_timeout_source_new_seconds:
3778 * @interval: the timeout interval in seconds
3780 * Creates a new timeout source.
3782 * The source will not initially be associated with any #GMainContext
3783 * and must be added to one with g_source_attach() before it will be
3786 * The scheduling granularity/accuracy of this timeout source will be
3789 * The interval given in terms of monotonic time, not wall clock time.
3790 * See g_get_monotonic_time().
3792 * Return value: the newly-created timeout source
3797 g_timeout_source_new_seconds (guint interval)
3799 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3800 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3802 timeout_source->interval = 1000 * interval;
3803 timeout_source->seconds = TRUE;
3805 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3812 * g_timeout_add_full:
3813 * @priority: the priority of the timeout source. Typically this will be in
3814 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3815 * @interval: the time between calls to the function, in milliseconds
3816 * (1/1000ths of a second)
3817 * @function: function to call
3818 * @data: data to pass to @function
3819 * @notify: function to call when the timeout is removed, or %NULL
3821 * Sets a function to be called at regular intervals, with the given
3822 * priority. The function is called repeatedly until it returns
3823 * %FALSE, at which point the timeout is automatically destroyed and
3824 * the function will not be called again. The @notify function is
3825 * called when the timeout is destroyed. The first call to the
3826 * function will be at the end of the first @interval.
3828 * Note that timeout functions may be delayed, due to the processing of other
3829 * event sources. Thus they should not be relied on for precise timing.
3830 * After each call to the timeout function, the time of the next
3831 * timeout is recalculated based on the current time and the given interval
3832 * (it does not try to 'catch up' time lost in delays).
3834 * This internally creates a main loop source using g_timeout_source_new()
3835 * and attaches it to the main loop context using g_source_attach(). You can
3836 * do these steps manually if you need greater control.
3838 * The interval given in terms of monotonic time, not wall clock time.
3839 * See g_get_monotonic_time().
3841 * Return value: the ID (greater than 0) of the event source.
3842 * Rename to: g_timeout_add
3845 g_timeout_add_full (gint priority,
3847 GSourceFunc function,
3849 GDestroyNotify notify)
3854 g_return_val_if_fail (function != NULL, 0);
3856 source = g_timeout_source_new (interval);
3858 if (priority != G_PRIORITY_DEFAULT)
3859 g_source_set_priority (source, priority);
3861 g_source_set_callback (source, function, data, notify);
3862 id = g_source_attach (source, NULL);
3863 g_source_unref (source);
3870 * @interval: the time between calls to the function, in milliseconds
3871 * (1/1000ths of a second)
3872 * @function: function to call
3873 * @data: data to pass to @function
3875 * Sets a function to be called at regular intervals, with the default
3876 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
3877 * until it returns %FALSE, at which point the timeout is automatically
3878 * destroyed and the function will not be called again. The first call
3879 * to the function will be at the end of the first @interval.
3881 * Note that timeout functions may be delayed, due to the processing of other
3882 * event sources. Thus they should not be relied on for precise timing.
3883 * After each call to the timeout function, the time of the next
3884 * timeout is recalculated based on the current time and the given interval
3885 * (it does not try to 'catch up' time lost in delays).
3887 * If you want to have a timer in the "seconds" range and do not care
3888 * about the exact time of the first call of the timer, use the
3889 * g_timeout_add_seconds() function; this function allows for more
3890 * optimizations and more efficient system power usage.
3892 * This internally creates a main loop source using g_timeout_source_new()
3893 * and attaches it to the main loop context using g_source_attach(). You can
3894 * do these steps manually if you need greater control.
3896 * The interval given is in terms of monotonic time, not wall clock
3897 * time. See g_get_monotonic_time().
3899 * Return value: the ID (greater than 0) of the event source.
3902 g_timeout_add (guint32 interval,
3903 GSourceFunc function,
3906 return g_timeout_add_full (G_PRIORITY_DEFAULT,
3907 interval, function, data, NULL);
3911 * g_timeout_add_seconds_full:
3912 * @priority: the priority of the timeout source. Typically this will be in
3913 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3914 * @interval: the time between calls to the function, in seconds
3915 * @function: function to call
3916 * @data: data to pass to @function
3917 * @notify: function to call when the timeout is removed, or %NULL
3919 * Sets a function to be called at regular intervals, with @priority.
3920 * The function is called repeatedly until it returns %FALSE, at which
3921 * point the timeout is automatically destroyed and the function will
3922 * not be called again.
3924 * Unlike g_timeout_add(), this function operates at whole second granularity.
3925 * The initial starting point of the timer is determined by the implementation
3926 * and the implementation is expected to group multiple timers together so that
3927 * they fire all at the same time.
3928 * To allow this grouping, the @interval to the first timer is rounded
3929 * and can deviate up to one second from the specified interval.
3930 * Subsequent timer iterations will generally run at the specified interval.
3932 * Note that timeout functions may be delayed, due to the processing of other
3933 * event sources. Thus they should not be relied on for precise timing.
3934 * After each call to the timeout function, the time of the next
3935 * timeout is recalculated based on the current time and the given @interval
3937 * If you want timing more precise than whole seconds, use g_timeout_add()
3940 * The grouping of timers to fire at the same time results in a more power
3941 * and CPU efficient behavior so if your timer is in multiples of seconds
3942 * and you don't require the first timer exactly one second from now, the
3943 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
3945 * This internally creates a main loop source using
3946 * g_timeout_source_new_seconds() and attaches it to the main loop context
3947 * using g_source_attach(). You can do these steps manually if you need
3950 * The interval given is in terms of monotonic time, not wall clock
3951 * time. See g_get_monotonic_time().
3953 * Return value: the ID (greater than 0) of the event source.
3955 * Rename to: g_timeout_add_seconds
3959 g_timeout_add_seconds_full (gint priority,
3961 GSourceFunc function,
3963 GDestroyNotify notify)
3968 g_return_val_if_fail (function != NULL, 0);
3970 source = g_timeout_source_new_seconds (interval);
3972 if (priority != G_PRIORITY_DEFAULT)
3973 g_source_set_priority (source, priority);
3975 g_source_set_callback (source, function, data, notify);
3976 id = g_source_attach (source, NULL);
3977 g_source_unref (source);
3983 * g_timeout_add_seconds:
3984 * @interval: the time between calls to the function, in seconds
3985 * @function: function to call
3986 * @data: data to pass to @function
3988 * Sets a function to be called at regular intervals with the default
3989 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
3990 * it returns %FALSE, at which point the timeout is automatically destroyed
3991 * and the function will not be called again.
3993 * This internally creates a main loop source using
3994 * g_timeout_source_new_seconds() and attaches it to the main loop context
3995 * using g_source_attach(). You can do these steps manually if you need
3996 * greater control. Also see g_timeout_add_seconds_full().
3998 * Note that the first call of the timer may not be precise for timeouts
3999 * of one second. If you need finer precision and have such a timeout,
4000 * you may want to use g_timeout_add() instead.
4002 * The interval given is in terms of monotonic time, not wall clock
4003 * time. See g_get_monotonic_time().
4005 * Return value: the ID (greater than 0) of the event source.
4010 g_timeout_add_seconds (guint interval,
4011 GSourceFunc function,
4014 g_return_val_if_fail (function != NULL, 0);
4016 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4019 /* Child watch functions */
4024 g_child_watch_prepare (GSource *source,
4032 g_child_watch_check (GSource *source)
4034 GChildWatchSource *child_watch_source;
4035 gboolean child_exited;
4037 child_watch_source = (GChildWatchSource *) source;
4039 child_exited = child_watch_source->poll.revents & G_IO_IN;
4046 * Note: We do _not_ check for the special value of STILL_ACTIVE
4047 * since we know that the process has exited and doing so runs into
4048 * problems if the child process "happens to return STILL_ACTIVE(259)"
4049 * as Microsoft's Platform SDK puts it.
4051 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4053 gchar *emsg = g_win32_error_message (GetLastError ());
4054 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4057 child_watch_source->child_status = -1;
4060 child_watch_source->child_status = child_status;
4063 return child_exited;
4067 g_child_watch_finalize (GSource *source)
4071 #else /* G_OS_WIN32 */
4074 wake_source (GSource *source)
4076 GMainContext *context;
4078 /* This should be thread-safe:
4080 * - if the source is currently being added to a context, that
4081 * context will be woken up anyway
4083 * - if the source is currently being destroyed, we simply need not
4086 * - the memory for the source will remain valid until after the
4087 * source finalize function was called (which would remove the
4088 * source from the global list which we are currently holding the
4091 * - the GMainContext will either be NULL or point to a live
4094 * - the GMainContext will remain valid since we hold the
4095 * main_context_list lock
4097 * Since we are holding a lot of locks here, don't try to enter any
4098 * more GMainContext functions for fear of dealock -- just hit the
4099 * GWakeup and run. Even if that's safe now, it could easily become
4100 * unsafe with some very minor changes in the future, and signal
4101 * handling is not the most well-tested codepath.
4103 G_LOCK(main_context_list);
4104 context = source->context;
4106 g_wakeup_signal (context->wakeup);
4107 G_UNLOCK(main_context_list);
4111 dispatch_unix_signals (void)
4115 /* clear this first incase another one arrives while we're processing */
4116 any_unix_signal_pending = FALSE;
4118 G_LOCK(unix_signal_lock);
4120 /* handle GChildWatchSource instances */
4121 if (unix_signal_pending[SIGCHLD])
4123 unix_signal_pending[SIGCHLD] = FALSE;
4125 /* The only way we can do this is to scan all of the children.
4127 * The docs promise that we will not reap children that we are not
4128 * explicitly watching, so that ties our hands from calling
4129 * waitpid(-1). We also can't use siginfo's si_pid field since if
4130 * multiple SIGCHLD arrive at the same time, one of them can be
4131 * dropped (since a given UNIX signal can only be pending once).
4133 for (node = unix_child_watches; node; node = node->next)
4135 GChildWatchSource *source = node->data;
4137 if (!source->child_exited)
4139 if (waitpid (source->pid, &source->child_status, WNOHANG) > 0)
4141 source->child_exited = TRUE;
4143 wake_source ((GSource *) source);
4149 /* handle GUnixSignalWatchSource instances */
4150 for (node = unix_signal_watches; node; node = node->next)
4152 GUnixSignalWatchSource *source = node->data;
4154 if (!source->pending)
4156 if (unix_signal_pending[source->signum])
4158 unix_signal_pending[source->signum] = FALSE;
4159 source->pending = TRUE;
4161 wake_source ((GSource *) source);
4166 G_UNLOCK(unix_signal_lock);
4170 g_child_watch_prepare (GSource *source,
4173 GChildWatchSource *child_watch_source;
4175 child_watch_source = (GChildWatchSource *) source;
4177 return child_watch_source->child_exited;
4181 g_child_watch_check (GSource *source)
4183 GChildWatchSource *child_watch_source;
4185 child_watch_source = (GChildWatchSource *) source;
4187 return child_watch_source->child_exited;
4191 g_unix_signal_watch_prepare (GSource *source,
4194 GUnixSignalWatchSource *unix_signal_source;
4196 unix_signal_source = (GUnixSignalWatchSource *) source;
4198 return unix_signal_source->pending;
4202 g_unix_signal_watch_check (GSource *source)
4204 GUnixSignalWatchSource *unix_signal_source;
4206 unix_signal_source = (GUnixSignalWatchSource *) source;
4208 return unix_signal_source->pending;
4212 g_unix_signal_watch_dispatch (GSource *source,
4213 GSourceFunc callback,
4216 GUnixSignalWatchSource *unix_signal_source;
4218 unix_signal_source = (GUnixSignalWatchSource *) source;
4222 g_warning ("Unix signal source dispatched without callback\n"
4223 "You must call g_source_set_callback().");
4227 (callback) (user_data);
4229 unix_signal_source->pending = FALSE;
4235 ensure_unix_signal_handler_installed_unlocked (int signum)
4237 static sigset_t installed_signal_mask;
4238 static gboolean initialized;
4239 struct sigaction action;
4243 sigemptyset (&installed_signal_mask);
4244 g_get_worker_context ();
4248 if (sigismember (&installed_signal_mask, signum))
4251 sigaddset (&installed_signal_mask, signum);
4253 action.sa_handler = g_unix_signal_handler;
4254 sigemptyset (&action.sa_mask);
4255 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4256 sigaction (signum, &action, NULL);
4260 _g_main_create_unix_signal_watch (int signum)
4263 GUnixSignalWatchSource *unix_signal_source;
4265 source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
4266 unix_signal_source = (GUnixSignalWatchSource *) source;
4268 unix_signal_source->signum = signum;
4269 unix_signal_source->pending = FALSE;
4271 G_LOCK (unix_signal_lock);
4272 ensure_unix_signal_handler_installed_unlocked (signum);
4273 unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
4274 if (unix_signal_pending[signum])
4275 unix_signal_source->pending = TRUE;
4276 unix_signal_pending[signum] = FALSE;
4277 G_UNLOCK (unix_signal_lock);
4283 g_unix_signal_watch_finalize (GSource *source)
4285 G_LOCK (unix_signal_lock);
4286 unix_signal_watches = g_slist_remove (unix_signal_watches, source);
4287 G_UNLOCK (unix_signal_lock);
4291 g_child_watch_finalize (GSource *source)
4293 G_LOCK (unix_signal_lock);
4294 unix_child_watches = g_slist_remove (unix_child_watches, source);
4295 G_UNLOCK (unix_signal_lock);
4298 #endif /* G_OS_WIN32 */
4301 g_child_watch_dispatch (GSource *source,
4302 GSourceFunc callback,
4305 GChildWatchSource *child_watch_source;
4306 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
4308 child_watch_source = (GChildWatchSource *) source;
4312 g_warning ("Child watch source dispatched without callback\n"
4313 "You must call g_source_set_callback().");
4317 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
4319 /* We never keep a child watch source around as the child is gone */
4326 g_unix_signal_handler (int signum)
4328 unix_signal_pending[signum] = TRUE;
4329 any_unix_signal_pending = TRUE;
4331 g_wakeup_signal (glib_worker_context->wakeup);
4334 #endif /* !G_OS_WIN32 */
4337 * g_child_watch_source_new:
4338 * @pid: process to watch. On POSIX the pid of a child process. On
4339 * Windows a handle for a process (which doesn't have to be a child).
4341 * Creates a new child_watch source.
4343 * The source will not initially be associated with any #GMainContext
4344 * and must be added to one with g_source_attach() before it will be
4347 * Note that child watch sources can only be used in conjunction with
4348 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4351 * Note that on platforms where #GPid must be explicitly closed
4352 * (see g_spawn_close_pid()) @pid must not be closed while the
4353 * source is still active. Typically, you will want to call
4354 * g_spawn_close_pid() in the callback function for the source.
4356 * Note further that using g_child_watch_source_new() is not
4357 * compatible with calling <literal>waitpid(-1)</literal> in
4358 * the application. Calling waitpid() for individual pids will
4361 * Return value: the newly-created child watch source
4366 g_child_watch_source_new (GPid pid)
4368 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4369 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4371 child_watch_source->pid = pid;
4374 child_watch_source->poll.fd = (gintptr) pid;
4375 child_watch_source->poll.events = G_IO_IN;
4377 g_source_add_poll (source, &child_watch_source->poll);
4378 #else /* G_OS_WIN32 */
4379 G_LOCK (unix_signal_lock);
4380 ensure_unix_signal_handler_installed_unlocked (SIGCHLD);
4381 unix_child_watches = g_slist_prepend (unix_child_watches, child_watch_source);
4382 if (waitpid (pid, &child_watch_source->child_status, WNOHANG) > 0)
4383 child_watch_source->child_exited = TRUE;
4384 G_UNLOCK (unix_signal_lock);
4385 #endif /* G_OS_WIN32 */
4391 * g_child_watch_add_full:
4392 * @priority: the priority of the idle source. Typically this will be in the
4393 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4394 * @pid: process to watch. On POSIX the pid of a child process. On
4395 * Windows a handle for a process (which doesn't have to be a child).
4396 * @function: function to call
4397 * @data: data to pass to @function
4398 * @notify: function to call when the idle is removed, or %NULL
4400 * Sets a function to be called when the child indicated by @pid
4401 * exits, at the priority @priority.
4403 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4404 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4405 * the spawn function for the child watching to work.
4407 * Note that on platforms where #GPid must be explicitly closed
4408 * (see g_spawn_close_pid()) @pid must not be closed while the
4409 * source is still active. Typically, you will want to call
4410 * g_spawn_close_pid() in the callback function for the source.
4412 * GLib supports only a single callback per process id.
4414 * This internally creates a main loop source using
4415 * g_child_watch_source_new() and attaches it to the main loop context
4416 * using g_source_attach(). You can do these steps manually if you
4417 * need greater control.
4419 * Return value: the ID (greater than 0) of the event source.
4421 * Rename to: g_child_watch_add
4425 g_child_watch_add_full (gint priority,
4427 GChildWatchFunc function,
4429 GDestroyNotify notify)
4434 g_return_val_if_fail (function != NULL, 0);
4436 source = g_child_watch_source_new (pid);
4438 if (priority != G_PRIORITY_DEFAULT)
4439 g_source_set_priority (source, priority);
4441 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4442 id = g_source_attach (source, NULL);
4443 g_source_unref (source);
4449 * g_child_watch_add:
4450 * @pid: process id to watch. On POSIX the pid of a child process. On
4451 * Windows a handle for a process (which doesn't have to be a child).
4452 * @function: function to call
4453 * @data: data to pass to @function
4455 * Sets a function to be called when the child indicated by @pid
4456 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4458 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4459 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4460 * the spawn function for the child watching to work.
4462 * Note that on platforms where #GPid must be explicitly closed
4463 * (see g_spawn_close_pid()) @pid must not be closed while the
4464 * source is still active. Typically, you will want to call
4465 * g_spawn_close_pid() in the callback function for the source.
4467 * GLib supports only a single callback per process id.
4469 * This internally creates a main loop source using
4470 * g_child_watch_source_new() and attaches it to the main loop context
4471 * using g_source_attach(). You can do these steps manually if you
4472 * need greater control.
4474 * Return value: the ID (greater than 0) of the event source.
4479 g_child_watch_add (GPid pid,
4480 GChildWatchFunc function,
4483 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4487 /* Idle functions */
4490 g_idle_prepare (GSource *source,
4499 g_idle_check (GSource *source)
4505 g_idle_dispatch (GSource *source,
4506 GSourceFunc callback,
4511 g_warning ("Idle source dispatched without callback\n"
4512 "You must call g_source_set_callback().");
4516 return callback (user_data);
4520 * g_idle_source_new:
4522 * Creates a new idle source.
4524 * The source will not initially be associated with any #GMainContext
4525 * and must be added to one with g_source_attach() before it will be
4526 * executed. Note that the default priority for idle sources is
4527 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4528 * have a default priority of %G_PRIORITY_DEFAULT.
4530 * Return value: the newly-created idle source
4533 g_idle_source_new (void)
4537 source = g_source_new (&g_idle_funcs, sizeof (GSource));
4538 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4545 * @priority: the priority of the idle source. Typically this will be in the
4546 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4547 * @function: function to call
4548 * @data: data to pass to @function
4549 * @notify: function to call when the idle is removed, or %NULL
4551 * Adds a function to be called whenever there are no higher priority
4552 * events pending. If the function returns %FALSE it is automatically
4553 * removed from the list of event sources and will not be called again.
4555 * This internally creates a main loop source using g_idle_source_new()
4556 * and attaches it to the main loop context using g_source_attach().
4557 * You can do these steps manually if you need greater control.
4559 * Return value: the ID (greater than 0) of the event source.
4560 * Rename to: g_idle_add
4563 g_idle_add_full (gint priority,
4564 GSourceFunc function,
4566 GDestroyNotify notify)
4571 g_return_val_if_fail (function != NULL, 0);
4573 source = g_idle_source_new ();
4575 if (priority != G_PRIORITY_DEFAULT_IDLE)
4576 g_source_set_priority (source, priority);
4578 g_source_set_callback (source, function, data, notify);
4579 id = g_source_attach (source, NULL);
4580 g_source_unref (source);
4587 * @function: function to call
4588 * @data: data to pass to @function.
4590 * Adds a function to be called whenever there are no higher priority
4591 * events pending to the default main loop. The function is given the
4592 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4593 * returns %FALSE it is automatically removed from the list of event
4594 * sources and will not be called again.
4596 * This internally creates a main loop source using g_idle_source_new()
4597 * and attaches it to the main loop context using g_source_attach().
4598 * You can do these steps manually if you need greater control.
4600 * Return value: the ID (greater than 0) of the event source.
4603 g_idle_add (GSourceFunc function,
4606 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4610 * g_idle_remove_by_data:
4611 * @data: the data for the idle source's callback.
4613 * Removes the idle function with the given data.
4615 * Return value: %TRUE if an idle source was found and removed.
4618 g_idle_remove_by_data (gpointer data)
4620 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4624 * g_main_context_invoke:
4625 * @context: (allow-none): a #GMainContext, or %NULL
4626 * @function: function to call
4627 * @data: data to pass to @function
4629 * Invokes a function in such a way that @context is owned during the
4630 * invocation of @function.
4632 * If @context is %NULL then the global default main context — as
4633 * returned by g_main_context_default() — is used.
4635 * If @context is owned by the current thread, @function is called
4636 * directly. Otherwise, if @context is the thread-default main context
4637 * of the current thread and g_main_context_acquire() succeeds, then
4638 * @function is called and g_main_context_release() is called
4641 * In any other case, an idle source is created to call @function and
4642 * that source is attached to @context (presumably to be run in another
4643 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
4644 * priority. If you want a different priority, use
4645 * g_main_context_invoke_full().
4647 * Note that, as with normal idle functions, @function should probably
4648 * return %FALSE. If it returns %TRUE, it will be continuously run in a
4649 * loop (and may prevent this call from returning).
4654 g_main_context_invoke (GMainContext *context,
4655 GSourceFunc function,
4658 g_main_context_invoke_full (context,
4660 function, data, NULL);
4664 * g_main_context_invoke_full:
4665 * @context: (allow-none): a #GMainContext, or %NULL
4666 * @priority: the priority at which to run @function
4667 * @function: function to call
4668 * @data: data to pass to @function
4669 * @notify: a function to call when @data is no longer in use, or %NULL.
4671 * Invokes a function in such a way that @context is owned during the
4672 * invocation of @function.
4674 * This function is the same as g_main_context_invoke() except that it
4675 * lets you specify the priority incase @function ends up being
4676 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
4678 * @notify should not assume that it is called from any particular
4679 * thread or with any particular context acquired.
4684 g_main_context_invoke_full (GMainContext *context,
4686 GSourceFunc function,
4688 GDestroyNotify notify)
4690 g_return_if_fail (function != NULL);
4693 context = g_main_context_default ();
4695 if (g_main_context_is_owner (context))
4697 while (function (data));
4704 GMainContext *thread_default;
4706 thread_default = g_main_context_get_thread_default ();
4708 if (!thread_default)
4709 thread_default = g_main_context_default ();
4711 if (thread_default == context && g_main_context_acquire (context))
4713 while (function (data));
4715 g_main_context_release (context);
4724 source = g_idle_source_new ();
4725 g_source_set_priority (source, priority);
4726 g_source_set_callback (source, function, data, notify);
4727 g_source_attach (source, context);
4728 g_source_unref (source);
4734 glib_worker_main (gpointer data)
4738 g_main_context_iteration (glib_worker_context, TRUE);
4741 if (any_unix_signal_pending)
4742 dispatch_unix_signals ();
4746 return NULL; /* worst GCC warning message ever... */
4750 g_get_worker_context (void)
4752 static gsize initialised;
4754 g_thread_init_glib ();
4756 if (g_once_init_enter (&initialised))
4758 GError *error = NULL;
4760 glib_worker_context = g_main_context_new ();
4761 if (g_thread_create (glib_worker_main, NULL, FALSE, &error) == NULL)
4762 g_error ("Creating GLib worker thread failed: %s\n", error->message);
4764 g_once_init_leave (&initialised, TRUE);
4767 return glib_worker_context;