1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * gmain.c: Main loop abstraction, timeouts, and idle functions
5 * Copyright 1998 Owen Taylor
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the
19 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 * Boston, MA 02111-1307, USA.
24 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
25 * file for a list of people on the GLib Team. See the ChangeLog
26 * files for a list of changes. These files are distributed with
27 * GLib at ftp://ftp.gtk.org/pub/gtk/.
35 #include "glibconfig.h"
37 /* Uncomment the next line (and the corresponding line in gpoll.c) to
38 * enable debugging printouts if the environment variable
39 * G_MAIN_POLL_DEBUG is set to some value.
41 /* #define G_MAIN_POLL_DEBUG */
44 /* Always enable debugging printout on Windows, as it is more often
47 #define G_MAIN_POLL_DEBUG
51 #include "glib-unix.h"
54 #include <sys/eventfd.h>
59 #include <sys/types.h>
62 #ifdef HAVE_SYS_TIME_H
64 #endif /* HAVE_SYS_TIME_H */
67 #endif /* HAVE_UNISTD_H */
74 #endif /* G_OS_WIN32 */
77 #include <sys/socket.h>
79 #endif /* G_OS_BEOS */
84 #include "giochannel.h"
88 #include "gstrfuncs.h"
89 #include "gtestutils.h"
90 #include "gthreadprivate.h"
96 #ifdef G_MAIN_POLL_DEBUG
102 #include "glib-private.h"
106 * @title: The Main Event Loop
107 * @short_description: manages all available sources of events
109 * The main event loop manages all the available sources of events for
110 * GLib and GTK+ applications. These events can come from any number of
111 * different types of sources such as file descriptors (plain files,
112 * pipes or sockets) and timeouts. New types of event sources can also
113 * be added using g_source_attach().
115 * To allow multiple independent sets of sources to be handled in
116 * different threads, each source is associated with a #GMainContext.
117 * A GMainContext can only be running in a single thread, but
118 * sources can be added to it and removed from it from other threads.
120 * Each event source is assigned a priority. The default priority,
121 * #G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
122 * Values greater than 0 denote lower priorities. Events from high priority
123 * sources are always processed before events from lower priority sources.
125 * Idle functions can also be added, and assigned a priority. These will
126 * be run whenever no events with a higher priority are ready to be processed.
128 * The #GMainLoop data type represents a main event loop. A GMainLoop is
129 * created with g_main_loop_new(). After adding the initial event sources,
130 * g_main_loop_run() is called. This continuously checks for new events from
131 * each of the event sources and dispatches them. Finally, the processing of
132 * an event from one of the sources leads to a call to g_main_loop_quit() to
133 * exit the main loop, and g_main_loop_run() returns.
135 * It is possible to create new instances of #GMainLoop recursively.
136 * This is often used in GTK+ applications when showing modal dialog
137 * boxes. Note that event sources are associated with a particular
138 * #GMainContext, and will be checked and dispatched for all main
139 * loops associated with that GMainContext.
141 * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
142 * gtk_main_quit() and gtk_events_pending().
144 * <refsect2><title>Creating new source types</title>
145 * <para>One of the unusual features of the #GMainLoop functionality
146 * is that new types of event source can be created and used in
147 * addition to the builtin type of event source. A new event source
148 * type is used for handling GDK events. A new source type is created
149 * by <firstterm>deriving</firstterm> from the #GSource structure.
150 * The derived type of source is represented by a structure that has
151 * the #GSource structure as a first element, and other elements specific
152 * to the new source type. To create an instance of the new source type,
153 * call g_source_new() passing in the size of the derived structure and
154 * a table of functions. These #GSourceFuncs determine the behavior of
155 * the new source type.</para>
156 * <para>New source types basically interact with the main context
157 * in two ways. Their prepare function in #GSourceFuncs can set a timeout
158 * to determine the maximum amount of time that the main loop will sleep
159 * before checking the source again. In addition, or as well, the source
160 * can add file descriptors to the set that the main context checks using
161 * g_source_add_poll().</para>
163 * <refsect2><title>Customizing the main loop iteration</title>
164 * <para>Single iterations of a #GMainContext can be run with
165 * g_main_context_iteration(). In some cases, more detailed control
166 * of exactly how the details of the main loop work is desired, for
167 * instance, when integrating the #GMainLoop with an external main loop.
168 * In such cases, you can call the component functions of
169 * g_main_context_iteration() directly. These functions are
170 * g_main_context_prepare(), g_main_context_query(),
171 * g_main_context_check() and g_main_context_dispatch().</para>
172 * <para>The operation of these functions can best be seen in terms
173 * of a state diagram, as shown in <xref linkend="mainloop-states"/>.</para>
174 * <figure id="mainloop-states"><title>States of a Main Context</title>
175 * <graphic fileref="mainloop-states.gif" format="GIF"></graphic>
179 * On Unix, the GLib mainloop is incompatible with fork(). Any program
180 * using the mainloop must either exec() or exit() from the child
181 * without returning to the mainloop.
186 typedef struct _GTimeoutSource GTimeoutSource;
187 typedef struct _GChildWatchSource GChildWatchSource;
188 typedef struct _GUnixSignalWatchSource GUnixSignalWatchSource;
189 typedef struct _GPollRec GPollRec;
190 typedef struct _GSourceCallback GSourceCallback;
194 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
195 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
198 typedef struct _GMainWaiter GMainWaiter;
206 typedef struct _GMainDispatch GMainDispatch;
208 struct _GMainDispatch
211 GSList *dispatching_sources; /* stack of current sources */
214 #ifdef G_MAIN_POLL_DEBUG
215 gboolean _g_main_poll_debug = FALSE;
220 /* The following lock is used for both the list of sources
221 * and the list of poll records
231 GPtrArray *pending_dispatches;
232 gint timeout; /* Timeout for current iteration */
235 GSource *source_list;
236 gint in_check_or_prepare;
238 GPollRec *poll_records, *poll_records_tail;
239 guint n_poll_records;
240 GPollFD *cached_poll_array;
241 guint cached_poll_array_size;
247 /* Flag indicating whether the set of fd's changed during a poll */
248 gboolean poll_changed;
253 gboolean time_is_fresh;
256 struct _GSourceCallback
261 GDestroyNotify notify;
266 GMainContext *context;
271 struct _GTimeoutSource
279 struct _GChildWatchSource
286 #else /* G_OS_WIN32 */
287 gboolean child_exited;
288 #endif /* G_OS_WIN32 */
291 struct _GUnixSignalWatchSource
306 struct _GSourcePrivate
308 GSList *child_sources;
309 GSource *parent_source;
312 #define LOCK_CONTEXT(context) g_mutex_lock (&context->mutex)
313 #define UNLOCK_CONTEXT(context) g_mutex_unlock (&context->mutex)
314 #define G_THREAD_SELF g_thread_self ()
316 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
317 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
318 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
320 #define SOURCE_UNREF(source, context) \
322 if ((source)->ref_count > 1) \
323 (source)->ref_count--; \
325 g_source_unref_internal ((source), (context), TRUE); \
329 /* Forward declarations */
331 static void g_source_unref_internal (GSource *source,
332 GMainContext *context,
334 static void g_source_destroy_internal (GSource *source,
335 GMainContext *context,
337 static void g_source_set_priority_unlocked (GSource *source,
338 GMainContext *context,
340 static void g_main_context_poll (GMainContext *context,
345 static void g_main_context_add_poll_unlocked (GMainContext *context,
348 static void g_main_context_remove_poll_unlocked (GMainContext *context,
351 static gboolean g_timeout_prepare (GSource *source,
353 static gboolean g_timeout_check (GSource *source);
354 static gboolean g_timeout_dispatch (GSource *source,
355 GSourceFunc callback,
357 static gboolean g_child_watch_prepare (GSource *source,
359 static gboolean g_child_watch_check (GSource *source);
360 static gboolean g_child_watch_dispatch (GSource *source,
361 GSourceFunc callback,
363 static void g_child_watch_finalize (GSource *source);
365 static void g_unix_signal_handler (int signum);
366 static gboolean g_unix_signal_watch_prepare (GSource *source,
368 static gboolean g_unix_signal_watch_check (GSource *source);
369 static gboolean g_unix_signal_watch_dispatch (GSource *source,
370 GSourceFunc callback,
372 static void g_unix_signal_watch_finalize (GSource *source);
374 static gboolean g_idle_prepare (GSource *source,
376 static gboolean g_idle_check (GSource *source);
377 static gboolean g_idle_dispatch (GSource *source,
378 GSourceFunc callback,
381 static GMainContext *glib_worker_context;
382 static gboolean g_main_context_fork_detected;
384 G_LOCK_DEFINE_STATIC (main_loop);
385 static GMainContext *default_main_context;
390 /* UNIX signals work by marking one of these variables then waking the
391 * worker context to check on them and dispatch accordingly.
393 static volatile gchar unix_signal_pending[NSIG];
394 static volatile gboolean any_unix_signal_pending;
396 /* Guards all the data below */
397 G_LOCK_DEFINE_STATIC (unix_signal_lock);
398 static GSList *unix_signal_watches;
399 static GSList *unix_child_watches;
401 static GSourceFuncs g_unix_signal_funcs =
403 g_unix_signal_watch_prepare,
404 g_unix_signal_watch_check,
405 g_unix_signal_watch_dispatch,
406 g_unix_signal_watch_finalize
408 #endif /* !G_OS_WIN32 */
409 G_LOCK_DEFINE_STATIC (main_context_list);
410 static GSList *main_context_list = NULL;
412 GSourceFuncs g_timeout_funcs =
420 GSourceFuncs g_child_watch_funcs =
422 g_child_watch_prepare,
424 g_child_watch_dispatch,
425 g_child_watch_finalize
428 GSourceFuncs g_idle_funcs =
437 * g_main_context_ref:
438 * @context: a #GMainContext
440 * Increases the reference count on a #GMainContext object by one.
442 * Returns: the @context that was passed in (since 2.6)
445 g_main_context_ref (GMainContext *context)
447 g_return_val_if_fail (context != NULL, NULL);
448 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
450 g_atomic_int_inc (&context->ref_count);
456 poll_rec_list_free (GMainContext *context,
459 g_slice_free_chain (GPollRec, list, next);
463 * g_main_context_unref:
464 * @context: a #GMainContext
466 * Decreases the reference count on a #GMainContext object by one. If
467 * the result is zero, free the context and free all associated memory.
470 g_main_context_unref (GMainContext *context)
473 g_return_if_fail (context != NULL);
474 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
476 if (!g_atomic_int_dec_and_test (&context->ref_count))
479 G_LOCK (main_context_list);
480 main_context_list = g_slist_remove (main_context_list, context);
481 G_UNLOCK (main_context_list);
483 source = context->source_list;
486 GSource *next = source->next;
487 g_source_destroy_internal (source, context, FALSE);
491 g_mutex_clear (&context->mutex);
493 g_ptr_array_free (context->pending_dispatches, TRUE);
494 g_free (context->cached_poll_array);
496 poll_rec_list_free (context, context->poll_records);
498 g_wakeup_free (context->wakeup);
499 g_cond_clear (&context->cond);
506 g_main_context_forked (void)
508 g_main_context_fork_detected = TRUE;
513 * g_main_context_new:
515 * Creates a new #GMainContext structure.
517 * Return value: the new #GMainContext
520 g_main_context_new (void)
522 static gsize initialised;
523 GMainContext *context;
525 if (g_once_init_enter (&initialised))
527 #ifdef G_MAIN_POLL_DEBUG
528 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
529 _g_main_poll_debug = TRUE;
533 pthread_atfork (NULL, NULL, g_main_context_forked);
536 g_once_init_leave (&initialised, TRUE);
539 context = g_new0 (GMainContext, 1);
541 g_mutex_init (&context->mutex);
542 g_cond_init (&context->cond);
544 context->owner = NULL;
545 context->waiters = NULL;
547 context->ref_count = 1;
549 context->next_id = 1;
551 context->source_list = NULL;
553 context->poll_func = g_poll;
555 context->cached_poll_array = NULL;
556 context->cached_poll_array_size = 0;
558 context->pending_dispatches = g_ptr_array_new ();
560 context->time_is_fresh = FALSE;
562 context->wakeup = g_wakeup_new ();
563 g_wakeup_get_pollfd (context->wakeup, &context->wake_up_rec);
564 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
566 G_LOCK (main_context_list);
567 main_context_list = g_slist_append (main_context_list, context);
569 #ifdef G_MAIN_POLL_DEBUG
570 if (_g_main_poll_debug)
571 g_print ("created context=%p\n", context);
574 G_UNLOCK (main_context_list);
580 * g_main_context_default:
582 * Returns the global default main context. This is the main context
583 * used for main loop functions when a main loop is not explicitly
584 * specified, and corresponds to the "main" main loop. See also
585 * g_main_context_get_thread_default().
587 * Return value: (transfer none): the global default main context.
590 g_main_context_default (void)
596 if (!default_main_context)
598 default_main_context = g_main_context_new ();
599 #ifdef G_MAIN_POLL_DEBUG
600 if (_g_main_poll_debug)
601 g_print ("default context=%p\n", default_main_context);
605 G_UNLOCK (main_loop);
607 return default_main_context;
610 static GStaticPrivate thread_context_stack = G_STATIC_PRIVATE_INIT;
613 free_context_stack (gpointer data)
615 GQueue *stack = data;
616 GMainContext *context;
618 while (!g_queue_is_empty (stack))
620 context = g_queue_pop_head (stack);
621 g_main_context_release (context);
623 g_main_context_unref (context);
625 g_queue_free (stack);
629 * g_main_context_push_thread_default:
630 * @context: a #GMainContext, or %NULL for the global default context
632 * Acquires @context and sets it as the thread-default context for the
633 * current thread. This will cause certain asynchronous operations
634 * (such as most <link linkend="gio">gio</link>-based I/O) which are
635 * started in this thread to run under @context and deliver their
636 * results to its main loop, rather than running under the global
637 * default context in the main thread. Note that calling this function
638 * changes the context returned by
639 * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
640 * one returned by g_main_context_default(), so it does not affect the
641 * context used by functions like g_idle_add().
643 * Normally you would call this function shortly after creating a new
644 * thread, passing it a #GMainContext which will be run by a
645 * #GMainLoop in that thread, to set a new default context for all
646 * async operations in that thread. (In this case, you don't need to
647 * ever call g_main_context_pop_thread_default().) In some cases
648 * however, you may want to schedule a single operation in a
649 * non-default context, or temporarily use a non-default context in
650 * the main thread. In that case, you can wrap the call to the
651 * asynchronous operation inside a
652 * g_main_context_push_thread_default() /
653 * g_main_context_pop_thread_default() pair, but it is up to you to
654 * ensure that no other asynchronous operations accidentally get
655 * started while the non-default context is active.
657 * Beware that libraries that predate this function may not correctly
658 * handle being used from a thread with a thread-default context. Eg,
659 * see g_file_supports_thread_contexts().
664 g_main_context_push_thread_default (GMainContext *context)
667 gboolean acquired_context;
669 acquired_context = g_main_context_acquire (context);
670 g_return_if_fail (acquired_context);
672 if (context == g_main_context_default ())
675 g_main_context_ref (context);
677 stack = g_static_private_get (&thread_context_stack);
680 stack = g_queue_new ();
681 g_static_private_set (&thread_context_stack, stack,
685 g_queue_push_head (stack, context);
689 * g_main_context_pop_thread_default:
690 * @context: a #GMainContext object, or %NULL
692 * Pops @context off the thread-default context stack (verifying that
693 * it was on the top of the stack).
698 g_main_context_pop_thread_default (GMainContext *context)
702 if (context == g_main_context_default ())
705 stack = g_static_private_get (&thread_context_stack);
707 g_return_if_fail (stack != NULL);
708 g_return_if_fail (g_queue_peek_head (stack) == context);
710 g_queue_pop_head (stack);
712 g_main_context_release (context);
714 g_main_context_unref (context);
718 * g_main_context_get_thread_default:
720 * Gets the thread-default #GMainContext for this thread. Asynchronous
721 * operations that want to be able to be run in contexts other than
722 * the default one should call this method to get a #GMainContext to
723 * add their #GSource<!-- -->s to. (Note that even in single-threaded
724 * programs applications may sometimes want to temporarily push a
725 * non-default context, so it is not safe to assume that this will
726 * always return %NULL if threads are not initialized.)
728 * Returns: (transfer none): the thread-default #GMainContext, or
729 * %NULL if the thread-default context is the global default context.
734 g_main_context_get_thread_default (void)
738 stack = g_static_private_get (&thread_context_stack);
740 return g_queue_peek_head (stack);
745 /* Hooks for adding to the main loop */
749 * @source_funcs: structure containing functions that implement
750 * the sources behavior.
751 * @struct_size: size of the #GSource structure to create.
753 * Creates a new #GSource structure. The size is specified to
754 * allow creating structures derived from #GSource that contain
755 * additional data. The size passed in must be at least
756 * <literal>sizeof (GSource)</literal>.
758 * The source will not initially be associated with any #GMainContext
759 * and must be added to one with g_source_attach() before it will be
762 * Return value: the newly-created #GSource.
765 g_source_new (GSourceFuncs *source_funcs,
770 g_return_val_if_fail (source_funcs != NULL, NULL);
771 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
773 source = (GSource*) g_malloc0 (struct_size);
775 source->source_funcs = source_funcs;
776 source->ref_count = 1;
778 source->priority = G_PRIORITY_DEFAULT;
780 source->flags = G_HOOK_FLAG_ACTIVE;
782 /* NULL/0 initialization for all other fields */
787 /* Holds context's lock
790 g_source_list_add (GSource *source,
791 GMainContext *context)
793 GSource *tmp_source, *last_source;
795 if (source->priv && source->priv->parent_source)
797 /* Put the source immediately before its parent */
798 tmp_source = source->priv->parent_source;
799 last_source = source->priv->parent_source->prev;
804 tmp_source = context->source_list;
805 while (tmp_source && tmp_source->priority <= source->priority)
807 last_source = tmp_source;
808 tmp_source = tmp_source->next;
812 source->next = tmp_source;
814 tmp_source->prev = source;
816 source->prev = last_source;
818 last_source->next = source;
820 context->source_list = source;
823 /* Holds context's lock
826 g_source_list_remove (GSource *source,
827 GMainContext *context)
830 source->prev->next = source->next;
832 context->source_list = source->next;
835 source->next->prev = source->prev;
842 g_source_attach_unlocked (GSource *source,
843 GMainContext *context)
848 source->context = context;
849 result = source->source_id = context->next_id++;
852 g_source_list_add (source, context);
854 tmp_list = source->poll_fds;
857 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
858 tmp_list = tmp_list->next;
863 tmp_list = source->priv->child_sources;
866 g_source_attach_unlocked (tmp_list->data, context);
867 tmp_list = tmp_list->next;
876 * @source: a #GSource
877 * @context: a #GMainContext (if %NULL, the default context will be used)
879 * Adds a #GSource to a @context so that it will be executed within
880 * that context. Remove it by calling g_source_destroy().
882 * Return value: the ID (greater than 0) for the source within the
886 g_source_attach (GSource *source,
887 GMainContext *context)
891 g_return_val_if_fail (source->context == NULL, 0);
892 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
895 context = g_main_context_default ();
897 LOCK_CONTEXT (context);
899 result = g_source_attach_unlocked (source, context);
901 /* If another thread has acquired the context, wake it up since it
902 * might be in poll() right now.
904 if (context->owner && context->owner != G_THREAD_SELF)
905 g_wakeup_signal (context->wakeup);
907 UNLOCK_CONTEXT (context);
913 g_source_destroy_internal (GSource *source,
914 GMainContext *context,
918 LOCK_CONTEXT (context);
920 if (!SOURCE_DESTROYED (source))
923 gpointer old_cb_data;
924 GSourceCallbackFuncs *old_cb_funcs;
926 source->flags &= ~G_HOOK_FLAG_ACTIVE;
928 old_cb_data = source->callback_data;
929 old_cb_funcs = source->callback_funcs;
931 source->callback_data = NULL;
932 source->callback_funcs = NULL;
936 UNLOCK_CONTEXT (context);
937 old_cb_funcs->unref (old_cb_data);
938 LOCK_CONTEXT (context);
941 if (!SOURCE_BLOCKED (source))
943 tmp_list = source->poll_fds;
946 g_main_context_remove_poll_unlocked (context, tmp_list->data);
947 tmp_list = tmp_list->next;
951 if (source->priv && source->priv->child_sources)
953 /* This is safe because even if a child_source finalizer or
954 * closure notify tried to modify source->priv->child_sources
955 * from outside the lock, it would fail since
956 * SOURCE_DESTROYED(source) is now TRUE.
958 tmp_list = source->priv->child_sources;
961 g_source_destroy_internal (tmp_list->data, context, TRUE);
962 g_source_unref_internal (tmp_list->data, context, TRUE);
963 tmp_list = tmp_list->next;
965 g_slist_free (source->priv->child_sources);
966 source->priv->child_sources = NULL;
969 g_source_unref_internal (source, context, TRUE);
973 UNLOCK_CONTEXT (context);
978 * @source: a #GSource
980 * Removes a source from its #GMainContext, if any, and mark it as
981 * destroyed. The source cannot be subsequently added to another
985 g_source_destroy (GSource *source)
987 GMainContext *context;
989 g_return_if_fail (source != NULL);
991 context = source->context;
994 g_source_destroy_internal (source, context, FALSE);
996 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1001 * @source: a #GSource
1003 * Returns the numeric ID for a particular source. The ID of a source
1004 * is a positive integer which is unique within a particular main loop
1005 * context. The reverse
1006 * mapping from ID to source is done by g_main_context_find_source_by_id().
1008 * Return value: the ID (greater than 0) for the source
1011 g_source_get_id (GSource *source)
1015 g_return_val_if_fail (source != NULL, 0);
1016 g_return_val_if_fail (source->context != NULL, 0);
1018 LOCK_CONTEXT (source->context);
1019 result = source->source_id;
1020 UNLOCK_CONTEXT (source->context);
1026 * g_source_get_context:
1027 * @source: a #GSource
1029 * Gets the #GMainContext with which the source is associated.
1030 * Calling this function on a destroyed source is an error.
1032 * Return value: (transfer none): the #GMainContext with which the
1033 * source is associated, or %NULL if the context has not
1034 * yet been added to a source.
1037 g_source_get_context (GSource *source)
1039 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1041 return source->context;
1045 * g_source_add_poll:
1046 * @source:a #GSource
1047 * @fd: a #GPollFD structure holding information about a file
1048 * descriptor to watch.
1050 * Adds a file descriptor to the set of file descriptors polled for
1051 * this source. This is usually combined with g_source_new() to add an
1052 * event source. The event source's check function will typically test
1053 * the @revents field in the #GPollFD struct and return %TRUE if events need
1057 g_source_add_poll (GSource *source,
1060 GMainContext *context;
1062 g_return_if_fail (source != NULL);
1063 g_return_if_fail (fd != NULL);
1064 g_return_if_fail (!SOURCE_DESTROYED (source));
1066 context = source->context;
1069 LOCK_CONTEXT (context);
1071 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1075 if (!SOURCE_BLOCKED (source))
1076 g_main_context_add_poll_unlocked (context, source->priority, fd);
1077 UNLOCK_CONTEXT (context);
1082 * g_source_remove_poll:
1083 * @source:a #GSource
1084 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1086 * Removes a file descriptor from the set of file descriptors polled for
1090 g_source_remove_poll (GSource *source,
1093 GMainContext *context;
1095 g_return_if_fail (source != NULL);
1096 g_return_if_fail (fd != NULL);
1097 g_return_if_fail (!SOURCE_DESTROYED (source));
1099 context = source->context;
1102 LOCK_CONTEXT (context);
1104 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1108 if (!SOURCE_BLOCKED (source))
1109 g_main_context_remove_poll_unlocked (context, fd);
1110 UNLOCK_CONTEXT (context);
1115 * g_source_add_child_source:
1116 * @source:a #GSource
1117 * @child_source: a second #GSource that @source should "poll"
1119 * Adds @child_source to @source as a "polled" source; when @source is
1120 * added to a #GMainContext, @child_source will be automatically added
1121 * with the same priority, when @child_source is triggered, it will
1122 * cause @source to dispatch (in addition to calling its own
1123 * callback), and when @source is destroyed, it will destroy
1124 * @child_source as well. (@source will also still be dispatched if
1125 * its own prepare/check functions indicate that it is ready.)
1127 * If you don't need @child_source to do anything on its own when it
1128 * triggers, you can call g_source_set_dummy_callback() on it to set a
1129 * callback that does nothing (except return %TRUE if appropriate).
1131 * @source will hold a reference on @child_source while @child_source
1132 * is attached to it.
1137 g_source_add_child_source (GSource *source,
1138 GSource *child_source)
1140 GMainContext *context;
1142 g_return_if_fail (source != NULL);
1143 g_return_if_fail (child_source != NULL);
1144 g_return_if_fail (!SOURCE_DESTROYED (source));
1145 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1146 g_return_if_fail (child_source->context == NULL);
1147 g_return_if_fail (child_source->priv == NULL || child_source->priv->parent_source == NULL);
1149 context = source->context;
1152 LOCK_CONTEXT (context);
1155 source->priv = g_slice_new0 (GSourcePrivate);
1156 if (!child_source->priv)
1157 child_source->priv = g_slice_new0 (GSourcePrivate);
1159 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1160 g_source_ref (child_source));
1161 child_source->priv->parent_source = source;
1162 g_source_set_priority_unlocked (child_source, context, source->priority);
1166 UNLOCK_CONTEXT (context);
1167 g_source_attach (child_source, context);
1172 * g_source_remove_child_source:
1173 * @source:a #GSource
1174 * @child_source: a #GSource previously passed to
1175 * g_source_add_child_source().
1177 * Detaches @child_source from @source and destroys it.
1182 g_source_remove_child_source (GSource *source,
1183 GSource *child_source)
1185 GMainContext *context;
1187 g_return_if_fail (source != NULL);
1188 g_return_if_fail (child_source != NULL);
1189 g_return_if_fail (child_source->priv != NULL && child_source->priv->parent_source == source);
1190 g_return_if_fail (!SOURCE_DESTROYED (source));
1191 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1193 context = source->context;
1196 LOCK_CONTEXT (context);
1198 source->priv->child_sources = g_slist_remove (source->priv->child_sources, child_source);
1199 g_source_destroy_internal (child_source, context, TRUE);
1200 g_source_unref_internal (child_source, context, TRUE);
1203 UNLOCK_CONTEXT (context);
1207 * g_source_set_callback_indirect:
1208 * @source: the source
1209 * @callback_data: pointer to callback data "object"
1210 * @callback_funcs: functions for reference counting @callback_data
1211 * and getting the callback and data
1213 * Sets the callback function storing the data as a refcounted callback
1214 * "object". This is used internally. Note that calling
1215 * g_source_set_callback_indirect() assumes
1216 * an initial reference count on @callback_data, and thus
1217 * @callback_funcs->unref will eventually be called once more
1218 * than @callback_funcs->ref.
1221 g_source_set_callback_indirect (GSource *source,
1222 gpointer callback_data,
1223 GSourceCallbackFuncs *callback_funcs)
1225 GMainContext *context;
1226 gpointer old_cb_data;
1227 GSourceCallbackFuncs *old_cb_funcs;
1229 g_return_if_fail (source != NULL);
1230 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1232 context = source->context;
1235 LOCK_CONTEXT (context);
1237 old_cb_data = source->callback_data;
1238 old_cb_funcs = source->callback_funcs;
1240 source->callback_data = callback_data;
1241 source->callback_funcs = callback_funcs;
1244 UNLOCK_CONTEXT (context);
1247 old_cb_funcs->unref (old_cb_data);
1251 g_source_callback_ref (gpointer cb_data)
1253 GSourceCallback *callback = cb_data;
1255 callback->ref_count++;
1260 g_source_callback_unref (gpointer cb_data)
1262 GSourceCallback *callback = cb_data;
1264 callback->ref_count--;
1265 if (callback->ref_count == 0)
1267 if (callback->notify)
1268 callback->notify (callback->data);
1274 g_source_callback_get (gpointer cb_data,
1279 GSourceCallback *callback = cb_data;
1281 *func = callback->func;
1282 *data = callback->data;
1285 static GSourceCallbackFuncs g_source_callback_funcs = {
1286 g_source_callback_ref,
1287 g_source_callback_unref,
1288 g_source_callback_get,
1292 * g_source_set_callback:
1293 * @source: the source
1294 * @func: a callback function
1295 * @data: the data to pass to callback function
1296 * @notify: a function to call when @data is no longer in use, or %NULL.
1298 * Sets the callback function for a source. The callback for a source is
1299 * called from the source's dispatch function.
1301 * The exact type of @func depends on the type of source; ie. you
1302 * should not count on @func being called with @data as its first
1305 * Typically, you won't use this function. Instead use functions specific
1306 * to the type of source you are using.
1309 g_source_set_callback (GSource *source,
1312 GDestroyNotify notify)
1314 GSourceCallback *new_callback;
1316 g_return_if_fail (source != NULL);
1318 new_callback = g_new (GSourceCallback, 1);
1320 new_callback->ref_count = 1;
1321 new_callback->func = func;
1322 new_callback->data = data;
1323 new_callback->notify = notify;
1325 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1330 * g_source_set_funcs:
1331 * @source: a #GSource
1332 * @funcs: the new #GSourceFuncs
1334 * Sets the source functions (can be used to override
1335 * default implementations) of an unattached source.
1340 g_source_set_funcs (GSource *source,
1341 GSourceFuncs *funcs)
1343 g_return_if_fail (source != NULL);
1344 g_return_if_fail (source->context == NULL);
1345 g_return_if_fail (source->ref_count > 0);
1346 g_return_if_fail (funcs != NULL);
1348 source->source_funcs = funcs;
1352 g_source_set_priority_unlocked (GSource *source,
1353 GMainContext *context,
1358 source->priority = priority;
1362 /* Remove the source from the context's source and then
1363 * add it back so it is sorted in the correct place
1365 g_source_list_remove (source, source->context);
1366 g_source_list_add (source, source->context);
1368 if (!SOURCE_BLOCKED (source))
1370 tmp_list = source->poll_fds;
1373 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1374 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1376 tmp_list = tmp_list->next;
1381 if (source->priv && source->priv->child_sources)
1383 tmp_list = source->priv->child_sources;
1386 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1387 tmp_list = tmp_list->next;
1393 * g_source_set_priority:
1394 * @source: a #GSource
1395 * @priority: the new priority.
1397 * Sets the priority of a source. While the main loop is being run, a
1398 * source will be dispatched if it is ready to be dispatched and no
1399 * sources at a higher (numerically smaller) priority are ready to be
1403 g_source_set_priority (GSource *source,
1406 GMainContext *context;
1408 g_return_if_fail (source != NULL);
1410 context = source->context;
1413 LOCK_CONTEXT (context);
1414 g_source_set_priority_unlocked (source, context, priority);
1416 UNLOCK_CONTEXT (source->context);
1420 * g_source_get_priority:
1421 * @source: a #GSource
1423 * Gets the priority of a source.
1425 * Return value: the priority of the source
1428 g_source_get_priority (GSource *source)
1430 g_return_val_if_fail (source != NULL, 0);
1432 return source->priority;
1436 * g_source_set_can_recurse:
1437 * @source: a #GSource
1438 * @can_recurse: whether recursion is allowed for this source
1440 * Sets whether a source can be called recursively. If @can_recurse is
1441 * %TRUE, then while the source is being dispatched then this source
1442 * will be processed normally. Otherwise, all processing of this
1443 * source is blocked until the dispatch function returns.
1446 g_source_set_can_recurse (GSource *source,
1447 gboolean can_recurse)
1449 GMainContext *context;
1451 g_return_if_fail (source != NULL);
1453 context = source->context;
1456 LOCK_CONTEXT (context);
1459 source->flags |= G_SOURCE_CAN_RECURSE;
1461 source->flags &= ~G_SOURCE_CAN_RECURSE;
1464 UNLOCK_CONTEXT (context);
1468 * g_source_get_can_recurse:
1469 * @source: a #GSource
1471 * Checks whether a source is allowed to be called recursively.
1472 * see g_source_set_can_recurse().
1474 * Return value: whether recursion is allowed.
1477 g_source_get_can_recurse (GSource *source)
1479 g_return_val_if_fail (source != NULL, FALSE);
1481 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1486 * g_source_set_name:
1487 * @source: a #GSource
1488 * @name: debug name for the source
1490 * Sets a name for the source, used in debugging and profiling.
1491 * The name defaults to #NULL.
1493 * The source name should describe in a human-readable way
1494 * what the source does. For example, "X11 event queue"
1495 * or "GTK+ repaint idle handler" or whatever it is.
1497 * It is permitted to call this function multiple times, but is not
1498 * recommended due to the potential performance impact. For example,
1499 * one could change the name in the "check" function of a #GSourceFuncs
1500 * to include details like the event type in the source name.
1505 g_source_set_name (GSource *source,
1508 g_return_if_fail (source != NULL);
1510 /* setting back to NULL is allowed, just because it's
1511 * weird if get_name can return NULL but you can't
1515 g_free (source->name);
1516 source->name = g_strdup (name);
1520 * g_source_get_name:
1521 * @source: a #GSource
1523 * Gets a name for the source, used in debugging and profiling.
1524 * The name may be #NULL if it has never been set with
1525 * g_source_set_name().
1527 * Return value: the name of the source
1531 g_source_get_name (GSource *source)
1533 g_return_val_if_fail (source != NULL, NULL);
1535 return source->name;
1539 * g_source_set_name_by_id:
1540 * @tag: a #GSource ID
1541 * @name: debug name for the source
1543 * Sets the name of a source using its ID.
1545 * This is a convenience utility to set source names from the return
1546 * value of g_idle_add(), g_timeout_add(), etc.
1551 g_source_set_name_by_id (guint tag,
1556 g_return_if_fail (tag > 0);
1558 source = g_main_context_find_source_by_id (NULL, tag);
1562 g_source_set_name (source, name);
1568 * @source: a #GSource
1570 * Increases the reference count on a source by one.
1572 * Return value: @source
1575 g_source_ref (GSource *source)
1577 GMainContext *context;
1579 g_return_val_if_fail (source != NULL, NULL);
1581 context = source->context;
1584 LOCK_CONTEXT (context);
1586 source->ref_count++;
1589 UNLOCK_CONTEXT (context);
1594 /* g_source_unref() but possible to call within context lock
1597 g_source_unref_internal (GSource *source,
1598 GMainContext *context,
1601 gpointer old_cb_data = NULL;
1602 GSourceCallbackFuncs *old_cb_funcs = NULL;
1604 g_return_if_fail (source != NULL);
1606 if (!have_lock && context)
1607 LOCK_CONTEXT (context);
1609 source->ref_count--;
1610 if (source->ref_count == 0)
1612 old_cb_data = source->callback_data;
1613 old_cb_funcs = source->callback_funcs;
1615 source->callback_data = NULL;
1616 source->callback_funcs = NULL;
1620 if (!SOURCE_DESTROYED (source))
1621 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
1622 g_source_list_remove (source, context);
1625 if (source->source_funcs->finalize)
1628 UNLOCK_CONTEXT (context);
1629 source->source_funcs->finalize (source);
1631 LOCK_CONTEXT (context);
1634 g_free (source->name);
1635 source->name = NULL;
1637 g_slist_free (source->poll_fds);
1638 source->poll_fds = NULL;
1642 g_slice_free (GSourcePrivate, source->priv);
1643 source->priv = NULL;
1649 if (!have_lock && context)
1650 UNLOCK_CONTEXT (context);
1655 UNLOCK_CONTEXT (context);
1657 old_cb_funcs->unref (old_cb_data);
1660 LOCK_CONTEXT (context);
1666 * @source: a #GSource
1668 * Decreases the reference count of a source by one. If the
1669 * resulting reference count is zero the source and associated
1670 * memory will be destroyed.
1673 g_source_unref (GSource *source)
1675 g_return_if_fail (source != NULL);
1677 g_source_unref_internal (source, source->context, FALSE);
1681 * g_main_context_find_source_by_id:
1682 * @context: a #GMainContext (if %NULL, the default context will be used)
1683 * @source_id: the source ID, as returned by g_source_get_id().
1685 * Finds a #GSource given a pair of context and ID.
1687 * Return value: (transfer none): the #GSource if found, otherwise, %NULL
1690 g_main_context_find_source_by_id (GMainContext *context,
1695 g_return_val_if_fail (source_id > 0, NULL);
1697 if (context == NULL)
1698 context = g_main_context_default ();
1700 LOCK_CONTEXT (context);
1702 source = context->source_list;
1705 if (!SOURCE_DESTROYED (source) &&
1706 source->source_id == source_id)
1708 source = source->next;
1711 UNLOCK_CONTEXT (context);
1717 * g_main_context_find_source_by_funcs_user_data:
1718 * @context: a #GMainContext (if %NULL, the default context will be used).
1719 * @funcs: the @source_funcs passed to g_source_new().
1720 * @user_data: the user data from the callback.
1722 * Finds a source with the given source functions and user data. If
1723 * multiple sources exist with the same source function and user data,
1724 * the first one found will be returned.
1726 * Return value: (transfer none): the source, if one was found, otherwise %NULL
1729 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1730 GSourceFuncs *funcs,
1735 g_return_val_if_fail (funcs != NULL, NULL);
1737 if (context == NULL)
1738 context = g_main_context_default ();
1740 LOCK_CONTEXT (context);
1742 source = context->source_list;
1745 if (!SOURCE_DESTROYED (source) &&
1746 source->source_funcs == funcs &&
1747 source->callback_funcs)
1749 GSourceFunc callback;
1750 gpointer callback_data;
1752 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1754 if (callback_data == user_data)
1757 source = source->next;
1760 UNLOCK_CONTEXT (context);
1766 * g_main_context_find_source_by_user_data:
1767 * @context: a #GMainContext
1768 * @user_data: the user_data for the callback.
1770 * Finds a source with the given user data for the callback. If
1771 * multiple sources exist with the same user data, the first
1772 * one found will be returned.
1774 * Return value: (transfer none): the source, if one was found, otherwise %NULL
1777 g_main_context_find_source_by_user_data (GMainContext *context,
1782 if (context == NULL)
1783 context = g_main_context_default ();
1785 LOCK_CONTEXT (context);
1787 source = context->source_list;
1790 if (!SOURCE_DESTROYED (source) &&
1791 source->callback_funcs)
1793 GSourceFunc callback;
1794 gpointer callback_data = NULL;
1796 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1798 if (callback_data == user_data)
1801 source = source->next;
1804 UNLOCK_CONTEXT (context);
1811 * @tag: the ID of the source to remove.
1813 * Removes the source with the given id from the default main context.
1815 * a #GSource is given by g_source_get_id(), or will be returned by the
1816 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1817 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1818 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1820 * See also g_source_destroy(). You must use g_source_destroy() for sources
1821 * added to a non-default main context.
1823 * Return value: %TRUE if the source was found and removed.
1826 g_source_remove (guint tag)
1830 g_return_val_if_fail (tag > 0, FALSE);
1832 source = g_main_context_find_source_by_id (NULL, tag);
1834 g_source_destroy (source);
1836 return source != NULL;
1840 * g_source_remove_by_user_data:
1841 * @user_data: the user_data for the callback.
1843 * Removes a source from the default main loop context given the user
1844 * data for the callback. If multiple sources exist with the same user
1845 * data, only one will be destroyed.
1847 * Return value: %TRUE if a source was found and removed.
1850 g_source_remove_by_user_data (gpointer user_data)
1854 source = g_main_context_find_source_by_user_data (NULL, user_data);
1857 g_source_destroy (source);
1865 * g_source_remove_by_funcs_user_data:
1866 * @funcs: The @source_funcs passed to g_source_new()
1867 * @user_data: the user data for the callback
1869 * Removes a source from the default main loop context given the
1870 * source functions and user data. If multiple sources exist with the
1871 * same source functions and user data, only one will be destroyed.
1873 * Return value: %TRUE if a source was found and removed.
1876 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1881 g_return_val_if_fail (funcs != NULL, FALSE);
1883 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1886 g_source_destroy (source);
1894 * g_get_current_time:
1895 * @result: #GTimeVal structure in which to store current time.
1897 * Equivalent to the UNIX gettimeofday() function, but portable.
1899 * You may find g_get_real_time() to be more convenient.
1902 g_get_current_time (GTimeVal *result)
1907 g_return_if_fail (result != NULL);
1909 /*this is required on alpha, there the timeval structs are int's
1910 not longs and a cast only would fail horribly*/
1911 gettimeofday (&r, NULL);
1912 result->tv_sec = r.tv_sec;
1913 result->tv_usec = r.tv_usec;
1918 g_return_if_fail (result != NULL);
1920 GetSystemTimeAsFileTime (&ft);
1921 memmove (&time64, &ft, sizeof (FILETIME));
1923 /* Convert from 100s of nanoseconds since 1601-01-01
1924 * to Unix epoch. Yes, this is Y2038 unsafe.
1926 time64 -= G_GINT64_CONSTANT (116444736000000000);
1929 result->tv_sec = time64 / 1000000;
1930 result->tv_usec = time64 % 1000000;
1937 * Queries the system wall-clock time.
1939 * This call is functionally equivalent to g_get_current_time() except
1940 * that the return value is often more convenient than dealing with a
1943 * You should only use this call if you are actually interested in the real
1944 * wall-clock time. g_get_monotonic_time() is probably more useful for
1945 * measuring intervals.
1947 * Returns: the number of microseconds since January 1, 1970 UTC.
1952 g_get_real_time (void)
1956 g_get_current_time (&tv);
1958 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
1962 * g_get_monotonic_time:
1964 * Queries the system monotonic time, if available.
1966 * On POSIX systems with clock_gettime() and %CLOCK_MONOTONIC this call
1967 * is a very shallow wrapper for that. Otherwise, we make a best effort
1968 * that probably involves returning the wall clock time (with at least
1969 * microsecond accuracy, subject to the limitations of the OS kernel).
1971 * It's important to note that POSIX %CLOCK_MONOTONIC does not count
1972 * time spent while the machine is suspended.
1974 * On Windows, "limitations of the OS kernel" is a rather substantial
1975 * statement. Depending on the configuration of the system, the wall
1976 * clock time is updated as infrequently as 64 times a second (which
1977 * is approximately every 16ms).
1979 * Returns: the monotonic time, in microseconds
1984 g_get_monotonic_time (void)
1986 #ifdef HAVE_CLOCK_GETTIME
1987 /* librt clock_gettime() is our first choice */
1989 #ifdef HAVE_MONOTONIC_CLOCK
1990 static volatile gsize clockid = 0;
1992 static clockid_t clockid = CLOCK_REALTIME;
1996 #ifdef HAVE_MONOTONIC_CLOCK
1997 if (g_once_init_enter (&clockid))
1999 clockid_t best_clockid;
2001 if (sysconf (_SC_MONOTONIC_CLOCK) >= 0)
2002 best_clockid = CLOCK_MONOTONIC;
2004 best_clockid = CLOCK_REALTIME;
2005 g_once_init_leave (&clockid, (gsize)best_clockid);
2009 clock_gettime (clockid, &ts);
2011 /* In theory monotonic time can have any epoch.
2013 * glib presently assumes the following:
2015 * 1) The epoch comes some time after the birth of Jesus of Nazareth, but
2016 * not more than 10000 years later.
2018 * 2) The current time also falls sometime within this range.
2020 * These two reasonable assumptions leave us with a maximum deviation from
2021 * the epoch of 10000 years, or 315569520000000000 seconds.
2023 * If we restrict ourselves to this range then the number of microseconds
2024 * will always fit well inside the constraints of a int64 (by a factor of
2027 * If you actually hit the following assertion, probably you should file a
2028 * bug against your operating system for being excessively silly.
2030 g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts.tv_sec &&
2031 ts.tv_sec < G_GINT64_CONSTANT (315569520000000000));
2033 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2036 /* It may look like we are discarding accuracy on Windows (since its
2037 * current time is expressed in 100s of nanoseconds) but according to
2038 * many sources, the time is only updated 64 times per second, so
2039 * microsecond accuracy is more than enough.
2044 g_get_current_time (&tv);
2046 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2052 g_main_dispatch_free (gpointer dispatch)
2054 g_slice_free (GMainDispatch, dispatch);
2057 /* Running the main loop */
2059 static GMainDispatch *
2062 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
2063 GMainDispatch *dispatch = g_static_private_get (&depth_private);
2066 dispatch = g_slice_new0 (GMainDispatch);
2067 g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
2076 * Returns the depth of the stack of calls to
2077 * g_main_context_dispatch() on any #GMainContext in the current thread.
2078 * That is, when called from the toplevel, it gives 0. When
2079 * called from within a callback from g_main_context_iteration()
2080 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2081 * a callback to a recursive call to g_main_context_iteration(),
2082 * it returns 2. And so forth.
2084 * This function is useful in a situation like the following:
2085 * Imagine an extremely simple "garbage collected" system.
2088 * static GList *free_list;
2091 * allocate_memory (gsize size)
2093 * gpointer result = g_malloc (size);
2094 * free_list = g_list_prepend (free_list, result);
2099 * free_allocated_memory (void)
2102 * for (l = free_list; l; l = l->next);
2104 * g_list_free (free_list);
2112 * g_main_context_iteration (NULL, TRUE);
2113 * free_allocated_memory();
2117 * This works from an application, however, if you want to do the same
2118 * thing from a library, it gets more difficult, since you no longer
2119 * control the main loop. You might think you can simply use an idle
2120 * function to make the call to free_allocated_memory(), but that
2121 * doesn't work, since the idle function could be called from a
2122 * recursive callback. This can be fixed by using g_main_depth()
2126 * allocate_memory (gsize size)
2128 * FreeListBlock *block = g_new (FreeListBlock, 1);
2129 * block->mem = g_malloc (size);
2130 * block->depth = g_main_depth ();
2131 * free_list = g_list_prepend (free_list, block);
2132 * return block->mem;
2136 * free_allocated_memory (void)
2140 * int depth = g_main_depth ();
2141 * for (l = free_list; l; );
2143 * GList *next = l->next;
2144 * FreeListBlock *block = l->data;
2145 * if (block->depth > depth)
2147 * g_free (block->mem);
2149 * free_list = g_list_delete_link (free_list, l);
2157 * There is a temptation to use g_main_depth() to solve
2158 * problems with reentrancy. For instance, while waiting for data
2159 * to be received from the network in response to a menu item,
2160 * the menu item might be selected again. It might seem that
2161 * one could make the menu item's callback return immediately
2162 * and do nothing if g_main_depth() returns a value greater than 1.
2163 * However, this should be avoided since the user then sees selecting
2164 * the menu item do nothing. Furthermore, you'll find yourself adding
2165 * these checks all over your code, since there are doubtless many,
2166 * many things that the user could do. Instead, you can use the
2167 * following techniques:
2172 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
2173 * the user from interacting with elements while the main
2174 * loop is recursing.
2179 * Avoid main loop recursion in situations where you can't handle
2180 * arbitrary callbacks. Instead, structure your code so that you
2181 * simply return to the main loop and then get called again when
2182 * there is more work to do.
2187 * Return value: The main loop recursion level in the current thread
2192 GMainDispatch *dispatch = get_dispatch ();
2193 return dispatch->depth;
2197 * g_main_current_source:
2199 * Returns the currently firing source for this thread.
2201 * Return value: (transfer none): The currently firing source or %NULL.
2206 g_main_current_source (void)
2208 GMainDispatch *dispatch = get_dispatch ();
2209 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
2213 * g_source_is_destroyed:
2214 * @source: a #GSource
2216 * Returns whether @source has been destroyed.
2218 * This is important when you operate upon your objects
2219 * from within idle handlers, but may have freed the object
2220 * before the dispatch of your idle handler.
2224 * idle_callback (gpointer data)
2226 * SomeWidget *self = data;
2228 * GDK_THREADS_ENTER (<!-- -->);
2229 * /<!-- -->* do stuff with self *<!-- -->/
2230 * self->idle_id = 0;
2231 * GDK_THREADS_LEAVE (<!-- -->);
2237 * some_widget_do_stuff_later (SomeWidget *self)
2239 * self->idle_id = g_idle_add (idle_callback, self);
2243 * some_widget_finalize (GObject *object)
2245 * SomeWidget *self = SOME_WIDGET (object);
2247 * if (self->idle_id)
2248 * g_source_remove (self->idle_id);
2250 * G_OBJECT_CLASS (parent_class)->finalize (object);
2254 * This will fail in a multi-threaded application if the
2255 * widget is destroyed before the idle handler fires due
2256 * to the use after free in the callback. A solution, to
2257 * this particular problem, is to check to if the source
2258 * has already been destroy within the callback.
2262 * idle_callback (gpointer data)
2264 * SomeWidget *self = data;
2266 * GDK_THREADS_ENTER ();
2267 * if (!g_source_is_destroyed (g_main_current_source ()))
2269 * /<!-- -->* do stuff with self *<!-- -->/
2271 * GDK_THREADS_LEAVE ();
2277 * Return value: %TRUE if the source has been destroyed
2282 g_source_is_destroyed (GSource *source)
2284 return SOURCE_DESTROYED (source);
2287 /* Temporarily remove all this source's file descriptors from the
2288 * poll(), so that if data comes available for one of the file descriptors
2289 * we don't continually spin in the poll()
2291 /* HOLDS: source->context's lock */
2293 block_source (GSource *source)
2297 g_return_if_fail (!SOURCE_BLOCKED (source));
2299 tmp_list = source->poll_fds;
2302 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2303 tmp_list = tmp_list->next;
2307 /* HOLDS: source->context's lock */
2309 unblock_source (GSource *source)
2313 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
2314 g_return_if_fail (!SOURCE_DESTROYED (source));
2316 tmp_list = source->poll_fds;
2319 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2320 tmp_list = tmp_list->next;
2324 /* HOLDS: context's lock */
2326 g_main_dispatch (GMainContext *context)
2328 GMainDispatch *current = get_dispatch ();
2331 for (i = 0; i < context->pending_dispatches->len; i++)
2333 GSource *source = context->pending_dispatches->pdata[i];
2335 context->pending_dispatches->pdata[i] = NULL;
2338 source->flags &= ~G_SOURCE_READY;
2340 if (!SOURCE_DESTROYED (source))
2342 gboolean was_in_call;
2343 gpointer user_data = NULL;
2344 GSourceFunc callback = NULL;
2345 GSourceCallbackFuncs *cb_funcs;
2347 gboolean need_destroy;
2349 gboolean (*dispatch) (GSource *,
2352 GSList current_source_link;
2354 dispatch = source->source_funcs->dispatch;
2355 cb_funcs = source->callback_funcs;
2356 cb_data = source->callback_data;
2359 cb_funcs->ref (cb_data);
2361 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2362 block_source (source);
2364 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2365 source->flags |= G_HOOK_FLAG_IN_CALL;
2368 cb_funcs->get (cb_data, source, &callback, &user_data);
2370 UNLOCK_CONTEXT (context);
2373 /* The on-stack allocation of the GSList is unconventional, but
2374 * we know that the lifetime of the link is bounded to this
2375 * function as the link is kept in a thread specific list and
2376 * not manipulated outside of this function and its descendants.
2377 * Avoiding the overhead of a g_slist_alloc() is useful as many
2378 * applications do little more than dispatch events.
2380 * This is a performance hack - do not revert to g_slist_prepend()!
2382 current_source_link.data = source;
2383 current_source_link.next = current->dispatching_sources;
2384 current->dispatching_sources = ¤t_source_link;
2385 need_destroy = ! dispatch (source,
2388 g_assert (current->dispatching_sources == ¤t_source_link);
2389 current->dispatching_sources = current_source_link.next;
2393 cb_funcs->unref (cb_data);
2395 LOCK_CONTEXT (context);
2398 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2400 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2401 !SOURCE_DESTROYED (source))
2402 unblock_source (source);
2404 /* Note: this depends on the fact that we can't switch
2405 * sources from one main context to another
2407 if (need_destroy && !SOURCE_DESTROYED (source))
2409 g_assert (source->context == context);
2410 g_source_destroy_internal (source, context, TRUE);
2414 SOURCE_UNREF (source, context);
2417 g_ptr_array_set_size (context->pending_dispatches, 0);
2420 /* Holds context's lock */
2421 static inline GSource *
2422 next_valid_source (GMainContext *context,
2425 GSource *new_source = source ? source->next : context->source_list;
2429 if (!SOURCE_DESTROYED (new_source))
2431 new_source->ref_count++;
2435 new_source = new_source->next;
2439 SOURCE_UNREF (source, context);
2445 * g_main_context_acquire:
2446 * @context: a #GMainContext
2448 * Tries to become the owner of the specified context.
2449 * If some other thread is the owner of the context,
2450 * returns %FALSE immediately. Ownership is properly
2451 * recursive: the owner can require ownership again
2452 * and will release ownership when g_main_context_release()
2453 * is called as many times as g_main_context_acquire().
2455 * You must be the owner of a context before you
2456 * can call g_main_context_prepare(), g_main_context_query(),
2457 * g_main_context_check(), g_main_context_dispatch().
2459 * Return value: %TRUE if the operation succeeded, and
2460 * this thread is now the owner of @context.
2463 g_main_context_acquire (GMainContext *context)
2465 gboolean result = FALSE;
2466 GThread *self = G_THREAD_SELF;
2468 if (context == NULL)
2469 context = g_main_context_default ();
2471 LOCK_CONTEXT (context);
2473 if (!context->owner)
2475 context->owner = self;
2476 g_assert (context->owner_count == 0);
2479 if (context->owner == self)
2481 context->owner_count++;
2485 UNLOCK_CONTEXT (context);
2491 * g_main_context_release:
2492 * @context: a #GMainContext
2494 * Releases ownership of a context previously acquired by this thread
2495 * with g_main_context_acquire(). If the context was acquired multiple
2496 * times, the ownership will be released only when g_main_context_release()
2497 * is called as many times as it was acquired.
2500 g_main_context_release (GMainContext *context)
2502 if (context == NULL)
2503 context = g_main_context_default ();
2505 LOCK_CONTEXT (context);
2507 context->owner_count--;
2508 if (context->owner_count == 0)
2510 context->owner = NULL;
2512 if (context->waiters)
2514 GMainWaiter *waiter = context->waiters->data;
2515 gboolean loop_internal_waiter = (waiter->mutex == &context->mutex);
2516 context->waiters = g_slist_delete_link (context->waiters,
2518 if (!loop_internal_waiter)
2519 g_mutex_lock (waiter->mutex);
2521 g_cond_signal (waiter->cond);
2523 if (!loop_internal_waiter)
2524 g_mutex_unlock (waiter->mutex);
2528 UNLOCK_CONTEXT (context);
2532 * g_main_context_wait:
2533 * @context: a #GMainContext
2534 * @cond: a condition variable
2535 * @mutex: a mutex, currently held
2537 * Tries to become the owner of the specified context,
2538 * as with g_main_context_acquire(). But if another thread
2539 * is the owner, atomically drop @mutex and wait on @cond until
2540 * that owner releases ownership or until @cond is signaled, then
2541 * try again (once) to become the owner.
2543 * Return value: %TRUE if the operation succeeded, and
2544 * this thread is now the owner of @context.
2547 g_main_context_wait (GMainContext *context,
2551 gboolean result = FALSE;
2552 GThread *self = G_THREAD_SELF;
2553 gboolean loop_internal_waiter;
2555 if (context == NULL)
2556 context = g_main_context_default ();
2558 loop_internal_waiter = (mutex == &context->mutex);
2560 if (!loop_internal_waiter)
2561 LOCK_CONTEXT (context);
2563 if (context->owner && context->owner != self)
2568 waiter.mutex = mutex;
2570 context->waiters = g_slist_append (context->waiters, &waiter);
2572 if (!loop_internal_waiter)
2573 UNLOCK_CONTEXT (context);
2574 g_cond_wait (cond, mutex);
2575 if (!loop_internal_waiter)
2576 LOCK_CONTEXT (context);
2578 context->waiters = g_slist_remove (context->waiters, &waiter);
2581 if (!context->owner)
2583 context->owner = self;
2584 g_assert (context->owner_count == 0);
2587 if (context->owner == self)
2589 context->owner_count++;
2593 if (!loop_internal_waiter)
2594 UNLOCK_CONTEXT (context);
2600 * g_main_context_prepare:
2601 * @context: a #GMainContext
2602 * @priority: location to store priority of highest priority
2603 * source already ready.
2605 * Prepares to poll sources within a main loop. The resulting information
2606 * for polling is determined by calling g_main_context_query ().
2608 * Return value: %TRUE if some source is ready to be dispatched
2612 g_main_context_prepare (GMainContext *context,
2617 gint current_priority = G_MAXINT;
2620 if (context == NULL)
2621 context = g_main_context_default ();
2623 LOCK_CONTEXT (context);
2625 context->time_is_fresh = FALSE;
2627 if (context->in_check_or_prepare)
2629 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2630 "prepare() member.");
2631 UNLOCK_CONTEXT (context);
2636 /* If recursing, finish up current dispatch, before starting over */
2637 if (context->pending_dispatches)
2640 g_main_dispatch (context, ¤t_time);
2642 UNLOCK_CONTEXT (context);
2647 /* If recursing, clear list of pending dispatches */
2649 for (i = 0; i < context->pending_dispatches->len; i++)
2651 if (context->pending_dispatches->pdata[i])
2652 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2654 g_ptr_array_set_size (context->pending_dispatches, 0);
2656 /* Prepare all sources */
2658 context->timeout = -1;
2660 source = next_valid_source (context, NULL);
2663 gint source_timeout = -1;
2665 if ((n_ready > 0) && (source->priority > current_priority))
2667 SOURCE_UNREF (source, context);
2670 if (SOURCE_BLOCKED (source))
2673 if (!(source->flags & G_SOURCE_READY))
2676 gboolean (*prepare) (GSource *source,
2679 prepare = source->source_funcs->prepare;
2680 context->in_check_or_prepare++;
2681 UNLOCK_CONTEXT (context);
2683 result = (*prepare) (source, &source_timeout);
2685 LOCK_CONTEXT (context);
2686 context->in_check_or_prepare--;
2690 GSource *ready_source = source;
2692 while (ready_source)
2694 ready_source->flags |= G_SOURCE_READY;
2695 ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2700 if (source->flags & G_SOURCE_READY)
2703 current_priority = source->priority;
2704 context->timeout = 0;
2707 if (source_timeout >= 0)
2709 if (context->timeout < 0)
2710 context->timeout = source_timeout;
2712 context->timeout = MIN (context->timeout, source_timeout);
2716 source = next_valid_source (context, source);
2719 UNLOCK_CONTEXT (context);
2722 *priority = current_priority;
2724 return (n_ready > 0);
2728 * g_main_context_query:
2729 * @context: a #GMainContext
2730 * @max_priority: maximum priority source to check
2731 * @timeout_: (out): location to store timeout to be used in polling
2732 * @fds: (out caller-allocates) (array length=n_fds): location to
2733 * store #GPollFD records that need to be polled.
2734 * @n_fds: length of @fds.
2736 * Determines information necessary to poll this main loop.
2738 * Return value: the number of records actually stored in @fds,
2739 * or, if more than @n_fds records need to be stored, the number
2740 * of records that need to be stored.
2743 g_main_context_query (GMainContext *context,
2752 LOCK_CONTEXT (context);
2754 pollrec = context->poll_records;
2756 while (pollrec && max_priority >= pollrec->priority)
2758 /* We need to include entries with fd->events == 0 in the array because
2759 * otherwise if the application changes fd->events behind our back and
2760 * makes it non-zero, we'll be out of sync when we check the fds[] array.
2761 * (Changing fd->events after adding an FD wasn't an anticipated use of
2762 * this API, but it occurs in practice.) */
2765 fds[n_poll].fd = pollrec->fd->fd;
2766 /* In direct contradiction to the Unix98 spec, IRIX runs into
2767 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2768 * flags in the events field of the pollfd while it should
2769 * just ignoring them. So we mask them out here.
2771 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2772 fds[n_poll].revents = 0;
2775 pollrec = pollrec->next;
2779 context->poll_changed = FALSE;
2783 *timeout = context->timeout;
2785 context->time_is_fresh = FALSE;
2788 UNLOCK_CONTEXT (context);
2794 * g_main_context_check:
2795 * @context: a #GMainContext
2796 * @max_priority: the maximum numerical priority of sources to check
2797 * @fds: (array length=n_fds): array of #GPollFD's that was passed to
2798 * the last call to g_main_context_query()
2799 * @n_fds: return value of g_main_context_query()
2801 * Passes the results of polling back to the main loop.
2803 * Return value: %TRUE if some sources are ready to be dispatched.
2806 g_main_context_check (GMainContext *context,
2816 LOCK_CONTEXT (context);
2818 if (context->in_check_or_prepare)
2820 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2821 "prepare() member.");
2822 UNLOCK_CONTEXT (context);
2826 if (context->wake_up_rec.events)
2827 g_wakeup_acknowledge (context->wakeup);
2829 /* If the set of poll file descriptors changed, bail out
2830 * and let the main loop rerun
2832 if (context->poll_changed)
2834 UNLOCK_CONTEXT (context);
2838 pollrec = context->poll_records;
2842 if (pollrec->fd->events)
2843 pollrec->fd->revents = fds[i].revents;
2845 pollrec = pollrec->next;
2849 source = next_valid_source (context, NULL);
2852 if ((n_ready > 0) && (source->priority > max_priority))
2854 SOURCE_UNREF (source, context);
2857 if (SOURCE_BLOCKED (source))
2860 if (!(source->flags & G_SOURCE_READY))
2863 gboolean (*check) (GSource *source);
2865 check = source->source_funcs->check;
2867 context->in_check_or_prepare++;
2868 UNLOCK_CONTEXT (context);
2870 result = (*check) (source);
2872 LOCK_CONTEXT (context);
2873 context->in_check_or_prepare--;
2877 GSource *ready_source = source;
2879 while (ready_source)
2881 ready_source->flags |= G_SOURCE_READY;
2882 ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2887 if (source->flags & G_SOURCE_READY)
2889 source->ref_count++;
2890 g_ptr_array_add (context->pending_dispatches, source);
2894 /* never dispatch sources with less priority than the first
2895 * one we choose to dispatch
2897 max_priority = source->priority;
2901 source = next_valid_source (context, source);
2904 UNLOCK_CONTEXT (context);
2910 * g_main_context_dispatch:
2911 * @context: a #GMainContext
2913 * Dispatches all pending sources.
2916 g_main_context_dispatch (GMainContext *context)
2918 LOCK_CONTEXT (context);
2920 if (context->pending_dispatches->len > 0)
2922 g_main_dispatch (context);
2925 UNLOCK_CONTEXT (context);
2928 /* HOLDS context lock */
2930 g_main_context_iterate (GMainContext *context,
2937 gboolean some_ready;
2938 gint nfds, allocated_nfds;
2939 GPollFD *fds = NULL;
2941 UNLOCK_CONTEXT (context);
2943 if (!g_main_context_acquire (context))
2945 gboolean got_ownership;
2947 LOCK_CONTEXT (context);
2952 got_ownership = g_main_context_wait (context,
2960 LOCK_CONTEXT (context);
2962 if (!context->cached_poll_array)
2964 context->cached_poll_array_size = context->n_poll_records;
2965 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2968 allocated_nfds = context->cached_poll_array_size;
2969 fds = context->cached_poll_array;
2971 UNLOCK_CONTEXT (context);
2973 g_main_context_prepare (context, &max_priority);
2975 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
2976 allocated_nfds)) > allocated_nfds)
2978 LOCK_CONTEXT (context);
2980 context->cached_poll_array_size = allocated_nfds = nfds;
2981 context->cached_poll_array = fds = g_new (GPollFD, nfds);
2982 UNLOCK_CONTEXT (context);
2988 g_assert (!g_main_context_fork_detected);
2989 g_main_context_poll (context, timeout, max_priority, fds, nfds);
2991 some_ready = g_main_context_check (context, max_priority, fds, nfds);
2994 g_main_context_dispatch (context);
2996 g_main_context_release (context);
2998 LOCK_CONTEXT (context);
3004 * g_main_context_pending:
3005 * @context: a #GMainContext (if %NULL, the default context will be used)
3007 * Checks if any sources have pending events for the given context.
3009 * Return value: %TRUE if events are pending.
3012 g_main_context_pending (GMainContext *context)
3017 context = g_main_context_default();
3019 LOCK_CONTEXT (context);
3020 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3021 UNLOCK_CONTEXT (context);
3027 * g_main_context_iteration:
3028 * @context: a #GMainContext (if %NULL, the default context will be used)
3029 * @may_block: whether the call may block.
3031 * Runs a single iteration for the given main loop. This involves
3032 * checking to see if any event sources are ready to be processed,
3033 * then if no events sources are ready and @may_block is %TRUE, waiting
3034 * for a source to become ready, then dispatching the highest priority
3035 * events sources that are ready. Otherwise, if @may_block is %FALSE
3036 * sources are not waited to become ready, only those highest priority
3037 * events sources will be dispatched (if any), that are ready at this
3038 * given moment without further waiting.
3040 * Note that even when @may_block is %TRUE, it is still possible for
3041 * g_main_context_iteration() to return %FALSE, since the the wait may
3042 * be interrupted for other reasons than an event source becoming ready.
3044 * Return value: %TRUE if events were dispatched.
3047 g_main_context_iteration (GMainContext *context, gboolean may_block)
3052 context = g_main_context_default();
3054 LOCK_CONTEXT (context);
3055 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3056 UNLOCK_CONTEXT (context);
3063 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
3064 * @is_running: set to %TRUE to indicate that the loop is running. This
3065 * is not very important since calling g_main_loop_run() will set this to
3068 * Creates a new #GMainLoop structure.
3070 * Return value: a new #GMainLoop.
3073 g_main_loop_new (GMainContext *context,
3074 gboolean is_running)
3079 context = g_main_context_default();
3081 g_main_context_ref (context);
3083 loop = g_new0 (GMainLoop, 1);
3084 loop->context = context;
3085 loop->is_running = is_running != FALSE;
3086 loop->ref_count = 1;
3093 * @loop: a #GMainLoop
3095 * Increases the reference count on a #GMainLoop object by one.
3097 * Return value: @loop
3100 g_main_loop_ref (GMainLoop *loop)
3102 g_return_val_if_fail (loop != NULL, NULL);
3103 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3105 g_atomic_int_inc (&loop->ref_count);
3111 * g_main_loop_unref:
3112 * @loop: a #GMainLoop
3114 * Decreases the reference count on a #GMainLoop object by one. If
3115 * the result is zero, free the loop and free all associated memory.
3118 g_main_loop_unref (GMainLoop *loop)
3120 g_return_if_fail (loop != NULL);
3121 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3123 if (!g_atomic_int_dec_and_test (&loop->ref_count))
3126 g_main_context_unref (loop->context);
3132 * @loop: a #GMainLoop
3134 * Runs a main loop until g_main_loop_quit() is called on the loop.
3135 * If this is called for the thread of the loop's #GMainContext,
3136 * it will process events from the loop, otherwise it will
3140 g_main_loop_run (GMainLoop *loop)
3142 GThread *self = G_THREAD_SELF;
3144 g_return_if_fail (loop != NULL);
3145 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3147 if (!g_main_context_acquire (loop->context))
3149 gboolean got_ownership = FALSE;
3151 /* Another thread owns this context */
3152 LOCK_CONTEXT (loop->context);
3154 g_atomic_int_inc (&loop->ref_count);
3156 if (!loop->is_running)
3157 loop->is_running = TRUE;
3159 while (loop->is_running && !got_ownership)
3160 got_ownership = g_main_context_wait (loop->context,
3161 &loop->context->cond,
3162 &loop->context->mutex);
3164 if (!loop->is_running)
3166 UNLOCK_CONTEXT (loop->context);
3168 g_main_context_release (loop->context);
3169 g_main_loop_unref (loop);
3173 g_assert (got_ownership);
3176 LOCK_CONTEXT (loop->context);
3178 if (loop->context->in_check_or_prepare)
3180 g_warning ("g_main_loop_run(): called recursively from within a source's "
3181 "check() or prepare() member, iteration not possible.");
3185 g_atomic_int_inc (&loop->ref_count);
3186 loop->is_running = TRUE;
3187 while (loop->is_running)
3188 g_main_context_iterate (loop->context, TRUE, TRUE, self);
3190 UNLOCK_CONTEXT (loop->context);
3192 g_main_context_release (loop->context);
3194 g_main_loop_unref (loop);
3199 * @loop: a #GMainLoop
3201 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3202 * for the loop will return.
3204 * Note that sources that have already been dispatched when
3205 * g_main_loop_quit() is called will still be executed.
3208 g_main_loop_quit (GMainLoop *loop)
3210 g_return_if_fail (loop != NULL);
3211 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3213 LOCK_CONTEXT (loop->context);
3214 loop->is_running = FALSE;
3215 g_wakeup_signal (loop->context->wakeup);
3217 g_cond_broadcast (&loop->context->cond);
3219 UNLOCK_CONTEXT (loop->context);
3223 * g_main_loop_is_running:
3224 * @loop: a #GMainLoop.
3226 * Checks to see if the main loop is currently being run via g_main_loop_run().
3228 * Return value: %TRUE if the mainloop is currently being run.
3231 g_main_loop_is_running (GMainLoop *loop)
3233 g_return_val_if_fail (loop != NULL, FALSE);
3234 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3236 return loop->is_running;
3240 * g_main_loop_get_context:
3241 * @loop: a #GMainLoop.
3243 * Returns the #GMainContext of @loop.
3245 * Return value: (transfer none): the #GMainContext of @loop
3248 g_main_loop_get_context (GMainLoop *loop)
3250 g_return_val_if_fail (loop != NULL, NULL);
3251 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3253 return loop->context;
3256 /* HOLDS: context's lock */
3258 g_main_context_poll (GMainContext *context,
3264 #ifdef G_MAIN_POLL_DEBUG
3270 GPollFunc poll_func;
3272 if (n_fds || timeout != 0)
3274 #ifdef G_MAIN_POLL_DEBUG
3275 if (_g_main_poll_debug)
3277 g_print ("polling context=%p n=%d timeout=%d\n",
3278 context, n_fds, timeout);
3279 poll_timer = g_timer_new ();
3283 LOCK_CONTEXT (context);
3285 poll_func = context->poll_func;
3287 UNLOCK_CONTEXT (context);
3288 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3291 g_warning ("poll(2) failed due to: %s.",
3292 g_strerror (errno));
3294 /* If g_poll () returns -1, it has already called g_warning() */
3298 #ifdef G_MAIN_POLL_DEBUG
3299 if (_g_main_poll_debug)
3301 LOCK_CONTEXT (context);
3303 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3306 g_timer_elapsed (poll_timer, NULL));
3307 g_timer_destroy (poll_timer);
3308 pollrec = context->poll_records;
3310 while (pollrec != NULL)
3315 if (fds[i].fd == pollrec->fd->fd &&
3316 pollrec->fd->events &&
3319 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3320 if (fds[i].revents & G_IO_IN)
3322 if (fds[i].revents & G_IO_OUT)
3324 if (fds[i].revents & G_IO_PRI)
3326 if (fds[i].revents & G_IO_ERR)
3328 if (fds[i].revents & G_IO_HUP)
3330 if (fds[i].revents & G_IO_NVAL)
3336 pollrec = pollrec->next;
3340 UNLOCK_CONTEXT (context);
3343 } /* if (n_fds || timeout != 0) */
3347 * g_main_context_add_poll:
3348 * @context: a #GMainContext (or %NULL for the default context)
3349 * @fd: a #GPollFD structure holding information about a file
3350 * descriptor to watch.
3351 * @priority: the priority for this file descriptor which should be
3352 * the same as the priority used for g_source_attach() to ensure that the
3353 * file descriptor is polled whenever the results may be needed.
3355 * Adds a file descriptor to the set of file descriptors polled for
3356 * this context. This will very seldom be used directly. Instead
3357 * a typical event source will use g_source_add_poll() instead.
3360 g_main_context_add_poll (GMainContext *context,
3365 context = g_main_context_default ();
3367 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3368 g_return_if_fail (fd);
3370 LOCK_CONTEXT (context);
3371 g_main_context_add_poll_unlocked (context, priority, fd);
3372 UNLOCK_CONTEXT (context);
3375 /* HOLDS: main_loop_lock */
3377 g_main_context_add_poll_unlocked (GMainContext *context,
3381 GPollRec *prevrec, *nextrec;
3382 GPollRec *newrec = g_slice_new (GPollRec);
3384 /* This file descriptor may be checked before we ever poll */
3387 newrec->priority = priority;
3389 prevrec = context->poll_records_tail;
3391 while (prevrec && priority < prevrec->priority)
3394 prevrec = prevrec->prev;
3398 prevrec->next = newrec;
3400 context->poll_records = newrec;
3402 newrec->prev = prevrec;
3403 newrec->next = nextrec;
3406 nextrec->prev = newrec;
3408 context->poll_records_tail = newrec;
3410 context->n_poll_records++;
3412 context->poll_changed = TRUE;
3414 /* Now wake up the main loop if it is waiting in the poll() */
3415 g_wakeup_signal (context->wakeup);
3419 * g_main_context_remove_poll:
3420 * @context:a #GMainContext
3421 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3423 * Removes file descriptor from the set of file descriptors to be
3424 * polled for a particular context.
3427 g_main_context_remove_poll (GMainContext *context,
3431 context = g_main_context_default ();
3433 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3434 g_return_if_fail (fd);
3436 LOCK_CONTEXT (context);
3437 g_main_context_remove_poll_unlocked (context, fd);
3438 UNLOCK_CONTEXT (context);
3442 g_main_context_remove_poll_unlocked (GMainContext *context,
3445 GPollRec *pollrec, *prevrec, *nextrec;
3448 pollrec = context->poll_records;
3452 nextrec = pollrec->next;
3453 if (pollrec->fd == fd)
3455 if (prevrec != NULL)
3456 prevrec->next = nextrec;
3458 context->poll_records = nextrec;
3460 if (nextrec != NULL)
3461 nextrec->prev = prevrec;
3463 context->poll_records_tail = prevrec;
3465 g_slice_free (GPollRec, pollrec);
3467 context->n_poll_records--;
3474 context->poll_changed = TRUE;
3476 /* Now wake up the main loop if it is waiting in the poll() */
3477 g_wakeup_signal (context->wakeup);
3481 * g_source_get_current_time:
3482 * @source: a #GSource
3483 * @timeval: #GTimeVal structure in which to store current time.
3485 * This function ignores @source and is otherwise the same as
3486 * g_get_current_time().
3488 * Deprecated: 2.28: use g_source_get_time() instead
3491 g_source_get_current_time (GSource *source,
3494 g_get_current_time (timeval);
3498 * g_source_get_time:
3499 * @source: a #GSource
3501 * Gets the time to be used when checking this source. The advantage of
3502 * calling this function over calling g_get_monotonic_time() directly is
3503 * that when checking multiple sources, GLib can cache a single value
3504 * instead of having to repeatedly get the system monotonic time.
3506 * The time here is the system monotonic time, if available, or some
3507 * other reasonable alternative otherwise. See g_get_monotonic_time().
3509 * Returns: the monotonic time in microseconds
3514 g_source_get_time (GSource *source)
3516 GMainContext *context;
3519 g_return_val_if_fail (source->context != NULL, 0);
3521 context = source->context;
3523 LOCK_CONTEXT (context);
3525 if (!context->time_is_fresh)
3527 context->time = g_get_monotonic_time ();
3528 context->time_is_fresh = TRUE;
3531 result = context->time;
3533 UNLOCK_CONTEXT (context);
3539 * g_main_context_set_poll_func:
3540 * @context: a #GMainContext
3541 * @func: the function to call to poll all file descriptors
3543 * Sets the function to use to handle polling of file descriptors. It
3544 * will be used instead of the poll() system call
3545 * (or GLib's replacement function, which is used where
3546 * poll() isn't available).
3548 * This function could possibly be used to integrate the GLib event
3549 * loop with an external event loop.
3552 g_main_context_set_poll_func (GMainContext *context,
3556 context = g_main_context_default ();
3558 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3560 LOCK_CONTEXT (context);
3563 context->poll_func = func;
3565 context->poll_func = g_poll;
3567 UNLOCK_CONTEXT (context);
3571 * g_main_context_get_poll_func:
3572 * @context: a #GMainContext
3574 * Gets the poll function set by g_main_context_set_poll_func().
3576 * Return value: the poll function
3579 g_main_context_get_poll_func (GMainContext *context)
3584 context = g_main_context_default ();
3586 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3588 LOCK_CONTEXT (context);
3589 result = context->poll_func;
3590 UNLOCK_CONTEXT (context);
3596 * g_main_context_wakeup:
3597 * @context: a #GMainContext
3599 * If @context is currently waiting in a poll(), interrupt
3600 * the poll(), and continue the iteration process.
3603 g_main_context_wakeup (GMainContext *context)
3606 context = g_main_context_default ();
3608 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3610 g_wakeup_signal (context->wakeup);
3614 * g_main_context_is_owner:
3615 * @context: a #GMainContext
3617 * Determines whether this thread holds the (recursive)
3618 * ownership of this #GMainContext. This is useful to
3619 * know before waiting on another thread that may be
3620 * blocking to get ownership of @context.
3622 * Returns: %TRUE if current thread is owner of @context.
3627 g_main_context_is_owner (GMainContext *context)
3632 context = g_main_context_default ();
3634 LOCK_CONTEXT (context);
3635 is_owner = context->owner == G_THREAD_SELF;
3636 UNLOCK_CONTEXT (context);
3644 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3645 gint64 current_time)
3647 timeout_source->expiration = current_time +
3648 (guint64) timeout_source->interval * 1000;
3650 if (timeout_source->seconds)
3653 static gint timer_perturb = -1;
3655 if (timer_perturb == -1)
3658 * we want a per machine/session unique 'random' value; try the dbus
3659 * address first, that has a UUID in it. If there is no dbus, use the
3660 * hostname for hashing.
3662 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3663 if (!session_bus_address)
3664 session_bus_address = g_getenv ("HOSTNAME");
3665 if (session_bus_address)
3666 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
3671 /* We want the microseconds part of the timeout to land on the
3672 * 'timer_perturb' mark, but we need to make sure we don't try to
3673 * set the timeout in the past. We do this by ensuring that we
3674 * always only *increase* the expiration time by adding a full
3675 * second in the case that the microsecond portion decreases.
3677 timeout_source->expiration -= timer_perturb;
3679 remainder = timeout_source->expiration % 1000000;
3680 if (remainder >= 1000000/4)
3681 timeout_source->expiration += 1000000;
3683 timeout_source->expiration -= remainder;
3684 timeout_source->expiration += timer_perturb;
3689 g_timeout_prepare (GSource *source,
3692 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3693 gint64 now = g_source_get_time (source);
3695 if (now < timeout_source->expiration)
3697 /* Round up to ensure that we don't try again too early */
3698 *timeout = (timeout_source->expiration - now + 999) / 1000;
3707 g_timeout_check (GSource *source)
3709 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3710 gint64 now = g_source_get_time (source);
3712 return timeout_source->expiration <= now;
3716 g_timeout_dispatch (GSource *source,
3717 GSourceFunc callback,
3720 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3725 g_warning ("Timeout source dispatched without callback\n"
3726 "You must call g_source_set_callback().");
3730 again = callback (user_data);
3733 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
3739 * g_timeout_source_new:
3740 * @interval: the timeout interval in milliseconds.
3742 * Creates a new timeout source.
3744 * The source will not initially be associated with any #GMainContext
3745 * and must be added to one with g_source_attach() before it will be
3748 * The interval given is in terms of monotonic time, not wall clock
3749 * time. See g_get_monotonic_time().
3751 * Return value: the newly-created timeout source
3754 g_timeout_source_new (guint interval)
3756 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3757 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3759 timeout_source->interval = interval;
3760 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3766 * g_timeout_source_new_seconds:
3767 * @interval: the timeout interval in seconds
3769 * Creates a new timeout source.
3771 * The source will not initially be associated with any #GMainContext
3772 * and must be added to one with g_source_attach() before it will be
3775 * The scheduling granularity/accuracy of this timeout source will be
3778 * The interval given in terms of monotonic time, not wall clock time.
3779 * See g_get_monotonic_time().
3781 * Return value: the newly-created timeout source
3786 g_timeout_source_new_seconds (guint interval)
3788 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3789 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3791 timeout_source->interval = 1000 * interval;
3792 timeout_source->seconds = TRUE;
3794 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3801 * g_timeout_add_full:
3802 * @priority: the priority of the timeout source. Typically this will be in
3803 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3804 * @interval: the time between calls to the function, in milliseconds
3805 * (1/1000ths of a second)
3806 * @function: function to call
3807 * @data: data to pass to @function
3808 * @notify: function to call when the timeout is removed, or %NULL
3810 * Sets a function to be called at regular intervals, with the given
3811 * priority. The function is called repeatedly until it returns
3812 * %FALSE, at which point the timeout is automatically destroyed and
3813 * the function will not be called again. The @notify function is
3814 * called when the timeout is destroyed. The first call to the
3815 * function will be at the end of the first @interval.
3817 * Note that timeout functions may be delayed, due to the processing of other
3818 * event sources. Thus they should not be relied on for precise timing.
3819 * After each call to the timeout function, the time of the next
3820 * timeout is recalculated based on the current time and the given interval
3821 * (it does not try to 'catch up' time lost in delays).
3823 * This internally creates a main loop source using g_timeout_source_new()
3824 * and attaches it to the main loop context using g_source_attach(). You can
3825 * do these steps manually if you need greater control.
3827 * The interval given in terms of monotonic time, not wall clock time.
3828 * See g_get_monotonic_time().
3830 * Return value: the ID (greater than 0) of the event source.
3831 * Rename to: g_timeout_add
3834 g_timeout_add_full (gint priority,
3836 GSourceFunc function,
3838 GDestroyNotify notify)
3843 g_return_val_if_fail (function != NULL, 0);
3845 source = g_timeout_source_new (interval);
3847 if (priority != G_PRIORITY_DEFAULT)
3848 g_source_set_priority (source, priority);
3850 g_source_set_callback (source, function, data, notify);
3851 id = g_source_attach (source, NULL);
3852 g_source_unref (source);
3859 * @interval: the time between calls to the function, in milliseconds
3860 * (1/1000ths of a second)
3861 * @function: function to call
3862 * @data: data to pass to @function
3864 * Sets a function to be called at regular intervals, with the default
3865 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
3866 * until it returns %FALSE, at which point the timeout is automatically
3867 * destroyed and the function will not be called again. The first call
3868 * to the function will be at the end of the first @interval.
3870 * Note that timeout functions may be delayed, due to the processing of other
3871 * event sources. Thus they should not be relied on for precise timing.
3872 * After each call to the timeout function, the time of the next
3873 * timeout is recalculated based on the current time and the given interval
3874 * (it does not try to 'catch up' time lost in delays).
3876 * If you want to have a timer in the "seconds" range and do not care
3877 * about the exact time of the first call of the timer, use the
3878 * g_timeout_add_seconds() function; this function allows for more
3879 * optimizations and more efficient system power usage.
3881 * This internally creates a main loop source using g_timeout_source_new()
3882 * and attaches it to the main loop context using g_source_attach(). You can
3883 * do these steps manually if you need greater control.
3885 * The interval given is in terms of monotonic time, not wall clock
3886 * time. See g_get_monotonic_time().
3888 * Return value: the ID (greater than 0) of the event source.
3891 g_timeout_add (guint32 interval,
3892 GSourceFunc function,
3895 return g_timeout_add_full (G_PRIORITY_DEFAULT,
3896 interval, function, data, NULL);
3900 * g_timeout_add_seconds_full:
3901 * @priority: the priority of the timeout source. Typically this will be in
3902 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3903 * @interval: the time between calls to the function, in seconds
3904 * @function: function to call
3905 * @data: data to pass to @function
3906 * @notify: function to call when the timeout is removed, or %NULL
3908 * Sets a function to be called at regular intervals, with @priority.
3909 * The function is called repeatedly until it returns %FALSE, at which
3910 * point the timeout is automatically destroyed and the function will
3911 * not be called again.
3913 * Unlike g_timeout_add(), this function operates at whole second granularity.
3914 * The initial starting point of the timer is determined by the implementation
3915 * and the implementation is expected to group multiple timers together so that
3916 * they fire all at the same time.
3917 * To allow this grouping, the @interval to the first timer is rounded
3918 * and can deviate up to one second from the specified interval.
3919 * Subsequent timer iterations will generally run at the specified interval.
3921 * Note that timeout functions may be delayed, due to the processing of other
3922 * event sources. Thus they should not be relied on for precise timing.
3923 * After each call to the timeout function, the time of the next
3924 * timeout is recalculated based on the current time and the given @interval
3926 * If you want timing more precise than whole seconds, use g_timeout_add()
3929 * The grouping of timers to fire at the same time results in a more power
3930 * and CPU efficient behavior so if your timer is in multiples of seconds
3931 * and you don't require the first timer exactly one second from now, the
3932 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
3934 * This internally creates a main loop source using
3935 * g_timeout_source_new_seconds() and attaches it to the main loop context
3936 * using g_source_attach(). You can do these steps manually if you need
3939 * The interval given is in terms of monotonic time, not wall clock
3940 * time. See g_get_monotonic_time().
3942 * Return value: the ID (greater than 0) of the event source.
3944 * Rename to: g_timeout_add_seconds
3948 g_timeout_add_seconds_full (gint priority,
3950 GSourceFunc function,
3952 GDestroyNotify notify)
3957 g_return_val_if_fail (function != NULL, 0);
3959 source = g_timeout_source_new_seconds (interval);
3961 if (priority != G_PRIORITY_DEFAULT)
3962 g_source_set_priority (source, priority);
3964 g_source_set_callback (source, function, data, notify);
3965 id = g_source_attach (source, NULL);
3966 g_source_unref (source);
3972 * g_timeout_add_seconds:
3973 * @interval: the time between calls to the function, in seconds
3974 * @function: function to call
3975 * @data: data to pass to @function
3977 * Sets a function to be called at regular intervals with the default
3978 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
3979 * it returns %FALSE, at which point the timeout is automatically destroyed
3980 * and the function will not be called again.
3982 * This internally creates a main loop source using
3983 * g_timeout_source_new_seconds() and attaches it to the main loop context
3984 * using g_source_attach(). You can do these steps manually if you need
3985 * greater control. Also see g_timeout_add_seconds_full().
3987 * Note that the first call of the timer may not be precise for timeouts
3988 * of one second. If you need finer precision and have such a timeout,
3989 * you may want to use g_timeout_add() instead.
3991 * The interval given is in terms of monotonic time, not wall clock
3992 * time. See g_get_monotonic_time().
3994 * Return value: the ID (greater than 0) of the event source.
3999 g_timeout_add_seconds (guint interval,
4000 GSourceFunc function,
4003 g_return_val_if_fail (function != NULL, 0);
4005 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4008 /* Child watch functions */
4013 g_child_watch_prepare (GSource *source,
4021 g_child_watch_check (GSource *source)
4023 GChildWatchSource *child_watch_source;
4024 gboolean child_exited;
4026 child_watch_source = (GChildWatchSource *) source;
4028 child_exited = child_watch_source->poll.revents & G_IO_IN;
4035 * Note: We do _not_ check for the special value of STILL_ACTIVE
4036 * since we know that the process has exited and doing so runs into
4037 * problems if the child process "happens to return STILL_ACTIVE(259)"
4038 * as Microsoft's Platform SDK puts it.
4040 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4042 gchar *emsg = g_win32_error_message (GetLastError ());
4043 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4046 child_watch_source->child_status = -1;
4049 child_watch_source->child_status = child_status;
4052 return child_exited;
4056 g_child_watch_finalize (GSource *source)
4060 #else /* G_OS_WIN32 */
4063 wake_source (GSource *source)
4065 GMainContext *context;
4067 /* This should be thread-safe:
4069 * - if the source is currently being added to a context, that
4070 * context will be woken up anyway
4072 * - if the source is currently being destroyed, we simply need not
4075 * - the memory for the source will remain valid until after the
4076 * source finalize function was called (which would remove the
4077 * source from the global list which we are currently holding the
4080 * - the GMainContext will either be NULL or point to a live
4083 * - the GMainContext will remain valid since we hold the
4084 * main_context_list lock
4086 * Since we are holding a lot of locks here, don't try to enter any
4087 * more GMainContext functions for fear of dealock -- just hit the
4088 * GWakeup and run. Even if that's safe now, it could easily become
4089 * unsafe with some very minor changes in the future, and signal
4090 * handling is not the most well-tested codepath.
4092 G_LOCK(main_context_list);
4093 context = source->context;
4095 g_wakeup_signal (context->wakeup);
4096 G_UNLOCK(main_context_list);
4100 dispatch_unix_signals (void)
4104 /* clear this first incase another one arrives while we're processing */
4105 any_unix_signal_pending = FALSE;
4107 G_LOCK(unix_signal_lock);
4109 /* handle GChildWatchSource instances */
4110 if (unix_signal_pending[SIGCHLD])
4112 unix_signal_pending[SIGCHLD] = FALSE;
4114 /* The only way we can do this is to scan all of the children.
4116 * The docs promise that we will not reap children that we are not
4117 * explicitly watching, so that ties our hands from calling
4118 * waitpid(-1). We also can't use siginfo's si_pid field since if
4119 * multiple SIGCHLD arrive at the same time, one of them can be
4120 * dropped (since a given UNIX signal can only be pending once).
4122 for (node = unix_child_watches; node; node = node->next)
4124 GChildWatchSource *source = node->data;
4126 if (!source->child_exited)
4128 if (waitpid (source->pid, &source->child_status, WNOHANG) > 0)
4130 source->child_exited = TRUE;
4132 wake_source ((GSource *) source);
4138 /* handle GUnixSignalWatchSource instances */
4139 for (node = unix_signal_watches; node; node = node->next)
4141 GUnixSignalWatchSource *source = node->data;
4143 if (!source->pending)
4145 if (unix_signal_pending[source->signum])
4147 unix_signal_pending[source->signum] = FALSE;
4148 source->pending = TRUE;
4150 wake_source ((GSource *) source);
4155 G_UNLOCK(unix_signal_lock);
4159 g_child_watch_prepare (GSource *source,
4162 GChildWatchSource *child_watch_source;
4164 child_watch_source = (GChildWatchSource *) source;
4166 return child_watch_source->child_exited;
4170 g_child_watch_check (GSource *source)
4172 GChildWatchSource *child_watch_source;
4174 child_watch_source = (GChildWatchSource *) source;
4176 return child_watch_source->child_exited;
4180 g_unix_signal_watch_prepare (GSource *source,
4183 GUnixSignalWatchSource *unix_signal_source;
4185 unix_signal_source = (GUnixSignalWatchSource *) source;
4187 return unix_signal_source->pending;
4191 g_unix_signal_watch_check (GSource *source)
4193 GUnixSignalWatchSource *unix_signal_source;
4195 unix_signal_source = (GUnixSignalWatchSource *) source;
4197 return unix_signal_source->pending;
4201 g_unix_signal_watch_dispatch (GSource *source,
4202 GSourceFunc callback,
4205 GUnixSignalWatchSource *unix_signal_source;
4207 unix_signal_source = (GUnixSignalWatchSource *) source;
4211 g_warning ("Unix signal source dispatched without callback\n"
4212 "You must call g_source_set_callback().");
4216 (callback) (user_data);
4218 unix_signal_source->pending = FALSE;
4224 ensure_unix_signal_handler_installed_unlocked (int signum)
4226 static sigset_t installed_signal_mask;
4227 static gboolean initialized;
4228 struct sigaction action;
4232 sigemptyset (&installed_signal_mask);
4233 g_get_worker_context ();
4237 if (sigismember (&installed_signal_mask, signum))
4240 sigaddset (&installed_signal_mask, signum);
4242 action.sa_handler = g_unix_signal_handler;
4243 sigemptyset (&action.sa_mask);
4244 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4245 sigaction (signum, &action, NULL);
4249 _g_main_create_unix_signal_watch (int signum)
4252 GUnixSignalWatchSource *unix_signal_source;
4254 source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
4255 unix_signal_source = (GUnixSignalWatchSource *) source;
4257 unix_signal_source->signum = signum;
4258 unix_signal_source->pending = FALSE;
4260 G_LOCK (unix_signal_lock);
4261 ensure_unix_signal_handler_installed_unlocked (signum);
4262 unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
4263 if (unix_signal_pending[signum])
4264 unix_signal_source->pending = TRUE;
4265 unix_signal_pending[signum] = FALSE;
4266 G_UNLOCK (unix_signal_lock);
4272 g_unix_signal_watch_finalize (GSource *source)
4274 G_LOCK (unix_signal_lock);
4275 unix_signal_watches = g_slist_remove (unix_signal_watches, source);
4276 G_UNLOCK (unix_signal_lock);
4280 g_child_watch_finalize (GSource *source)
4282 G_LOCK (unix_signal_lock);
4283 unix_child_watches = g_slist_remove (unix_child_watches, source);
4284 G_UNLOCK (unix_signal_lock);
4287 #endif /* G_OS_WIN32 */
4290 g_child_watch_dispatch (GSource *source,
4291 GSourceFunc callback,
4294 GChildWatchSource *child_watch_source;
4295 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
4297 child_watch_source = (GChildWatchSource *) source;
4301 g_warning ("Child watch source dispatched without callback\n"
4302 "You must call g_source_set_callback().");
4306 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
4308 /* We never keep a child watch source around as the child is gone */
4315 g_unix_signal_handler (int signum)
4317 unix_signal_pending[signum] = TRUE;
4318 any_unix_signal_pending = TRUE;
4320 g_wakeup_signal (glib_worker_context->wakeup);
4323 #endif /* !G_OS_WIN32 */
4326 * g_child_watch_source_new:
4327 * @pid: process to watch. On POSIX the pid of a child process. On
4328 * Windows a handle for a process (which doesn't have to be a child).
4330 * Creates a new child_watch source.
4332 * The source will not initially be associated with any #GMainContext
4333 * and must be added to one with g_source_attach() before it will be
4336 * Note that child watch sources can only be used in conjunction with
4337 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4340 * Note that on platforms where #GPid must be explicitly closed
4341 * (see g_spawn_close_pid()) @pid must not be closed while the
4342 * source is still active. Typically, you will want to call
4343 * g_spawn_close_pid() in the callback function for the source.
4345 * Note further that using g_child_watch_source_new() is not
4346 * compatible with calling <literal>waitpid(-1)</literal> in
4347 * the application. Calling waitpid() for individual pids will
4350 * Return value: the newly-created child watch source
4355 g_child_watch_source_new (GPid pid)
4357 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4358 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4360 child_watch_source->pid = pid;
4363 child_watch_source->poll.fd = (gintptr) pid;
4364 child_watch_source->poll.events = G_IO_IN;
4366 g_source_add_poll (source, &child_watch_source->poll);
4367 #else /* G_OS_WIN32 */
4368 G_LOCK (unix_signal_lock);
4369 ensure_unix_signal_handler_installed_unlocked (SIGCHLD);
4370 unix_child_watches = g_slist_prepend (unix_child_watches, child_watch_source);
4371 if (waitpid (pid, &child_watch_source->child_status, WNOHANG) > 0)
4372 child_watch_source->child_exited = TRUE;
4373 G_UNLOCK (unix_signal_lock);
4374 #endif /* G_OS_WIN32 */
4380 * g_child_watch_add_full:
4381 * @priority: the priority of the idle source. Typically this will be in the
4382 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4383 * @pid: process to watch. On POSIX the pid of a child process. On
4384 * Windows a handle for a process (which doesn't have to be a child).
4385 * @function: function to call
4386 * @data: data to pass to @function
4387 * @notify: function to call when the idle is removed, or %NULL
4389 * Sets a function to be called when the child indicated by @pid
4390 * exits, at the priority @priority.
4392 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4393 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4394 * the spawn function for the child watching to work.
4396 * Note that on platforms where #GPid must be explicitly closed
4397 * (see g_spawn_close_pid()) @pid must not be closed while the
4398 * source is still active. Typically, you will want to call
4399 * g_spawn_close_pid() in the callback function for the source.
4401 * GLib supports only a single callback per process id.
4403 * This internally creates a main loop source using
4404 * g_child_watch_source_new() and attaches it to the main loop context
4405 * using g_source_attach(). You can do these steps manually if you
4406 * need greater control.
4408 * Return value: the ID (greater than 0) of the event source.
4410 * Rename to: g_child_watch_add
4414 g_child_watch_add_full (gint priority,
4416 GChildWatchFunc function,
4418 GDestroyNotify notify)
4423 g_return_val_if_fail (function != NULL, 0);
4425 source = g_child_watch_source_new (pid);
4427 if (priority != G_PRIORITY_DEFAULT)
4428 g_source_set_priority (source, priority);
4430 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4431 id = g_source_attach (source, NULL);
4432 g_source_unref (source);
4438 * g_child_watch_add:
4439 * @pid: process id to watch. On POSIX the pid of a child process. On
4440 * Windows a handle for a process (which doesn't have to be a child).
4441 * @function: function to call
4442 * @data: data to pass to @function
4444 * Sets a function to be called when the child indicated by @pid
4445 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4447 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4448 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4449 * the spawn function for the child watching to work.
4451 * Note that on platforms where #GPid must be explicitly closed
4452 * (see g_spawn_close_pid()) @pid must not be closed while the
4453 * source is still active. Typically, you will want to call
4454 * g_spawn_close_pid() in the callback function for the source.
4456 * GLib supports only a single callback per process id.
4458 * This internally creates a main loop source using
4459 * g_child_watch_source_new() and attaches it to the main loop context
4460 * using g_source_attach(). You can do these steps manually if you
4461 * need greater control.
4463 * Return value: the ID (greater than 0) of the event source.
4468 g_child_watch_add (GPid pid,
4469 GChildWatchFunc function,
4472 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4476 /* Idle functions */
4479 g_idle_prepare (GSource *source,
4488 g_idle_check (GSource *source)
4494 g_idle_dispatch (GSource *source,
4495 GSourceFunc callback,
4500 g_warning ("Idle source dispatched without callback\n"
4501 "You must call g_source_set_callback().");
4505 return callback (user_data);
4509 * g_idle_source_new:
4511 * Creates a new idle source.
4513 * The source will not initially be associated with any #GMainContext
4514 * and must be added to one with g_source_attach() before it will be
4515 * executed. Note that the default priority for idle sources is
4516 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4517 * have a default priority of %G_PRIORITY_DEFAULT.
4519 * Return value: the newly-created idle source
4522 g_idle_source_new (void)
4526 source = g_source_new (&g_idle_funcs, sizeof (GSource));
4527 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4534 * @priority: the priority of the idle source. Typically this will be in the
4535 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4536 * @function: function to call
4537 * @data: data to pass to @function
4538 * @notify: function to call when the idle is removed, or %NULL
4540 * Adds a function to be called whenever there are no higher priority
4541 * events pending. If the function returns %FALSE it is automatically
4542 * removed from the list of event sources and will not be called again.
4544 * This internally creates a main loop source using g_idle_source_new()
4545 * and attaches it to the main loop context using g_source_attach().
4546 * You can do these steps manually if you need greater control.
4548 * Return value: the ID (greater than 0) of the event source.
4549 * Rename to: g_idle_add
4552 g_idle_add_full (gint priority,
4553 GSourceFunc function,
4555 GDestroyNotify notify)
4560 g_return_val_if_fail (function != NULL, 0);
4562 source = g_idle_source_new ();
4564 if (priority != G_PRIORITY_DEFAULT_IDLE)
4565 g_source_set_priority (source, priority);
4567 g_source_set_callback (source, function, data, notify);
4568 id = g_source_attach (source, NULL);
4569 g_source_unref (source);
4576 * @function: function to call
4577 * @data: data to pass to @function.
4579 * Adds a function to be called whenever there are no higher priority
4580 * events pending to the default main loop. The function is given the
4581 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4582 * returns %FALSE it is automatically removed from the list of event
4583 * sources and will not be called again.
4585 * This internally creates a main loop source using g_idle_source_new()
4586 * and attaches it to the main loop context using g_source_attach().
4587 * You can do these steps manually if you need greater control.
4589 * Return value: the ID (greater than 0) of the event source.
4592 g_idle_add (GSourceFunc function,
4595 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4599 * g_idle_remove_by_data:
4600 * @data: the data for the idle source's callback.
4602 * Removes the idle function with the given data.
4604 * Return value: %TRUE if an idle source was found and removed.
4607 g_idle_remove_by_data (gpointer data)
4609 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4613 * g_main_context_invoke:
4614 * @context: (allow-none): a #GMainContext, or %NULL
4615 * @function: function to call
4616 * @data: data to pass to @function
4618 * Invokes a function in such a way that @context is owned during the
4619 * invocation of @function.
4621 * If @context is %NULL then the global default main context — as
4622 * returned by g_main_context_default() — is used.
4624 * If @context is owned by the current thread, @function is called
4625 * directly. Otherwise, if @context is the thread-default main context
4626 * of the current thread and g_main_context_acquire() succeeds, then
4627 * @function is called and g_main_context_release() is called
4630 * In any other case, an idle source is created to call @function and
4631 * that source is attached to @context (presumably to be run in another
4632 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
4633 * priority. If you want a different priority, use
4634 * g_main_context_invoke_full().
4636 * Note that, as with normal idle functions, @function should probably
4637 * return %FALSE. If it returns %TRUE, it will be continuously run in a
4638 * loop (and may prevent this call from returning).
4643 g_main_context_invoke (GMainContext *context,
4644 GSourceFunc function,
4647 g_main_context_invoke_full (context,
4649 function, data, NULL);
4653 * g_main_context_invoke_full:
4654 * @context: (allow-none): a #GMainContext, or %NULL
4655 * @priority: the priority at which to run @function
4656 * @function: function to call
4657 * @data: data to pass to @function
4658 * @notify: a function to call when @data is no longer in use, or %NULL.
4660 * Invokes a function in such a way that @context is owned during the
4661 * invocation of @function.
4663 * This function is the same as g_main_context_invoke() except that it
4664 * lets you specify the priority incase @function ends up being
4665 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
4667 * @notify should not assume that it is called from any particular
4668 * thread or with any particular context acquired.
4673 g_main_context_invoke_full (GMainContext *context,
4675 GSourceFunc function,
4677 GDestroyNotify notify)
4679 g_return_if_fail (function != NULL);
4682 context = g_main_context_default ();
4684 if (g_main_context_is_owner (context))
4686 while (function (data));
4693 GMainContext *thread_default;
4695 thread_default = g_main_context_get_thread_default ();
4697 if (!thread_default)
4698 thread_default = g_main_context_default ();
4700 if (thread_default == context && g_main_context_acquire (context))
4702 while (function (data));
4704 g_main_context_release (context);
4713 source = g_idle_source_new ();
4714 g_source_set_priority (source, priority);
4715 g_source_set_callback (source, function, data, notify);
4716 g_source_attach (source, context);
4717 g_source_unref (source);
4723 glib_worker_main (gpointer data)
4727 g_main_context_iteration (glib_worker_context, TRUE);
4730 if (any_unix_signal_pending)
4731 dispatch_unix_signals ();
4735 return NULL; /* worst GCC warning message ever... */
4739 g_get_worker_context (void)
4741 static gsize initialised;
4743 if (g_once_init_enter (&initialised))
4745 GError *error = NULL;
4747 glib_worker_context = g_main_context_new ();
4748 if (g_thread_new ("gmain", glib_worker_main, NULL, FALSE, &error) == NULL)
4749 g_error ("Creating GLib worker thread failed: %s\n", error->message);
4751 g_once_init_leave (&initialised, TRUE);
4754 return glib_worker_context;