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 /* for pipe2; need to define it first to avoid
36 * other headers pulling in unistd.h
38 /* The meaning of_GNU_SOURCE that is intended here is present only on
39 * Linux; avoid the possibility that some misguided header in MinGW
40 * looks at it. Ideally we should define _GNU_SOURCE only on platforms
41 * where we know what it means and that is what we want here
42 * (i.e. Linux with glibc). After all, there might be some other POSIX
43 * platform even where _GNU_SOURCE is used for some unrelated change
44 * in semantics that isn't wanted. Sigh.
50 #include "glibconfig.h"
52 /* Uncomment the next line (and the corresponding line in gpoll.c) to
53 * enable debugging printouts if the environment variable
54 * G_MAIN_POLL_DEBUG is set to some value.
56 /* #define G_MAIN_POLL_DEBUG */
59 /* Always enable debugging printout on Windows, as it is more often
62 #define G_MAIN_POLL_DEBUG
66 #include <sys/types.h>
69 #ifdef HAVE_SYS_TIME_H
71 #endif /* HAVE_SYS_TIME_H */
74 #endif /* HAVE_UNISTD_H */
80 #endif /* G_OS_WIN32 */
83 #include <sys/socket.h>
85 #endif /* G_OS_BEOS */
95 #include "giochannel.h"
99 #include "gstrfuncs.h"
100 #include "gtestutils.h"
101 #include "gthreadprivate.h"
107 #ifdef G_MAIN_POLL_DEBUG
113 * @title: The Main Event Loop
114 * @short_description: manages all available sources of events
116 * The main event loop manages all the available sources of events for
117 * GLib and GTK+ applications. These events can come from any number of
118 * different types of sources such as file descriptors (plain files,
119 * pipes or sockets) and timeouts. New types of event sources can also
120 * be added using g_source_attach().
122 * To allow multiple independent sets of sources to be handled in
123 * different threads, each source is associated with a #GMainContext.
124 * A GMainContext can only be running in a single thread, but
125 * sources can be added to it and removed from it from other threads.
127 * Each event source is assigned a priority. The default priority,
128 * #G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
129 * Values greater than 0 denote lower priorities. Events from high priority
130 * sources are always processed before events from lower priority sources.
132 * Idle functions can also be added, and assigned a priority. These will
133 * be run whenever no events with a higher priority are ready to be processed.
135 * The #GMainLoop data type represents a main event loop. A GMainLoop is
136 * created with g_main_loop_new(). After adding the initial event sources,
137 * g_main_loop_run() is called. This continuously checks for new events from
138 * each of the event sources and dispatches them. Finally, the processing of
139 * an event from one of the sources leads to a call to g_main_loop_quit() to
140 * exit the main loop, and g_main_loop_run() returns.
142 * It is possible to create new instances of #GMainLoop recursively.
143 * This is often used in GTK+ applications when showing modal dialog
144 * boxes. Note that event sources are associated with a particular
145 * #GMainContext, and will be checked and dispatched for all main
146 * loops associated with that GMainContext.
148 * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
149 * gtk_main_quit() and gtk_events_pending().
151 * <refsect2><title>Creating new source types</title>
152 * <para>One of the unusual features of the #GMainLoop functionality
153 * is that new types of event source can be created and used in
154 * addition to the builtin type of event source. A new event source
155 * type is used for handling GDK events. A new source type is created
156 * by <firstterm>deriving</firstterm> from the #GSource structure.
157 * The derived type of source is represented by a structure that has
158 * the #GSource structure as a first element, and other elements specific
159 * to the new source type. To create an instance of the new source type,
160 * call g_source_new() passing in the size of the derived structure and
161 * a table of functions. These #GSourceFuncs determine the behavior of
162 * the new source type.</para>
163 * <para>New source types basically interact with the main context
164 * in two ways. Their prepare function in #GSourceFuncs can set a timeout
165 * to determine the maximum amount of time that the main loop will sleep
166 * before checking the source again. In addition, or as well, the source
167 * can add file descriptors to the set that the main context checks using
168 * g_source_add_poll().</para>
170 * <refsect2><title>Customizing the main loop iteration</title>
171 * <para>Single iterations of a #GMainContext can be run with
172 * g_main_context_iteration(). In some cases, more detailed control
173 * of exactly how the details of the main loop work is desired, for
174 * instance, when integrating the #GMainLoop with an external main loop.
175 * In such cases, you can call the component functions of
176 * g_main_context_iteration() directly. These functions are
177 * g_main_context_prepare(), g_main_context_query(),
178 * g_main_context_check() and g_main_context_dispatch().</para>
179 * <para>The operation of these functions can best be seen in terms
180 * of a state diagram, as shown in <xref linkend="mainloop-states"/>.</para>
181 * <figure id="mainloop-states"><title>States of a Main Context</title>
182 * <graphic fileref="mainloop-states.gif" format="GIF"></graphic>
189 typedef struct _GTimeoutSource GTimeoutSource;
190 typedef struct _GChildWatchSource GChildWatchSource;
191 typedef struct _GPollRec GPollRec;
192 typedef struct _GSourceCallback GSourceCallback;
196 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
197 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
200 #ifdef G_THREADS_ENABLED
201 typedef struct _GMainWaiter GMainWaiter;
210 typedef struct _GMainDispatch GMainDispatch;
212 struct _GMainDispatch
215 GSList *dispatching_sources; /* stack of current sources */
218 #ifdef G_MAIN_POLL_DEBUG
219 gboolean _g_main_poll_debug = FALSE;
224 #ifdef G_THREADS_ENABLED
225 /* The following lock is used for both the list of sources
226 * and the list of poll records
237 GPtrArray *pending_dispatches;
238 gint timeout; /* Timeout for current iteration */
241 GSource *source_list;
242 gint in_check_or_prepare;
244 GPollRec *poll_records;
245 guint n_poll_records;
246 GPollFD *cached_poll_array;
247 guint cached_poll_array_size;
249 #ifdef G_THREADS_ENABLED
251 /* this pipe is used to wake up the main loop when a source is added.
253 gint wake_up_pipe[2];
254 #else /* G_OS_WIN32 */
255 HANDLE wake_up_semaphore;
256 #endif /* G_OS_WIN32 */
259 gboolean poll_waiting;
261 /* Flag indicating whether the set of fd's changed during a poll */
262 gboolean poll_changed;
263 #endif /* G_THREADS_ENABLED */
268 gboolean time_is_fresh;
269 GTimeVal current_time;
270 gboolean current_time_is_fresh;
273 struct _GSourceCallback
278 GDestroyNotify notify;
283 GMainContext *context;
288 struct _GTimeoutSource
291 GTimeSpec expiration;
296 struct _GChildWatchSource
303 #else /* G_OS_WIN32 */
305 gboolean child_exited;
306 #endif /* G_OS_WIN32 */
316 #ifdef G_THREADS_ENABLED
317 #define LOCK_CONTEXT(context) g_static_mutex_lock (&context->mutex)
318 #define UNLOCK_CONTEXT(context) g_static_mutex_unlock (&context->mutex)
319 #define G_THREAD_SELF g_thread_self ()
321 #define LOCK_CONTEXT(context) (void)0
322 #define UNLOCK_CONTEXT(context) (void)0
323 #define G_THREAD_SELF NULL
326 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
327 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
328 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
330 #define SOURCE_UNREF(source, context) \
332 if ((source)->ref_count > 1) \
333 (source)->ref_count--; \
335 g_source_unref_internal ((source), (context), TRUE); \
339 /* Forward declarations */
341 static void g_source_unref_internal (GSource *source,
342 GMainContext *context,
344 static void g_source_destroy_internal (GSource *source,
345 GMainContext *context,
347 static void g_main_context_poll (GMainContext *context,
352 static void g_main_context_add_poll_unlocked (GMainContext *context,
355 static void g_main_context_remove_poll_unlocked (GMainContext *context,
357 static void g_main_context_wakeup_unlocked (GMainContext *context);
359 static gboolean g_timeout_prepare (GSource *source,
361 static gboolean g_timeout_check (GSource *source);
362 static gboolean g_timeout_dispatch (GSource *source,
363 GSourceFunc callback,
365 static gboolean g_child_watch_prepare (GSource *source,
367 static gboolean g_child_watch_check (GSource *source);
368 static gboolean g_child_watch_dispatch (GSource *source,
369 GSourceFunc callback,
371 static gboolean g_idle_prepare (GSource *source,
373 static gboolean g_idle_check (GSource *source);
374 static gboolean g_idle_dispatch (GSource *source,
375 GSourceFunc callback,
378 G_LOCK_DEFINE_STATIC (main_loop);
379 static GMainContext *default_main_context;
380 static GSList *main_contexts_without_pipe = NULL;
383 /* Child status monitoring code */
385 CHILD_WATCH_UNINITIALIZED,
386 CHILD_WATCH_INITIALIZED_SINGLE,
387 CHILD_WATCH_INITIALIZED_THREADED
389 static gint child_watch_init_state = CHILD_WATCH_UNINITIALIZED;
390 static gint child_watch_count = 1;
391 static gint child_watch_wake_up_pipe[2] = {0, 0};
392 #endif /* !G_OS_WIN32 */
393 G_LOCK_DEFINE_STATIC (main_context_list);
394 static GSList *main_context_list = NULL;
396 static gint timer_perturb = -1;
398 GSourceFuncs g_timeout_funcs =
406 GSourceFuncs g_child_watch_funcs =
408 g_child_watch_prepare,
410 g_child_watch_dispatch,
414 GSourceFuncs g_idle_funcs =
423 * g_main_context_ref:
424 * @context: a #GMainContext
426 * Increases the reference count on a #GMainContext object by one.
428 * Returns: the @context that was passed in (since 2.6)
431 g_main_context_ref (GMainContext *context)
433 g_return_val_if_fail (context != NULL, NULL);
434 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
436 g_atomic_int_inc (&context->ref_count);
442 poll_rec_list_free (GMainContext *context,
445 g_slice_free_chain (GPollRec, list, next);
449 * g_main_context_unref:
450 * @context: a #GMainContext
452 * Decreases the reference count on a #GMainContext object by one. If
453 * the result is zero, free the context and free all associated memory.
456 g_main_context_unref (GMainContext *context)
459 g_return_if_fail (context != NULL);
460 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
462 if (!g_atomic_int_dec_and_test (&context->ref_count))
465 G_LOCK (main_context_list);
466 main_context_list = g_slist_remove (main_context_list, context);
467 G_UNLOCK (main_context_list);
469 source = context->source_list;
472 GSource *next = source->next;
473 g_source_destroy_internal (source, context, FALSE);
477 #ifdef G_THREADS_ENABLED
478 g_static_mutex_free (&context->mutex);
481 g_ptr_array_free (context->pending_dispatches, TRUE);
482 g_free (context->cached_poll_array);
484 poll_rec_list_free (context, context->poll_records);
486 #ifdef G_THREADS_ENABLED
487 if (g_thread_supported())
490 close (context->wake_up_pipe[0]);
491 close (context->wake_up_pipe[1]);
493 CloseHandle (context->wake_up_semaphore);
497 main_contexts_without_pipe = g_slist_remove (main_contexts_without_pipe,
500 if (context->cond != NULL)
501 g_cond_free (context->cond);
507 #ifdef G_THREADS_ENABLED
509 g_main_context_init_pipe (GMainContext *context)
512 if (context->wake_up_pipe[0] != -1)
516 /* if this fails, we fall through and try pipe */
517 pipe2 (context->wake_up_pipe, O_CLOEXEC);
519 if (context->wake_up_pipe[0] == -1)
521 if (pipe (context->wake_up_pipe) < 0)
522 g_error ("Cannot create pipe main loop wake-up: %s\n",
525 fcntl (context->wake_up_pipe[0], F_SETFD, FD_CLOEXEC);
526 fcntl (context->wake_up_pipe[1], F_SETFD, FD_CLOEXEC);
529 context->wake_up_rec.fd = context->wake_up_pipe[0];
530 context->wake_up_rec.events = G_IO_IN;
532 if (context->wake_up_semaphore != NULL)
534 context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
535 if (context->wake_up_semaphore == NULL)
536 g_error ("Cannot create wake-up semaphore: %s",
537 g_win32_error_message (GetLastError ()));
538 context->wake_up_rec.fd = (gintptr) context->wake_up_semaphore;
539 context->wake_up_rec.events = G_IO_IN;
541 if (_g_main_poll_debug)
542 g_print ("wake-up semaphore: %p\n", context->wake_up_semaphore);
544 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
548 _g_main_thread_init (void)
550 GSList *curr = main_contexts_without_pipe;
553 g_main_context_init_pipe ((GMainContext *)curr->data);
556 g_slist_free (main_contexts_without_pipe);
557 main_contexts_without_pipe = NULL;
559 #endif /* G_THREADS_ENABLED */
562 * g_main_context_new:
564 * Creates a new #GMainContext structure.
566 * Return value: the new #GMainContext
569 g_main_context_new (void)
571 GMainContext *context = g_new0 (GMainContext, 1);
573 #ifdef G_MAIN_POLL_DEBUG
575 static gboolean beenhere = FALSE;
579 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
580 _g_main_poll_debug = TRUE;
586 #ifdef G_THREADS_ENABLED
587 g_static_mutex_init (&context->mutex);
589 context->owner = NULL;
590 context->waiters = NULL;
593 context->wake_up_pipe[0] = -1;
594 context->wake_up_pipe[1] = -1;
596 context->wake_up_semaphore = NULL;
600 context->ref_count = 1;
602 context->next_id = 1;
604 context->source_list = NULL;
606 context->poll_func = g_poll;
608 context->cached_poll_array = NULL;
609 context->cached_poll_array_size = 0;
611 context->pending_dispatches = g_ptr_array_new ();
613 context->time_is_fresh = FALSE;
614 context->current_time_is_fresh = FALSE;
616 #ifdef G_THREADS_ENABLED
617 if (g_thread_supported ())
618 g_main_context_init_pipe (context);
620 main_contexts_without_pipe = g_slist_prepend (main_contexts_without_pipe,
624 G_LOCK (main_context_list);
625 main_context_list = g_slist_append (main_context_list, context);
627 #ifdef G_MAIN_POLL_DEBUG
628 if (_g_main_poll_debug)
629 g_print ("created context=%p\n", context);
632 G_UNLOCK (main_context_list);
638 * g_main_context_default:
640 * Returns the global default main context. This is the main context
641 * used for main loop functions when a main loop is not explicitly
642 * specified, and corresponds to the "main" main loop. See also
643 * g_main_context_get_thread_default().
645 * Return value: the global default main context.
648 g_main_context_default (void)
654 if (!default_main_context)
656 default_main_context = g_main_context_new ();
657 #ifdef G_MAIN_POLL_DEBUG
658 if (_g_main_poll_debug)
659 g_print ("default context=%p\n", default_main_context);
663 G_UNLOCK (main_loop);
665 return default_main_context;
668 static GStaticPrivate thread_context_stack = G_STATIC_PRIVATE_INIT;
671 free_context_stack (gpointer data)
673 GQueue *stack = data;
674 GMainContext *context;
676 while (!g_queue_is_empty (stack))
678 context = g_queue_pop_head (stack);
679 g_main_context_release (context);
681 g_main_context_unref (context);
683 g_queue_free (stack);
687 * g_main_context_push_thread_default:
688 * @context: a #GMainContext, or %NULL for the global default context
690 * Acquires @context and sets it as the thread-default context for the
691 * current thread. This will cause certain asynchronous operations
692 * (such as most <link linkend="gio">gio</link>-based I/O) which are
693 * started in this thread to run under @context and deliver their
694 * results to its main loop, rather than running under the global
695 * default context in the main thread. Note that calling this function
696 * changes the context returned by
697 * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
698 * one returned by g_main_context_default(), so it does not affect the
699 * context used by functions like g_idle_add().
701 * Normally you would call this function shortly after creating a new
702 * thread, passing it a #GMainContext which will be run by a
703 * #GMainLoop in that thread, to set a new default context for all
704 * async operations in that thread. (In this case, you don't need to
705 * ever call g_main_context_pop_thread_default().) In some cases
706 * however, you may want to schedule a single operation in a
707 * non-default context, or temporarily use a non-default context in
708 * the main thread. In that case, you can wrap the call to the
709 * asynchronous operation inside a
710 * g_main_context_push_thread_default() /
711 * g_main_context_pop_thread_default() pair, but it is up to you to
712 * ensure that no other asynchronous operations accidentally get
713 * started while the non-default context is active.
715 * Beware that libraries that predate this function may not correctly
716 * handle being used from a thread with a thread-default context. Eg,
717 * see g_file_supports_thread_contexts().
722 g_main_context_push_thread_default (GMainContext *context)
725 gboolean acquired_context;
727 acquired_context = g_main_context_acquire (context);
728 g_return_if_fail (acquired_context);
730 if (context == g_main_context_default ())
733 g_main_context_ref (context);
735 stack = g_static_private_get (&thread_context_stack);
738 stack = g_queue_new ();
739 g_static_private_set (&thread_context_stack, stack,
743 g_queue_push_head (stack, context);
747 * g_main_context_pop_thread_default:
748 * @context: a #GMainContext object, or %NULL
750 * Pops @context off the thread-default context stack (verifying that
751 * it was on the top of the stack).
756 g_main_context_pop_thread_default (GMainContext *context)
760 if (context == g_main_context_default ())
763 stack = g_static_private_get (&thread_context_stack);
765 g_return_if_fail (stack != NULL);
766 g_return_if_fail (g_queue_peek_head (stack) == context);
768 g_queue_pop_head (stack);
770 g_main_context_release (context);
772 g_main_context_unref (context);
776 * g_main_context_get_thread_default:
778 * Gets the thread-default #GMainContext for this thread. Asynchronous
779 * operations that want to be able to be run in contexts other than
780 * the default one should call this method to get a #GMainContext to
781 * add their #GSource<!-- -->s to. (Note that even in single-threaded
782 * programs applications may sometimes want to temporarily push a
783 * non-default context, so it is not safe to assume that this will
784 * always return %NULL if threads are not initialized.)
786 * Returns: the thread-default #GMainContext, or %NULL if the
787 * thread-default context is the global default context.
792 g_main_context_get_thread_default (void)
796 stack = g_static_private_get (&thread_context_stack);
798 return g_queue_peek_head (stack);
803 /* Hooks for adding to the main loop */
807 * @source_funcs: structure containing functions that implement
808 * the sources behavior.
809 * @struct_size: size of the #GSource structure to create.
811 * Creates a new #GSource structure. The size is specified to
812 * allow creating structures derived from #GSource that contain
813 * additional data. The size passed in must be at least
814 * <literal>sizeof (GSource)</literal>.
816 * The source will not initially be associated with any #GMainContext
817 * and must be added to one with g_source_attach() before it will be
820 * Return value: the newly-created #GSource.
823 g_source_new (GSourceFuncs *source_funcs,
828 g_return_val_if_fail (source_funcs != NULL, NULL);
829 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
831 source = (GSource*) g_malloc0 (struct_size);
833 source->source_funcs = source_funcs;
834 source->ref_count = 1;
836 source->priority = G_PRIORITY_DEFAULT;
838 source->flags = G_HOOK_FLAG_ACTIVE;
840 /* NULL/0 initialization for all other fields */
845 /* Holds context's lock
848 g_source_list_add (GSource *source,
849 GMainContext *context)
851 GSource *tmp_source, *last_source;
854 tmp_source = context->source_list;
855 while (tmp_source && tmp_source->priority <= source->priority)
857 last_source = tmp_source;
858 tmp_source = tmp_source->next;
861 source->next = tmp_source;
863 tmp_source->prev = source;
865 source->prev = last_source;
867 last_source->next = source;
869 context->source_list = source;
872 /* Holds context's lock
875 g_source_list_remove (GSource *source,
876 GMainContext *context)
879 source->prev->next = source->next;
881 context->source_list = source->next;
884 source->next->prev = source->prev;
892 * @source: a #GSource
893 * @context: a #GMainContext (if %NULL, the default context will be used)
895 * Adds a #GSource to a @context so that it will be executed within
896 * that context. Remove it by calling g_source_destroy().
898 * Return value: the ID (greater than 0) for the source within the
902 g_source_attach (GSource *source,
903 GMainContext *context)
908 g_return_val_if_fail (source->context == NULL, 0);
909 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
912 context = g_main_context_default ();
914 LOCK_CONTEXT (context);
916 source->context = context;
917 result = source->source_id = context->next_id++;
920 g_source_list_add (source, context);
922 tmp_list = source->poll_fds;
925 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
926 tmp_list = tmp_list->next;
929 #ifdef G_THREADS_ENABLED
930 /* Now wake up the main loop if it is waiting in the poll() */
931 g_main_context_wakeup_unlocked (context);
934 UNLOCK_CONTEXT (context);
940 g_source_destroy_internal (GSource *source,
941 GMainContext *context,
945 LOCK_CONTEXT (context);
947 if (!SOURCE_DESTROYED (source))
950 gpointer old_cb_data;
951 GSourceCallbackFuncs *old_cb_funcs;
953 source->flags &= ~G_HOOK_FLAG_ACTIVE;
955 old_cb_data = source->callback_data;
956 old_cb_funcs = source->callback_funcs;
958 source->callback_data = NULL;
959 source->callback_funcs = NULL;
963 UNLOCK_CONTEXT (context);
964 old_cb_funcs->unref (old_cb_data);
965 LOCK_CONTEXT (context);
968 if (!SOURCE_BLOCKED (source))
970 tmp_list = source->poll_fds;
973 g_main_context_remove_poll_unlocked (context, tmp_list->data);
974 tmp_list = tmp_list->next;
978 g_source_unref_internal (source, context, TRUE);
982 UNLOCK_CONTEXT (context);
987 * @source: a #GSource
989 * Removes a source from its #GMainContext, if any, and mark it as
990 * destroyed. The source cannot be subsequently added to another
994 g_source_destroy (GSource *source)
996 GMainContext *context;
998 g_return_if_fail (source != NULL);
1000 context = source->context;
1003 g_source_destroy_internal (source, context, FALSE);
1005 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1010 * @source: a #GSource
1012 * Returns the numeric ID for a particular source. The ID of a source
1013 * is a positive integer which is unique within a particular main loop
1014 * context. The reverse
1015 * mapping from ID to source is done by g_main_context_find_source_by_id().
1017 * Return value: the ID (greater than 0) for the source
1020 g_source_get_id (GSource *source)
1024 g_return_val_if_fail (source != NULL, 0);
1025 g_return_val_if_fail (source->context != NULL, 0);
1027 LOCK_CONTEXT (source->context);
1028 result = source->source_id;
1029 UNLOCK_CONTEXT (source->context);
1035 * g_source_get_context:
1036 * @source: a #GSource
1038 * Gets the #GMainContext with which the source is associated.
1039 * Calling this function on a destroyed source is an error.
1041 * Return value: the #GMainContext with which the source is associated,
1042 * or %NULL if the context has not yet been added
1046 g_source_get_context (GSource *source)
1048 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1050 return source->context;
1054 * g_source_add_poll:
1055 * @source:a #GSource
1056 * @fd: a #GPollFD structure holding information about a file
1057 * descriptor to watch.
1059 * Adds a file descriptor to the set of file descriptors polled for
1060 * this source. This is usually combined with g_source_new() to add an
1061 * event source. The event source's check function will typically test
1062 * the @revents field in the #GPollFD struct and return %TRUE if events need
1066 g_source_add_poll (GSource *source,
1069 GMainContext *context;
1071 g_return_if_fail (source != NULL);
1072 g_return_if_fail (fd != NULL);
1073 g_return_if_fail (!SOURCE_DESTROYED (source));
1075 context = source->context;
1078 LOCK_CONTEXT (context);
1080 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1084 if (!SOURCE_BLOCKED (source))
1085 g_main_context_add_poll_unlocked (context, source->priority, fd);
1086 UNLOCK_CONTEXT (context);
1091 * g_source_remove_poll:
1092 * @source:a #GSource
1093 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1095 * Removes a file descriptor from the set of file descriptors polled for
1099 g_source_remove_poll (GSource *source,
1102 GMainContext *context;
1104 g_return_if_fail (source != NULL);
1105 g_return_if_fail (fd != NULL);
1106 g_return_if_fail (!SOURCE_DESTROYED (source));
1108 context = source->context;
1111 LOCK_CONTEXT (context);
1113 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1117 if (!SOURCE_BLOCKED (source))
1118 g_main_context_remove_poll_unlocked (context, fd);
1119 UNLOCK_CONTEXT (context);
1124 * g_source_set_callback_indirect:
1125 * @source: the source
1126 * @callback_data: pointer to callback data "object"
1127 * @callback_funcs: functions for reference counting @callback_data
1128 * and getting the callback and data
1130 * Sets the callback function storing the data as a refcounted callback
1131 * "object". This is used internally. Note that calling
1132 * g_source_set_callback_indirect() assumes
1133 * an initial reference count on @callback_data, and thus
1134 * @callback_funcs->unref will eventually be called once more
1135 * than @callback_funcs->ref.
1138 g_source_set_callback_indirect (GSource *source,
1139 gpointer callback_data,
1140 GSourceCallbackFuncs *callback_funcs)
1142 GMainContext *context;
1143 gpointer old_cb_data;
1144 GSourceCallbackFuncs *old_cb_funcs;
1146 g_return_if_fail (source != NULL);
1147 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1149 context = source->context;
1152 LOCK_CONTEXT (context);
1154 old_cb_data = source->callback_data;
1155 old_cb_funcs = source->callback_funcs;
1157 source->callback_data = callback_data;
1158 source->callback_funcs = callback_funcs;
1161 UNLOCK_CONTEXT (context);
1164 old_cb_funcs->unref (old_cb_data);
1168 g_source_callback_ref (gpointer cb_data)
1170 GSourceCallback *callback = cb_data;
1172 callback->ref_count++;
1177 g_source_callback_unref (gpointer cb_data)
1179 GSourceCallback *callback = cb_data;
1181 callback->ref_count--;
1182 if (callback->ref_count == 0)
1184 if (callback->notify)
1185 callback->notify (callback->data);
1191 g_source_callback_get (gpointer cb_data,
1196 GSourceCallback *callback = cb_data;
1198 *func = callback->func;
1199 *data = callback->data;
1202 static GSourceCallbackFuncs g_source_callback_funcs = {
1203 g_source_callback_ref,
1204 g_source_callback_unref,
1205 g_source_callback_get,
1209 * g_source_set_callback:
1210 * @source: the source
1211 * @func: a callback function
1212 * @data: the data to pass to callback function
1213 * @notify: a function to call when @data is no longer in use, or %NULL.
1215 * Sets the callback function for a source. The callback for a source is
1216 * called from the source's dispatch function.
1218 * The exact type of @func depends on the type of source; ie. you
1219 * should not count on @func being called with @data as its first
1222 * Typically, you won't use this function. Instead use functions specific
1223 * to the type of source you are using.
1226 g_source_set_callback (GSource *source,
1229 GDestroyNotify notify)
1231 GSourceCallback *new_callback;
1233 g_return_if_fail (source != NULL);
1235 new_callback = g_new (GSourceCallback, 1);
1237 new_callback->ref_count = 1;
1238 new_callback->func = func;
1239 new_callback->data = data;
1240 new_callback->notify = notify;
1242 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1247 * g_source_set_funcs:
1248 * @source: a #GSource
1249 * @funcs: the new #GSourceFuncs
1251 * Sets the source functions (can be used to override
1252 * default implementations) of an unattached source.
1257 g_source_set_funcs (GSource *source,
1258 GSourceFuncs *funcs)
1260 g_return_if_fail (source != NULL);
1261 g_return_if_fail (source->context == NULL);
1262 g_return_if_fail (source->ref_count > 0);
1263 g_return_if_fail (funcs != NULL);
1265 source->source_funcs = funcs;
1269 * g_source_set_priority:
1270 * @source: a #GSource
1271 * @priority: the new priority.
1273 * Sets the priority of a source. While the main loop is being
1274 * run, a source will be dispatched if it is ready to be dispatched and no sources
1275 * at a higher (numerically smaller) priority are ready to be dispatched.
1278 g_source_set_priority (GSource *source,
1282 GMainContext *context;
1284 g_return_if_fail (source != NULL);
1286 context = source->context;
1289 LOCK_CONTEXT (context);
1291 source->priority = priority;
1295 /* Remove the source from the context's source and then
1296 * add it back so it is sorted in the correct plcae
1298 g_source_list_remove (source, source->context);
1299 g_source_list_add (source, source->context);
1301 if (!SOURCE_BLOCKED (source))
1303 tmp_list = source->poll_fds;
1306 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1307 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1309 tmp_list = tmp_list->next;
1313 UNLOCK_CONTEXT (source->context);
1318 * g_source_get_priority:
1319 * @source: a #GSource
1321 * Gets the priority of a source.
1323 * Return value: the priority of the source
1326 g_source_get_priority (GSource *source)
1328 g_return_val_if_fail (source != NULL, 0);
1330 return source->priority;
1334 * g_source_set_can_recurse:
1335 * @source: a #GSource
1336 * @can_recurse: whether recursion is allowed for this source
1338 * Sets whether a source can be called recursively. If @can_recurse is
1339 * %TRUE, then while the source is being dispatched then this source
1340 * will be processed normally. Otherwise, all processing of this
1341 * source is blocked until the dispatch function returns.
1344 g_source_set_can_recurse (GSource *source,
1345 gboolean can_recurse)
1347 GMainContext *context;
1349 g_return_if_fail (source != NULL);
1351 context = source->context;
1354 LOCK_CONTEXT (context);
1357 source->flags |= G_SOURCE_CAN_RECURSE;
1359 source->flags &= ~G_SOURCE_CAN_RECURSE;
1362 UNLOCK_CONTEXT (context);
1366 * g_source_get_can_recurse:
1367 * @source: a #GSource
1369 * Checks whether a source is allowed to be called recursively.
1370 * see g_source_set_can_recurse().
1372 * Return value: whether recursion is allowed.
1375 g_source_get_can_recurse (GSource *source)
1377 g_return_val_if_fail (source != NULL, FALSE);
1379 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1384 * g_source_set_name:
1385 * @source: a #GSource
1386 * @name: debug name for the source
1388 * Sets a name for the source, used in debugging and profiling.
1389 * The name defaults to #NULL.
1391 * The source name should describe in a human-readable way
1392 * what the source does. For example, "X11 event queue"
1393 * or "GTK+ repaint idle handler" or whatever it is.
1395 * It is permitted to call this function multiple times, but is not
1396 * recommended due to the potential performance impact. For example,
1397 * one could change the name in the "check" function of a #GSourceFuncs
1398 * to include details like the event type in the source name.
1403 g_source_set_name (GSource *source,
1406 g_return_if_fail (source != NULL);
1408 /* setting back to NULL is allowed, just because it's
1409 * weird if get_name can return NULL but you can't
1413 g_free (source->name);
1414 source->name = g_strdup (name);
1418 * g_source_get_name:
1419 * @source: a #GSource
1421 * Gets a name for the source, used in debugging and profiling.
1422 * The name may be #NULL if it has never been set with
1423 * g_source_set_name().
1425 * Return value: the name of the source
1428 G_CONST_RETURN char*
1429 g_source_get_name (GSource *source)
1431 g_return_val_if_fail (source != NULL, NULL);
1433 return source->name;
1437 * g_source_set_name_by_id:
1438 * @tag: a #GSource ID
1439 * @name: debug name for the source
1441 * Sets the name of a source using its ID.
1443 * This is a convenience utility to set source names from the return
1444 * value of g_idle_add(), g_timeout_add(), etc.
1449 g_source_set_name_by_id (guint tag,
1454 g_return_if_fail (tag > 0);
1456 source = g_main_context_find_source_by_id (NULL, tag);
1460 g_source_set_name (source, name);
1466 * @source: a #GSource
1468 * Increases the reference count on a source by one.
1470 * Return value: @source
1473 g_source_ref (GSource *source)
1475 GMainContext *context;
1477 g_return_val_if_fail (source != NULL, NULL);
1479 context = source->context;
1482 LOCK_CONTEXT (context);
1484 source->ref_count++;
1487 UNLOCK_CONTEXT (context);
1492 /* g_source_unref() but possible to call within context lock
1495 g_source_unref_internal (GSource *source,
1496 GMainContext *context,
1499 gpointer old_cb_data = NULL;
1500 GSourceCallbackFuncs *old_cb_funcs = NULL;
1502 g_return_if_fail (source != NULL);
1504 if (!have_lock && context)
1505 LOCK_CONTEXT (context);
1507 source->ref_count--;
1508 if (source->ref_count == 0)
1510 old_cb_data = source->callback_data;
1511 old_cb_funcs = source->callback_funcs;
1513 source->callback_data = NULL;
1514 source->callback_funcs = NULL;
1516 if (context && !SOURCE_DESTROYED (source))
1518 g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1519 source->ref_count++;
1522 g_source_list_remove (source, context);
1524 if (source->source_funcs->finalize)
1525 source->source_funcs->finalize (source);
1527 g_free (source->name);
1528 source->name = NULL;
1530 g_slist_free (source->poll_fds);
1531 source->poll_fds = NULL;
1535 if (!have_lock && context)
1536 UNLOCK_CONTEXT (context);
1541 UNLOCK_CONTEXT (context);
1543 old_cb_funcs->unref (old_cb_data);
1546 LOCK_CONTEXT (context);
1552 * @source: a #GSource
1554 * Decreases the reference count of a source by one. If the
1555 * resulting reference count is zero the source and associated
1556 * memory will be destroyed.
1559 g_source_unref (GSource *source)
1561 g_return_if_fail (source != NULL);
1563 g_source_unref_internal (source, source->context, FALSE);
1567 * g_main_context_find_source_by_id:
1568 * @context: a #GMainContext (if %NULL, the default context will be used)
1569 * @source_id: the source ID, as returned by g_source_get_id().
1571 * Finds a #GSource given a pair of context and ID.
1573 * Return value: the #GSource if found, otherwise, %NULL
1576 g_main_context_find_source_by_id (GMainContext *context,
1581 g_return_val_if_fail (source_id > 0, NULL);
1583 if (context == NULL)
1584 context = g_main_context_default ();
1586 LOCK_CONTEXT (context);
1588 source = context->source_list;
1591 if (!SOURCE_DESTROYED (source) &&
1592 source->source_id == source_id)
1594 source = source->next;
1597 UNLOCK_CONTEXT (context);
1603 * g_main_context_find_source_by_funcs_user_data:
1604 * @context: a #GMainContext (if %NULL, the default context will be used).
1605 * @funcs: the @source_funcs passed to g_source_new().
1606 * @user_data: the user data from the callback.
1608 * Finds a source with the given source functions and user data. If
1609 * multiple sources exist with the same source function and user data,
1610 * the first one found will be returned.
1612 * Return value: the source, if one was found, otherwise %NULL
1615 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1616 GSourceFuncs *funcs,
1621 g_return_val_if_fail (funcs != NULL, NULL);
1623 if (context == NULL)
1624 context = g_main_context_default ();
1626 LOCK_CONTEXT (context);
1628 source = context->source_list;
1631 if (!SOURCE_DESTROYED (source) &&
1632 source->source_funcs == funcs &&
1633 source->callback_funcs)
1635 GSourceFunc callback;
1636 gpointer callback_data;
1638 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1640 if (callback_data == user_data)
1643 source = source->next;
1646 UNLOCK_CONTEXT (context);
1652 * g_main_context_find_source_by_user_data:
1653 * @context: a #GMainContext
1654 * @user_data: the user_data for the callback.
1656 * Finds a source with the given user data for the callback. If
1657 * multiple sources exist with the same user data, the first
1658 * one found will be returned.
1660 * Return value: the source, if one was found, otherwise %NULL
1663 g_main_context_find_source_by_user_data (GMainContext *context,
1668 if (context == NULL)
1669 context = g_main_context_default ();
1671 LOCK_CONTEXT (context);
1673 source = context->source_list;
1676 if (!SOURCE_DESTROYED (source) &&
1677 source->callback_funcs)
1679 GSourceFunc callback;
1680 gpointer callback_data = NULL;
1682 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1684 if (callback_data == user_data)
1687 source = source->next;
1690 UNLOCK_CONTEXT (context);
1697 * @tag: the ID of the source to remove.
1699 * Removes the source with the given id from the default main context.
1701 * a #GSource is given by g_source_get_id(), or will be returned by the
1702 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1703 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1704 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1706 * See also g_source_destroy(). You must use g_source_destroy() for sources
1707 * added to a non-default main context.
1709 * Return value: %TRUE if the source was found and removed.
1712 g_source_remove (guint tag)
1716 g_return_val_if_fail (tag > 0, FALSE);
1718 source = g_main_context_find_source_by_id (NULL, tag);
1720 g_source_destroy (source);
1722 return source != NULL;
1726 * g_source_remove_by_user_data:
1727 * @user_data: the user_data for the callback.
1729 * Removes a source from the default main loop context given the user
1730 * data for the callback. If multiple sources exist with the same user
1731 * data, only one will be destroyed.
1733 * Return value: %TRUE if a source was found and removed.
1736 g_source_remove_by_user_data (gpointer user_data)
1740 source = g_main_context_find_source_by_user_data (NULL, user_data);
1743 g_source_destroy (source);
1751 * g_source_remove_by_funcs_user_data:
1752 * @funcs: The @source_funcs passed to g_source_new()
1753 * @user_data: the user data for the callback
1755 * Removes a source from the default main loop context given the
1756 * source functions and user data. If multiple sources exist with the
1757 * same source functions and user data, only one will be destroyed.
1759 * Return value: %TRUE if a source was found and removed.
1762 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1767 g_return_val_if_fail (funcs != NULL, FALSE);
1769 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1772 g_source_destroy (source);
1780 * g_get_current_time:
1781 * @result: #GTimeVal structure in which to store current time.
1783 * Equivalent to the UNIX gettimeofday() function, but portable.
1786 g_get_current_time (GTimeVal *result)
1791 g_return_if_fail (result != NULL);
1793 /*this is required on alpha, there the timeval structs are int's
1794 not longs and a cast only would fail horribly*/
1795 gettimeofday (&r, NULL);
1796 result->tv_sec = r.tv_sec;
1797 result->tv_usec = r.tv_usec;
1802 g_return_if_fail (result != NULL);
1804 GetSystemTimeAsFileTime (&ft);
1805 memmove (&time64, &ft, sizeof (FILETIME));
1807 /* Convert from 100s of nanoseconds since 1601-01-01
1808 * to Unix epoch. Yes, this is Y2038 unsafe.
1810 time64 -= G_GINT64_CONSTANT (116444736000000000);
1813 result->tv_sec = time64 / 1000000;
1814 result->tv_usec = time64 % 1000000;
1821 * Represents a precise time, with seconds and nanoseconds. This is
1822 * similar to POSIX <structname>struct timespec</structname>. This
1823 * structure can be filled in with g_get_monotonic_time().
1829 * g_get_monotonic_time:
1830 * @result: #GTimeSpec structure in which to store the time
1832 * Queries the system monotonic time, if available.
1834 * On POSIX systems with clock_gettime() and %CLOCK_MONOTONIC this call
1835 * is a very shallow wrapper for that. Otherwise, we make a best effort
1836 * that probably involves returning the wall clock time (with at least
1837 * microsecond accuracy, subject to the limitations of the OS kernel).
1839 * Note that, on Windows, "limitations of the OS kernel" is a rather
1840 * substantial statement. Depending on the configuration of the system,
1841 * the wall clock time is updated as infrequently as 64 times a second
1842 * (which is approximately every 16ms).
1847 g_get_monotonic_time (GTimeSpec *result)
1849 g_return_if_fail (result != NULL);
1851 #ifdef HAVE_CLOCK_GETTIME
1852 /* librt clock_gettime() is our first choice */
1854 static int clockid = CLOCK_REALTIME;
1857 #ifdef HAVE_MONOTONIC_CLOCK
1858 /* We have to check if we actually have monotonic clock support.
1860 * There is no thread safety issue here since there is no harm if we
1864 static gboolean checked;
1866 if G_UNLIKELY (!checked)
1868 if (sysconf (_SC_MONOTONIC_CLOCK) >= 0)
1869 clockid = CLOCK_MONOTONIC;
1875 clock_gettime (clockid, &ts);
1876 result->tv_sec = ts.tv_sec;
1877 result->tv_nsec = ts.tv_nsec;
1880 /* It may look like we are discarding accuracy on Windows (since its
1881 * current time is expressed in 100s of nanoseconds) but according to
1882 * many sources, the time is only updated 64 times per second, so
1883 * microsecond accuracy is more than enough.
1888 g_get_current_time (&tv);
1889 result->tv_sec = tv.tv_sec;
1890 result->tv_nsec = tv.tv_usec * 1000;
1896 g_main_dispatch_free (gpointer dispatch)
1898 g_slice_free (GMainDispatch, dispatch);
1901 /* Running the main loop */
1903 static GMainDispatch *
1906 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
1907 GMainDispatch *dispatch = g_static_private_get (&depth_private);
1910 dispatch = g_slice_new0 (GMainDispatch);
1911 g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
1920 * Returns the depth of the stack of calls to
1921 * g_main_context_dispatch() on any #GMainContext in the current thread.
1922 * That is, when called from the toplevel, it gives 0. When
1923 * called from within a callback from g_main_context_iteration()
1924 * (or g_main_loop_run(), etc.) it returns 1. When called from within
1925 * a callback to a recursive call to g_main_context_iterate(),
1926 * it returns 2. And so forth.
1928 * This function is useful in a situation like the following:
1929 * Imagine an extremely simple "garbage collected" system.
1932 * static GList *free_list;
1935 * allocate_memory (gsize size)
1937 * gpointer result = g_malloc (size);
1938 * free_list = g_list_prepend (free_list, result);
1943 * free_allocated_memory (void)
1946 * for (l = free_list; l; l = l->next);
1948 * g_list_free (free_list);
1956 * g_main_context_iteration (NULL, TRUE);
1957 * free_allocated_memory();
1961 * This works from an application, however, if you want to do the same
1962 * thing from a library, it gets more difficult, since you no longer
1963 * control the main loop. You might think you can simply use an idle
1964 * function to make the call to free_allocated_memory(), but that
1965 * doesn't work, since the idle function could be called from a
1966 * recursive callback. This can be fixed by using g_main_depth()
1970 * allocate_memory (gsize size)
1972 * FreeListBlock *block = g_new (FreeListBlock, 1);
1973 * block->mem = g_malloc (size);
1974 * block->depth = g_main_depth ();
1975 * free_list = g_list_prepend (free_list, block);
1976 * return block->mem;
1980 * free_allocated_memory (void)
1984 * int depth = g_main_depth ();
1985 * for (l = free_list; l; );
1987 * GList *next = l->next;
1988 * FreeListBlock *block = l->data;
1989 * if (block->depth > depth)
1991 * g_free (block->mem);
1993 * free_list = g_list_delete_link (free_list, l);
2001 * There is a temptation to use g_main_depth() to solve
2002 * problems with reentrancy. For instance, while waiting for data
2003 * to be received from the network in response to a menu item,
2004 * the menu item might be selected again. It might seem that
2005 * one could make the menu item's callback return immediately
2006 * and do nothing if g_main_depth() returns a value greater than 1.
2007 * However, this should be avoided since the user then sees selecting
2008 * the menu item do nothing. Furthermore, you'll find yourself adding
2009 * these checks all over your code, since there are doubtless many,
2010 * many things that the user could do. Instead, you can use the
2011 * following techniques:
2016 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
2017 * the user from interacting with elements while the main
2018 * loop is recursing.
2023 * Avoid main loop recursion in situations where you can't handle
2024 * arbitrary callbacks. Instead, structure your code so that you
2025 * simply return to the main loop and then get called again when
2026 * there is more work to do.
2031 * Return value: The main loop recursion level in the current thread
2036 GMainDispatch *dispatch = get_dispatch ();
2037 return dispatch->depth;
2041 * g_main_current_source:
2043 * Returns the currently firing source for this thread.
2045 * Return value: The currently firing source or %NULL.
2050 g_main_current_source (void)
2052 GMainDispatch *dispatch = get_dispatch ();
2053 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
2057 * g_source_is_destroyed:
2058 * @source: a #GSource
2060 * Returns whether @source has been destroyed.
2062 * This is important when you operate upon your objects
2063 * from within idle handlers, but may have freed the object
2064 * before the dispatch of your idle handler.
2068 * idle_callback (gpointer data)
2070 * SomeWidget *self = data;
2072 * GDK_THREADS_ENTER (<!-- -->);
2073 * /<!-- -->* do stuff with self *<!-- -->/
2074 * self->idle_id = 0;
2075 * GDK_THREADS_LEAVE (<!-- -->);
2081 * some_widget_do_stuff_later (SomeWidget *self)
2083 * self->idle_id = g_idle_add (idle_callback, self);
2087 * some_widget_finalize (GObject *object)
2089 * SomeWidget *self = SOME_WIDGET (object);
2091 * if (self->idle_id)
2092 * g_source_remove (self->idle_id);
2094 * G_OBJECT_CLASS (parent_class)->finalize (object);
2098 * This will fail in a multi-threaded application if the
2099 * widget is destroyed before the idle handler fires due
2100 * to the use after free in the callback. A solution, to
2101 * this particular problem, is to check to if the source
2102 * has already been destroy within the callback.
2106 * idle_callback (gpointer data)
2108 * SomeWidget *self = data;
2110 * GDK_THREADS_ENTER ();
2111 * if (!g_source_is_destroyed (g_main_current_source ()))
2113 * /<!-- -->* do stuff with self *<!-- -->/
2115 * GDK_THREADS_LEAVE ();
2121 * Return value: %TRUE if the source has been destroyed
2126 g_source_is_destroyed (GSource *source)
2128 return SOURCE_DESTROYED (source);
2131 /* Temporarily remove all this source's file descriptors from the
2132 * poll(), so that if data comes available for one of the file descriptors
2133 * we don't continually spin in the poll()
2135 /* HOLDS: source->context's lock */
2137 block_source (GSource *source)
2141 g_return_if_fail (!SOURCE_BLOCKED (source));
2143 tmp_list = source->poll_fds;
2146 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2147 tmp_list = tmp_list->next;
2151 /* HOLDS: source->context's lock */
2153 unblock_source (GSource *source)
2157 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
2158 g_return_if_fail (!SOURCE_DESTROYED (source));
2160 tmp_list = source->poll_fds;
2163 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2164 tmp_list = tmp_list->next;
2168 /* HOLDS: context's lock */
2170 g_main_dispatch (GMainContext *context)
2172 GMainDispatch *current = get_dispatch ();
2175 for (i = 0; i < context->pending_dispatches->len; i++)
2177 GSource *source = context->pending_dispatches->pdata[i];
2179 context->pending_dispatches->pdata[i] = NULL;
2182 source->flags &= ~G_SOURCE_READY;
2184 if (!SOURCE_DESTROYED (source))
2186 gboolean was_in_call;
2187 gpointer user_data = NULL;
2188 GSourceFunc callback = NULL;
2189 GSourceCallbackFuncs *cb_funcs;
2191 gboolean need_destroy;
2193 gboolean (*dispatch) (GSource *,
2196 GSList current_source_link;
2198 dispatch = source->source_funcs->dispatch;
2199 cb_funcs = source->callback_funcs;
2200 cb_data = source->callback_data;
2203 cb_funcs->ref (cb_data);
2205 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2206 block_source (source);
2208 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2209 source->flags |= G_HOOK_FLAG_IN_CALL;
2212 cb_funcs->get (cb_data, source, &callback, &user_data);
2214 UNLOCK_CONTEXT (context);
2217 /* The on-stack allocation of the GSList is unconventional, but
2218 * we know that the lifetime of the link is bounded to this
2219 * function as the link is kept in a thread specific list and
2220 * not manipulated outside of this function and its descendants.
2221 * Avoiding the overhead of a g_slist_alloc() is useful as many
2222 * applications do little more than dispatch events.
2224 * This is a performance hack - do not revert to g_slist_prepend()!
2226 current_source_link.data = source;
2227 current_source_link.next = current->dispatching_sources;
2228 current->dispatching_sources = ¤t_source_link;
2229 need_destroy = ! dispatch (source,
2232 g_assert (current->dispatching_sources == ¤t_source_link);
2233 current->dispatching_sources = current_source_link.next;
2237 cb_funcs->unref (cb_data);
2239 LOCK_CONTEXT (context);
2242 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2244 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2245 !SOURCE_DESTROYED (source))
2246 unblock_source (source);
2248 /* Note: this depends on the fact that we can't switch
2249 * sources from one main context to another
2251 if (need_destroy && !SOURCE_DESTROYED (source))
2253 g_assert (source->context == context);
2254 g_source_destroy_internal (source, context, TRUE);
2258 SOURCE_UNREF (source, context);
2261 g_ptr_array_set_size (context->pending_dispatches, 0);
2264 /* Holds context's lock */
2265 static inline GSource *
2266 next_valid_source (GMainContext *context,
2269 GSource *new_source = source ? source->next : context->source_list;
2273 if (!SOURCE_DESTROYED (new_source))
2275 new_source->ref_count++;
2279 new_source = new_source->next;
2283 SOURCE_UNREF (source, context);
2289 * g_main_context_acquire:
2290 * @context: a #GMainContext
2292 * Tries to become the owner of the specified context.
2293 * If some other thread is the owner of the context,
2294 * returns %FALSE immediately. Ownership is properly
2295 * recursive: the owner can require ownership again
2296 * and will release ownership when g_main_context_release()
2297 * is called as many times as g_main_context_acquire().
2299 * You must be the owner of a context before you
2300 * can call g_main_context_prepare(), g_main_context_query(),
2301 * g_main_context_check(), g_main_context_dispatch().
2303 * Return value: %TRUE if the operation succeeded, and
2304 * this thread is now the owner of @context.
2307 g_main_context_acquire (GMainContext *context)
2309 #ifdef G_THREADS_ENABLED
2310 gboolean result = FALSE;
2311 GThread *self = G_THREAD_SELF;
2313 if (context == NULL)
2314 context = g_main_context_default ();
2316 LOCK_CONTEXT (context);
2318 if (!context->owner)
2320 context->owner = self;
2321 g_assert (context->owner_count == 0);
2324 if (context->owner == self)
2326 context->owner_count++;
2330 UNLOCK_CONTEXT (context);
2333 #else /* !G_THREADS_ENABLED */
2335 #endif /* G_THREADS_ENABLED */
2339 * g_main_context_release:
2340 * @context: a #GMainContext
2342 * Releases ownership of a context previously acquired by this thread
2343 * with g_main_context_acquire(). If the context was acquired multiple
2344 * times, the ownership will be released only when g_main_context_release()
2345 * is called as many times as it was acquired.
2348 g_main_context_release (GMainContext *context)
2350 #ifdef G_THREADS_ENABLED
2351 if (context == NULL)
2352 context = g_main_context_default ();
2354 LOCK_CONTEXT (context);
2356 context->owner_count--;
2357 if (context->owner_count == 0)
2359 context->owner = NULL;
2361 if (context->waiters)
2363 GMainWaiter *waiter = context->waiters->data;
2364 gboolean loop_internal_waiter =
2365 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
2366 context->waiters = g_slist_delete_link (context->waiters,
2368 if (!loop_internal_waiter)
2369 g_mutex_lock (waiter->mutex);
2371 g_cond_signal (waiter->cond);
2373 if (!loop_internal_waiter)
2374 g_mutex_unlock (waiter->mutex);
2378 UNLOCK_CONTEXT (context);
2379 #endif /* G_THREADS_ENABLED */
2383 * g_main_context_wait:
2384 * @context: a #GMainContext
2385 * @cond: a condition variable
2386 * @mutex: a mutex, currently held
2388 * Tries to become the owner of the specified context,
2389 * as with g_main_context_acquire(). But if another thread
2390 * is the owner, atomically drop @mutex and wait on @cond until
2391 * that owner releases ownership or until @cond is signaled, then
2392 * try again (once) to become the owner.
2394 * Return value: %TRUE if the operation succeeded, and
2395 * this thread is now the owner of @context.
2398 g_main_context_wait (GMainContext *context,
2402 #ifdef G_THREADS_ENABLED
2403 gboolean result = FALSE;
2404 GThread *self = G_THREAD_SELF;
2405 gboolean loop_internal_waiter;
2407 if (context == NULL)
2408 context = g_main_context_default ();
2410 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2412 if (!loop_internal_waiter)
2413 LOCK_CONTEXT (context);
2415 if (context->owner && context->owner != self)
2420 waiter.mutex = mutex;
2422 context->waiters = g_slist_append (context->waiters, &waiter);
2424 if (!loop_internal_waiter)
2425 UNLOCK_CONTEXT (context);
2426 g_cond_wait (cond, mutex);
2427 if (!loop_internal_waiter)
2428 LOCK_CONTEXT (context);
2430 context->waiters = g_slist_remove (context->waiters, &waiter);
2433 if (!context->owner)
2435 context->owner = self;
2436 g_assert (context->owner_count == 0);
2439 if (context->owner == self)
2441 context->owner_count++;
2445 if (!loop_internal_waiter)
2446 UNLOCK_CONTEXT (context);
2449 #else /* !G_THREADS_ENABLED */
2451 #endif /* G_THREADS_ENABLED */
2455 * g_main_context_prepare:
2456 * @context: a #GMainContext
2457 * @priority: location to store priority of highest priority
2458 * source already ready.
2460 * Prepares to poll sources within a main loop. The resulting information
2461 * for polling is determined by calling g_main_context_query ().
2463 * Return value: %TRUE if some source is ready to be dispatched
2467 g_main_context_prepare (GMainContext *context,
2472 gint current_priority = G_MAXINT;
2475 if (context == NULL)
2476 context = g_main_context_default ();
2478 LOCK_CONTEXT (context);
2480 context->time_is_fresh = FALSE;
2481 context->current_time_is_fresh = FALSE;
2483 if (context->in_check_or_prepare)
2485 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2486 "prepare() member.");
2487 UNLOCK_CONTEXT (context);
2491 #ifdef G_THREADS_ENABLED
2492 if (context->poll_waiting)
2494 g_warning("g_main_context_prepare(): main loop already active in another thread");
2495 UNLOCK_CONTEXT (context);
2499 context->poll_waiting = TRUE;
2500 #endif /* G_THREADS_ENABLED */
2503 /* If recursing, finish up current dispatch, before starting over */
2504 if (context->pending_dispatches)
2507 g_main_dispatch (context, ¤t_time);
2509 UNLOCK_CONTEXT (context);
2514 /* If recursing, clear list of pending dispatches */
2516 for (i = 0; i < context->pending_dispatches->len; i++)
2518 if (context->pending_dispatches->pdata[i])
2519 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2521 g_ptr_array_set_size (context->pending_dispatches, 0);
2523 /* Prepare all sources */
2525 context->timeout = -1;
2527 source = next_valid_source (context, NULL);
2530 gint source_timeout = -1;
2532 if ((n_ready > 0) && (source->priority > current_priority))
2534 SOURCE_UNREF (source, context);
2537 if (SOURCE_BLOCKED (source))
2540 if (!(source->flags & G_SOURCE_READY))
2543 gboolean (*prepare) (GSource *source,
2546 prepare = source->source_funcs->prepare;
2547 context->in_check_or_prepare++;
2548 UNLOCK_CONTEXT (context);
2550 result = (*prepare) (source, &source_timeout);
2552 LOCK_CONTEXT (context);
2553 context->in_check_or_prepare--;
2556 source->flags |= G_SOURCE_READY;
2559 if (source->flags & G_SOURCE_READY)
2562 current_priority = source->priority;
2563 context->timeout = 0;
2566 if (source_timeout >= 0)
2568 if (context->timeout < 0)
2569 context->timeout = source_timeout;
2571 context->timeout = MIN (context->timeout, source_timeout);
2575 source = next_valid_source (context, source);
2578 UNLOCK_CONTEXT (context);
2581 *priority = current_priority;
2583 return (n_ready > 0);
2587 * g_main_context_query:
2588 * @context: a #GMainContext
2589 * @max_priority: maximum priority source to check
2590 * @timeout_: location to store timeout to be used in polling
2591 * @fds: location to store #GPollFD records that need to be polled.
2592 * @n_fds: length of @fds.
2594 * Determines information necessary to poll this main loop.
2596 * Return value: the number of records actually stored in @fds,
2597 * or, if more than @n_fds records need to be stored, the number
2598 * of records that need to be stored.
2601 g_main_context_query (GMainContext *context,
2610 LOCK_CONTEXT (context);
2612 pollrec = context->poll_records;
2614 while (pollrec && max_priority >= pollrec->priority)
2616 /* We need to include entries with fd->events == 0 in the array because
2617 * otherwise if the application changes fd->events behind our back and
2618 * makes it non-zero, we'll be out of sync when we check the fds[] array.
2619 * (Changing fd->events after adding an FD wasn't an anticipated use of
2620 * this API, but it occurs in practice.) */
2623 fds[n_poll].fd = pollrec->fd->fd;
2624 /* In direct contradiction to the Unix98 spec, IRIX runs into
2625 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2626 * flags in the events field of the pollfd while it should
2627 * just ignoring them. So we mask them out here.
2629 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2630 fds[n_poll].revents = 0;
2633 pollrec = pollrec->next;
2637 #ifdef G_THREADS_ENABLED
2638 context->poll_changed = FALSE;
2643 *timeout = context->timeout;
2646 context->time_is_fresh = FALSE;
2647 context->current_time_is_fresh = FALSE;
2651 UNLOCK_CONTEXT (context);
2657 * g_main_context_check:
2658 * @context: a #GMainContext
2659 * @max_priority: the maximum numerical priority of sources to check
2660 * @fds: array of #GPollFD's that was passed to the last call to
2661 * g_main_context_query()
2662 * @n_fds: return value of g_main_context_query()
2664 * Passes the results of polling back to the main loop.
2666 * Return value: %TRUE if some sources are ready to be dispatched.
2669 g_main_context_check (GMainContext *context,
2679 LOCK_CONTEXT (context);
2681 if (context->in_check_or_prepare)
2683 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2684 "prepare() member.");
2685 UNLOCK_CONTEXT (context);
2689 #ifdef G_THREADS_ENABLED
2690 if (!context->poll_waiting)
2694 read (context->wake_up_pipe[0], &a, 1);
2698 context->poll_waiting = FALSE;
2700 /* If the set of poll file descriptors changed, bail out
2701 * and let the main loop rerun
2703 if (context->poll_changed)
2705 UNLOCK_CONTEXT (context);
2708 #endif /* G_THREADS_ENABLED */
2710 pollrec = context->poll_records;
2714 if (pollrec->fd->events)
2715 pollrec->fd->revents = fds[i].revents;
2717 pollrec = pollrec->next;
2721 source = next_valid_source (context, NULL);
2724 if ((n_ready > 0) && (source->priority > max_priority))
2726 SOURCE_UNREF (source, context);
2729 if (SOURCE_BLOCKED (source))
2732 if (!(source->flags & G_SOURCE_READY))
2735 gboolean (*check) (GSource *source);
2737 check = source->source_funcs->check;
2739 context->in_check_or_prepare++;
2740 UNLOCK_CONTEXT (context);
2742 result = (*check) (source);
2744 LOCK_CONTEXT (context);
2745 context->in_check_or_prepare--;
2748 source->flags |= G_SOURCE_READY;
2751 if (source->flags & G_SOURCE_READY)
2753 source->ref_count++;
2754 g_ptr_array_add (context->pending_dispatches, source);
2758 /* never dispatch sources with less priority than the first
2759 * one we choose to dispatch
2761 max_priority = source->priority;
2765 source = next_valid_source (context, source);
2768 UNLOCK_CONTEXT (context);
2774 * g_main_context_dispatch:
2775 * @context: a #GMainContext
2777 * Dispatches all pending sources.
2780 g_main_context_dispatch (GMainContext *context)
2782 LOCK_CONTEXT (context);
2784 if (context->pending_dispatches->len > 0)
2786 g_main_dispatch (context);
2789 UNLOCK_CONTEXT (context);
2792 /* HOLDS context lock */
2794 g_main_context_iterate (GMainContext *context,
2801 gboolean some_ready;
2802 gint nfds, allocated_nfds;
2803 GPollFD *fds = NULL;
2805 UNLOCK_CONTEXT (context);
2807 #ifdef G_THREADS_ENABLED
2808 if (!g_main_context_acquire (context))
2810 gboolean got_ownership;
2812 LOCK_CONTEXT (context);
2814 g_return_val_if_fail (g_thread_supported (), FALSE);
2820 context->cond = g_cond_new ();
2822 got_ownership = g_main_context_wait (context,
2824 g_static_mutex_get_mutex (&context->mutex));
2830 LOCK_CONTEXT (context);
2831 #endif /* G_THREADS_ENABLED */
2833 if (!context->cached_poll_array)
2835 context->cached_poll_array_size = context->n_poll_records;
2836 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2839 allocated_nfds = context->cached_poll_array_size;
2840 fds = context->cached_poll_array;
2842 UNLOCK_CONTEXT (context);
2844 g_main_context_prepare (context, &max_priority);
2846 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
2847 allocated_nfds)) > allocated_nfds)
2849 LOCK_CONTEXT (context);
2851 context->cached_poll_array_size = allocated_nfds = nfds;
2852 context->cached_poll_array = fds = g_new (GPollFD, nfds);
2853 UNLOCK_CONTEXT (context);
2859 g_main_context_poll (context, timeout, max_priority, fds, nfds);
2861 some_ready = g_main_context_check (context, max_priority, fds, nfds);
2864 g_main_context_dispatch (context);
2866 #ifdef G_THREADS_ENABLED
2867 g_main_context_release (context);
2868 #endif /* G_THREADS_ENABLED */
2870 LOCK_CONTEXT (context);
2876 * g_main_context_pending:
2877 * @context: a #GMainContext (if %NULL, the default context will be used)
2879 * Checks if any sources have pending events for the given context.
2881 * Return value: %TRUE if events are pending.
2884 g_main_context_pending (GMainContext *context)
2889 context = g_main_context_default();
2891 LOCK_CONTEXT (context);
2892 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
2893 UNLOCK_CONTEXT (context);
2899 * g_main_context_iteration:
2900 * @context: a #GMainContext (if %NULL, the default context will be used)
2901 * @may_block: whether the call may block.
2903 * Runs a single iteration for the given main loop. This involves
2904 * checking to see if any event sources are ready to be processed,
2905 * then if no events sources are ready and @may_block is %TRUE, waiting
2906 * for a source to become ready, then dispatching the highest priority
2907 * events sources that are ready. Otherwise, if @may_block is %FALSE
2908 * sources are not waited to become ready, only those highest priority
2909 * events sources will be dispatched (if any), that are ready at this
2910 * given moment without further waiting.
2912 * Note that even when @may_block is %TRUE, it is still possible for
2913 * g_main_context_iteration() to return %FALSE, since the the wait may
2914 * be interrupted for other reasons than an event source becoming ready.
2916 * Return value: %TRUE if events were dispatched.
2919 g_main_context_iteration (GMainContext *context, gboolean may_block)
2924 context = g_main_context_default();
2926 LOCK_CONTEXT (context);
2927 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
2928 UNLOCK_CONTEXT (context);
2935 * @context: a #GMainContext (if %NULL, the default context will be used).
2936 * @is_running: set to %TRUE to indicate that the loop is running. This
2937 * is not very important since calling g_main_loop_run() will set this to
2940 * Creates a new #GMainLoop structure.
2942 * Return value: a new #GMainLoop.
2945 g_main_loop_new (GMainContext *context,
2946 gboolean is_running)
2951 context = g_main_context_default();
2953 g_main_context_ref (context);
2955 loop = g_new0 (GMainLoop, 1);
2956 loop->context = context;
2957 loop->is_running = is_running != FALSE;
2958 loop->ref_count = 1;
2965 * @loop: a #GMainLoop
2967 * Increases the reference count on a #GMainLoop object by one.
2969 * Return value: @loop
2972 g_main_loop_ref (GMainLoop *loop)
2974 g_return_val_if_fail (loop != NULL, NULL);
2975 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2977 g_atomic_int_inc (&loop->ref_count);
2983 * g_main_loop_unref:
2984 * @loop: a #GMainLoop
2986 * Decreases the reference count on a #GMainLoop object by one. If
2987 * the result is zero, free the loop and free all associated memory.
2990 g_main_loop_unref (GMainLoop *loop)
2992 g_return_if_fail (loop != NULL);
2993 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2995 if (!g_atomic_int_dec_and_test (&loop->ref_count))
2998 g_main_context_unref (loop->context);
3004 * @loop: a #GMainLoop
3006 * Runs a main loop until g_main_loop_quit() is called on the loop.
3007 * If this is called for the thread of the loop's #GMainContext,
3008 * it will process events from the loop, otherwise it will
3012 g_main_loop_run (GMainLoop *loop)
3014 GThread *self = G_THREAD_SELF;
3016 g_return_if_fail (loop != NULL);
3017 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3019 #ifdef G_THREADS_ENABLED
3020 if (!g_main_context_acquire (loop->context))
3022 gboolean got_ownership = FALSE;
3024 /* Another thread owns this context */
3025 if (!g_thread_supported ())
3027 g_warning ("g_main_loop_run() was called from second thread but "
3028 "g_thread_init() was never called.");
3032 LOCK_CONTEXT (loop->context);
3034 g_atomic_int_inc (&loop->ref_count);
3036 if (!loop->is_running)
3037 loop->is_running = TRUE;
3039 if (!loop->context->cond)
3040 loop->context->cond = g_cond_new ();
3042 while (loop->is_running && !got_ownership)
3043 got_ownership = g_main_context_wait (loop->context,
3044 loop->context->cond,
3045 g_static_mutex_get_mutex (&loop->context->mutex));
3047 if (!loop->is_running)
3049 UNLOCK_CONTEXT (loop->context);
3051 g_main_context_release (loop->context);
3052 g_main_loop_unref (loop);
3056 g_assert (got_ownership);
3059 LOCK_CONTEXT (loop->context);
3060 #endif /* G_THREADS_ENABLED */
3062 if (loop->context->in_check_or_prepare)
3064 g_warning ("g_main_loop_run(): called recursively from within a source's "
3065 "check() or prepare() member, iteration not possible.");
3069 g_atomic_int_inc (&loop->ref_count);
3070 loop->is_running = TRUE;
3071 while (loop->is_running)
3072 g_main_context_iterate (loop->context, TRUE, TRUE, self);
3074 UNLOCK_CONTEXT (loop->context);
3076 #ifdef G_THREADS_ENABLED
3077 g_main_context_release (loop->context);
3078 #endif /* G_THREADS_ENABLED */
3080 g_main_loop_unref (loop);
3085 * @loop: a #GMainLoop
3087 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3088 * for the loop will return.
3090 * Note that sources that have already been dispatched when
3091 * g_main_loop_quit() is called will still be executed.
3094 g_main_loop_quit (GMainLoop *loop)
3096 g_return_if_fail (loop != NULL);
3097 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3099 LOCK_CONTEXT (loop->context);
3100 loop->is_running = FALSE;
3101 g_main_context_wakeup_unlocked (loop->context);
3103 #ifdef G_THREADS_ENABLED
3104 if (loop->context->cond)
3105 g_cond_broadcast (loop->context->cond);
3106 #endif /* G_THREADS_ENABLED */
3108 UNLOCK_CONTEXT (loop->context);
3112 * g_main_loop_is_running:
3113 * @loop: a #GMainLoop.
3115 * Checks to see if the main loop is currently being run via g_main_loop_run().
3117 * Return value: %TRUE if the mainloop is currently being run.
3120 g_main_loop_is_running (GMainLoop *loop)
3122 g_return_val_if_fail (loop != NULL, FALSE);
3123 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3125 return loop->is_running;
3129 * g_main_loop_get_context:
3130 * @loop: a #GMainLoop.
3132 * Returns the #GMainContext of @loop.
3134 * Return value: the #GMainContext of @loop
3137 g_main_loop_get_context (GMainLoop *loop)
3139 g_return_val_if_fail (loop != NULL, NULL);
3140 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3142 return loop->context;
3145 /* HOLDS: context's lock */
3147 g_main_context_poll (GMainContext *context,
3153 #ifdef G_MAIN_POLL_DEBUG
3159 GPollFunc poll_func;
3161 if (n_fds || timeout != 0)
3163 #ifdef G_MAIN_POLL_DEBUG
3164 if (_g_main_poll_debug)
3166 g_print ("polling context=%p n=%d timeout=%d\n",
3167 context, n_fds, timeout);
3168 poll_timer = g_timer_new ();
3172 LOCK_CONTEXT (context);
3174 poll_func = context->poll_func;
3176 UNLOCK_CONTEXT (context);
3177 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3180 g_warning ("poll(2) failed due to: %s.",
3181 g_strerror (errno));
3183 /* If g_poll () returns -1, it has already called g_warning() */
3187 #ifdef G_MAIN_POLL_DEBUG
3188 if (_g_main_poll_debug)
3190 LOCK_CONTEXT (context);
3192 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3195 g_timer_elapsed (poll_timer, NULL));
3196 g_timer_destroy (poll_timer);
3197 pollrec = context->poll_records;
3199 while (pollrec != NULL)
3204 if (fds[i].fd == pollrec->fd->fd &&
3205 pollrec->fd->events &&
3208 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3209 if (fds[i].revents & G_IO_IN)
3211 if (fds[i].revents & G_IO_OUT)
3213 if (fds[i].revents & G_IO_PRI)
3215 if (fds[i].revents & G_IO_ERR)
3217 if (fds[i].revents & G_IO_HUP)
3219 if (fds[i].revents & G_IO_NVAL)
3225 pollrec = pollrec->next;
3229 UNLOCK_CONTEXT (context);
3232 } /* if (n_fds || timeout != 0) */
3236 * g_main_context_add_poll:
3237 * @context: a #GMainContext (or %NULL for the default context)
3238 * @fd: a #GPollFD structure holding information about a file
3239 * descriptor to watch.
3240 * @priority: the priority for this file descriptor which should be
3241 * the same as the priority used for g_source_attach() to ensure that the
3242 * file descriptor is polled whenever the results may be needed.
3244 * Adds a file descriptor to the set of file descriptors polled for
3245 * this context. This will very seldomly be used directly. Instead
3246 * a typical event source will use g_source_add_poll() instead.
3249 g_main_context_add_poll (GMainContext *context,
3254 context = g_main_context_default ();
3256 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3257 g_return_if_fail (fd);
3259 LOCK_CONTEXT (context);
3260 g_main_context_add_poll_unlocked (context, priority, fd);
3261 UNLOCK_CONTEXT (context);
3264 /* HOLDS: main_loop_lock */
3266 g_main_context_add_poll_unlocked (GMainContext *context,
3270 GPollRec *lastrec, *pollrec;
3271 GPollRec *newrec = g_slice_new (GPollRec);
3273 /* This file descriptor may be checked before we ever poll */
3276 newrec->priority = priority;
3279 pollrec = context->poll_records;
3280 while (pollrec && priority >= pollrec->priority)
3283 pollrec = pollrec->next;
3287 lastrec->next = newrec;
3289 context->poll_records = newrec;
3291 newrec->next = pollrec;
3293 context->n_poll_records++;
3295 #ifdef G_THREADS_ENABLED
3296 context->poll_changed = TRUE;
3298 /* Now wake up the main loop if it is waiting in the poll() */
3299 g_main_context_wakeup_unlocked (context);
3304 * g_main_context_remove_poll:
3305 * @context:a #GMainContext
3306 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3308 * Removes file descriptor from the set of file descriptors to be
3309 * polled for a particular context.
3312 g_main_context_remove_poll (GMainContext *context,
3316 context = g_main_context_default ();
3318 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3319 g_return_if_fail (fd);
3321 LOCK_CONTEXT (context);
3322 g_main_context_remove_poll_unlocked (context, fd);
3323 UNLOCK_CONTEXT (context);
3327 g_main_context_remove_poll_unlocked (GMainContext *context,
3330 GPollRec *pollrec, *lastrec;
3333 pollrec = context->poll_records;
3337 if (pollrec->fd == fd)
3339 if (lastrec != NULL)
3340 lastrec->next = pollrec->next;
3342 context->poll_records = pollrec->next;
3344 g_slice_free (GPollRec, pollrec);
3346 context->n_poll_records--;
3350 pollrec = pollrec->next;
3353 #ifdef G_THREADS_ENABLED
3354 context->poll_changed = TRUE;
3356 /* Now wake up the main loop if it is waiting in the poll() */
3357 g_main_context_wakeup_unlocked (context);
3362 * g_source_get_current_time:
3363 * @source: a #GSource
3364 * @timeval: #GTimeVal structure in which to store current time.
3366 * Gets the "current time" to be used when checking
3367 * this source. The advantage of calling this function over
3368 * calling g_get_current_time() directly is that when
3369 * checking multiple sources, GLib can cache a single value
3370 * instead of having to repeatedly get the system time.
3372 * Deprecated: 2.28: use g_source_get_time() instead
3375 g_source_get_current_time (GSource *source,
3378 GMainContext *context;
3380 g_return_if_fail (source->context != NULL);
3382 context = source->context;
3384 LOCK_CONTEXT (context);
3386 if (!context->current_time_is_fresh)
3388 g_get_current_time (&context->current_time);
3389 context->current_time_is_fresh = TRUE;
3392 *timeval = context->current_time;
3394 UNLOCK_CONTEXT (context);
3398 * g_source_get_time:
3399 * @source: a #GSource
3400 * @timespec: #GTimeSpec structure in which to store the time
3402 * Gets the time to be used when checking this source. The advantage of
3403 * calling this function over calling g_get_monotonic_time() directly is
3404 * that when checking multiple sources, GLib can cache a single value
3405 * instead of having to repeatedly get the system monotonic time.
3407 * The time here is the system monotonic time, if available, or some
3408 * other reasonable alternative otherwise. See g_get_monotonic_time().
3413 g_source_get_time (GSource *source,
3414 GTimeSpec *timespec)
3416 GMainContext *context;
3418 g_return_if_fail (source->context != NULL);
3420 context = source->context;
3422 LOCK_CONTEXT (context);
3424 if (!context->time_is_fresh)
3426 g_get_monotonic_time (&context->time);
3427 context->time_is_fresh = TRUE;
3430 *timespec = context->time;
3432 UNLOCK_CONTEXT (context);
3436 * g_main_context_set_poll_func:
3437 * @context: a #GMainContext
3438 * @func: the function to call to poll all file descriptors
3440 * Sets the function to use to handle polling of file descriptors. It
3441 * will be used instead of the poll() system call
3442 * (or GLib's replacement function, which is used where
3443 * poll() isn't available).
3445 * This function could possibly be used to integrate the GLib event
3446 * loop with an external event loop.
3449 g_main_context_set_poll_func (GMainContext *context,
3453 context = g_main_context_default ();
3455 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3457 LOCK_CONTEXT (context);
3460 context->poll_func = func;
3462 context->poll_func = g_poll;
3464 UNLOCK_CONTEXT (context);
3468 * g_main_context_get_poll_func:
3469 * @context: a #GMainContext
3471 * Gets the poll function set by g_main_context_set_poll_func().
3473 * Return value: the poll function
3476 g_main_context_get_poll_func (GMainContext *context)
3481 context = g_main_context_default ();
3483 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3485 LOCK_CONTEXT (context);
3486 result = context->poll_func;
3487 UNLOCK_CONTEXT (context);
3492 /* HOLDS: context's lock */
3493 /* Wake the main loop up from a poll() */
3495 g_main_context_wakeup_unlocked (GMainContext *context)
3497 #ifdef G_THREADS_ENABLED
3498 if (g_thread_supported() && context->poll_waiting)
3500 context->poll_waiting = FALSE;
3502 write (context->wake_up_pipe[1], "A", 1);
3504 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
3511 * g_main_context_wakeup:
3512 * @context: a #GMainContext
3514 * If @context is currently waiting in a poll(), interrupt
3515 * the poll(), and continue the iteration process.
3518 g_main_context_wakeup (GMainContext *context)
3521 context = g_main_context_default ();
3523 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3525 LOCK_CONTEXT (context);
3526 g_main_context_wakeup_unlocked (context);
3527 UNLOCK_CONTEXT (context);
3531 * g_main_context_is_owner:
3532 * @context: a #GMainContext
3534 * Determines whether this thread holds the (recursive)
3535 * ownership of this #GMaincontext. This is useful to
3536 * know before waiting on another thread that may be
3537 * blocking to get ownership of @context.
3539 * Returns: %TRUE if current thread is owner of @context.
3544 g_main_context_is_owner (GMainContext *context)
3549 context = g_main_context_default ();
3551 #ifdef G_THREADS_ENABLED
3552 LOCK_CONTEXT (context);
3553 is_owner = context->owner == G_THREAD_SELF;
3554 UNLOCK_CONTEXT (context);
3565 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3566 GTimeSpec *current_time)
3568 guint seconds = timeout_source->interval / 1000;
3569 guint msecs = timeout_source->interval - seconds * 1000;
3571 timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
3572 timeout_source->expiration.tv_nsec = current_time->tv_nsec + msecs * 1000000;
3573 if (timeout_source->expiration.tv_nsec >= 1000000000)
3575 timeout_source->expiration.tv_nsec -= 1000000000;
3576 timeout_source->expiration.tv_sec++;
3578 if (timer_perturb==-1)
3581 * we want a per machine/session unique 'random' value; try the dbus
3582 * address first, that has a UUID in it. If there is no dbus, use the
3583 * hostname for hashing.
3585 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3586 if (!session_bus_address)
3587 session_bus_address = g_getenv ("HOSTNAME");
3588 if (session_bus_address)
3589 timer_perturb = ABS ((gint) g_str_hash (session_bus_address));
3593 if (timeout_source->granularity)
3596 gint gran; /* in nsecs */
3599 gran = timeout_source->granularity * 1000000;
3600 perturb = timer_perturb % gran;
3602 * We want to give each machine a per machine pertubation;
3603 * shift time back first, and forward later after the rounding
3606 timeout_source->expiration.tv_nsec -= perturb;
3607 if (timeout_source->expiration.tv_nsec < 0)
3609 timeout_source->expiration.tv_nsec += 1000000000;
3610 timeout_source->expiration.tv_sec--;
3613 remainder = timeout_source->expiration.tv_nsec % gran;
3614 if (remainder >= gran/4) /* round up */
3615 timeout_source->expiration.tv_nsec += gran;
3616 timeout_source->expiration.tv_nsec -= remainder;
3618 timeout_source->expiration.tv_nsec += perturb;
3620 /* the rounding may have overflown tv_nsec */
3621 while (timeout_source->expiration.tv_nsec > 1000000000)
3623 timeout_source->expiration.tv_nsec -= 1000000000;
3624 timeout_source->expiration.tv_sec++;
3630 g_timeout_prepare (GSource *source,
3637 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3639 g_source_get_time (source, &now);
3641 sec = timeout_source->expiration.tv_sec - now.tv_sec;
3642 msec = (timeout_source->expiration.tv_nsec - now.tv_nsec) / 1000000;
3644 /* We do the following in a rather convoluted fashion to deal with
3645 * the fact that we don't have an integral type big enough to hold
3646 * the difference of two timevals in millseconds.
3648 if (sec < 0 || (sec == 0 && msec < 0))
3652 glong interval_sec = timeout_source->interval / 1000;
3653 glong interval_msec = timeout_source->interval % 1000;
3661 if (sec > interval_sec ||
3662 (sec == interval_sec && msec > interval_msec))
3664 /* The system time has been set backwards, so we
3665 * reset the expiration time to now + timeout_source->interval;
3666 * this at least avoids hanging for long periods of time.
3668 g_timeout_set_expiration (timeout_source, &now);
3669 msec = MIN (G_MAXINT, timeout_source->interval);
3673 msec = MIN (G_MAXINT, (guint)msec + 1000 * (guint)sec);
3677 *timeout = (gint)msec;
3683 g_timeout_check (GSource *source)
3686 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3688 g_source_get_time (source, &now);
3690 return ((timeout_source->expiration.tv_sec < now.tv_sec) ||
3691 ((timeout_source->expiration.tv_sec == now.tv_sec) &&
3692 (timeout_source->expiration.tv_nsec <= now.tv_nsec)));
3696 g_timeout_dispatch (GSource *source,
3697 GSourceFunc callback,
3700 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3704 g_warning ("Timeout source dispatched without callback\n"
3705 "You must call g_source_set_callback().");
3709 if (callback (user_data))
3713 g_source_get_time (source, &now);
3714 g_timeout_set_expiration (timeout_source, &now);
3723 * g_timeout_source_new:
3724 * @interval: the timeout interval in milliseconds.
3726 * Creates a new timeout source.
3728 * The source will not initially be associated with any #GMainContext
3729 * and must be added to one with g_source_attach() before it will be
3732 * Return value: the newly-created timeout source
3735 g_timeout_source_new (guint interval)
3737 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3738 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3741 timeout_source->interval = interval;
3743 g_get_monotonic_time (&now);
3744 g_timeout_set_expiration (timeout_source, &now);
3750 * g_timeout_source_new_seconds:
3751 * @interval: the timeout interval in seconds
3753 * Creates a new timeout source.
3755 * The source will not initially be associated with any #GMainContext
3756 * and must be added to one with g_source_attach() before it will be
3759 * The scheduling granularity/accuracy of this timeout source will be
3762 * Return value: the newly-created timeout source
3767 g_timeout_source_new_seconds (guint interval)
3769 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3770 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3773 timeout_source->interval = 1000*interval;
3774 timeout_source->granularity = 1000;
3776 g_get_monotonic_time (&now);
3777 g_timeout_set_expiration (timeout_source, &now);
3784 * g_timeout_add_full:
3785 * @priority: the priority of the timeout source. Typically this will be in
3786 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3787 * @interval: the time between calls to the function, in milliseconds
3788 * (1/1000ths of a second)
3789 * @function: function to call
3790 * @data: data to pass to @function
3791 * @notify: function to call when the timeout is removed, or %NULL
3793 * Sets a function to be called at regular intervals, with the given
3794 * priority. The function is called repeatedly until it returns
3795 * %FALSE, at which point the timeout is automatically destroyed and
3796 * the function will not be called again. The @notify function is
3797 * called when the timeout is destroyed. The first call to the
3798 * function will be at the end of the first @interval.
3800 * Note that timeout functions may be delayed, due to the processing of other
3801 * event sources. Thus they should not be relied on for precise timing.
3802 * After each call to the timeout function, the time of the next
3803 * timeout is recalculated based on the current time and the given interval
3804 * (it does not try to 'catch up' time lost in delays).
3806 * This internally creates a main loop source using g_timeout_source_new()
3807 * and attaches it to the main loop context using g_source_attach(). You can
3808 * do these steps manually if you need greater control.
3810 * Return value: the ID (greater than 0) of the event source.
3813 g_timeout_add_full (gint priority,
3815 GSourceFunc function,
3817 GDestroyNotify notify)
3822 g_return_val_if_fail (function != NULL, 0);
3824 source = g_timeout_source_new (interval);
3826 if (priority != G_PRIORITY_DEFAULT)
3827 g_source_set_priority (source, priority);
3829 g_source_set_callback (source, function, data, notify);
3830 id = g_source_attach (source, NULL);
3831 g_source_unref (source);
3838 * @interval: the time between calls to the function, in milliseconds
3839 * (1/1000ths of a second)
3840 * @function: function to call
3841 * @data: data to pass to @function
3843 * Sets a function to be called at regular intervals, with the default
3844 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
3845 * until it returns %FALSE, at which point the timeout is automatically
3846 * destroyed and the function will not be called again. The first call
3847 * to the function will be at the end of the first @interval.
3849 * Note that timeout functions may be delayed, due to the processing of other
3850 * event sources. Thus they should not be relied on for precise timing.
3851 * After each call to the timeout function, the time of the next
3852 * timeout is recalculated based on the current time and the given interval
3853 * (it does not try to 'catch up' time lost in delays).
3855 * If you want to have a timer in the "seconds" range and do not care
3856 * about the exact time of the first call of the timer, use the
3857 * g_timeout_add_seconds() function; this function allows for more
3858 * optimizations and more efficient system power usage.
3860 * This internally creates a main loop source using g_timeout_source_new()
3861 * and attaches it to the main loop context using g_source_attach(). You can
3862 * do these steps manually if you need greater control.
3864 * Return value: the ID (greater than 0) of the event source.
3867 g_timeout_add (guint32 interval,
3868 GSourceFunc function,
3871 return g_timeout_add_full (G_PRIORITY_DEFAULT,
3872 interval, function, data, NULL);
3876 * g_timeout_add_seconds_full:
3877 * @priority: the priority of the timeout source. Typically this will be in
3878 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3879 * @interval: the time between calls to the function, in seconds
3880 * @function: function to call
3881 * @data: data to pass to @function
3882 * @notify: function to call when the timeout is removed, or %NULL
3884 * Sets a function to be called at regular intervals, with @priority.
3885 * The function is called repeatedly until it returns %FALSE, at which
3886 * point the timeout is automatically destroyed and the function will
3887 * not be called again.
3889 * Unlike g_timeout_add(), this function operates at whole second granularity.
3890 * The initial starting point of the timer is determined by the implementation
3891 * and the implementation is expected to group multiple timers together so that
3892 * they fire all at the same time.
3893 * To allow this grouping, the @interval to the first timer is rounded
3894 * and can deviate up to one second from the specified interval.
3895 * Subsequent timer iterations will generally run at the specified interval.
3897 * Note that timeout functions may be delayed, due to the processing of other
3898 * event sources. Thus they should not be relied on for precise timing.
3899 * After each call to the timeout function, the time of the next
3900 * timeout is recalculated based on the current time and the given @interval
3902 * If you want timing more precise than whole seconds, use g_timeout_add()
3905 * The grouping of timers to fire at the same time results in a more power
3906 * and CPU efficient behavior so if your timer is in multiples of seconds
3907 * and you don't require the first timer exactly one second from now, the
3908 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
3910 * This internally creates a main loop source using
3911 * g_timeout_source_new_seconds() and attaches it to the main loop context
3912 * using g_source_attach(). You can do these steps manually if you need
3915 * Return value: the ID (greater than 0) of the event source.
3920 g_timeout_add_seconds_full (gint priority,
3922 GSourceFunc function,
3924 GDestroyNotify notify)
3929 g_return_val_if_fail (function != NULL, 0);
3931 source = g_timeout_source_new_seconds (interval);
3933 if (priority != G_PRIORITY_DEFAULT)
3934 g_source_set_priority (source, priority);
3936 g_source_set_callback (source, function, data, notify);
3937 id = g_source_attach (source, NULL);
3938 g_source_unref (source);
3944 * g_timeout_add_seconds:
3945 * @interval: the time between calls to the function, in seconds
3946 * @function: function to call
3947 * @data: data to pass to @function
3949 * Sets a function to be called at regular intervals with the default
3950 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
3951 * it returns %FALSE, at which point the timeout is automatically destroyed
3952 * and the function will not be called again.
3954 * This internally creates a main loop source using
3955 * g_timeout_source_new_seconds() and attaches it to the main loop context
3956 * using g_source_attach(). You can do these steps manually if you need
3957 * greater control. Also see g_timout_add_seconds_full().
3959 * Return value: the ID (greater than 0) of the event source.
3964 g_timeout_add_seconds (guint interval,
3965 GSourceFunc function,
3968 g_return_val_if_fail (function != NULL, 0);
3970 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
3973 /* Child watch functions */
3978 g_child_watch_prepare (GSource *source,
3987 g_child_watch_check (GSource *source)
3989 GChildWatchSource *child_watch_source;
3990 gboolean child_exited;
3992 child_watch_source = (GChildWatchSource *) source;
3994 child_exited = child_watch_source->poll.revents & G_IO_IN;
4001 * Note: We do _not_ check for the special value of STILL_ACTIVE
4002 * since we know that the process has exited and doing so runs into
4003 * problems if the child process "happens to return STILL_ACTIVE(259)"
4004 * as Microsoft's Platform SDK puts it.
4006 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4008 gchar *emsg = g_win32_error_message (GetLastError ());
4009 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4012 child_watch_source->child_status = -1;
4015 child_watch_source->child_status = child_status;
4018 return child_exited;
4021 #else /* G_OS_WIN32 */
4024 check_for_child_exited (GSource *source)
4026 GChildWatchSource *child_watch_source;
4029 /* protect against another SIGCHLD in the middle of this call */
4030 count = child_watch_count;
4032 child_watch_source = (GChildWatchSource *) source;
4034 if (child_watch_source->child_exited)
4037 if (child_watch_source->count < count)
4041 if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
4043 child_watch_source->child_status = child_status;
4044 child_watch_source->child_exited = TRUE;
4046 child_watch_source->count = count;
4049 return child_watch_source->child_exited;
4053 g_child_watch_prepare (GSource *source,
4058 return check_for_child_exited (source);
4063 g_child_watch_check (GSource *source)
4065 return check_for_child_exited (source);
4068 #endif /* G_OS_WIN32 */
4071 g_child_watch_dispatch (GSource *source,
4072 GSourceFunc callback,
4075 GChildWatchSource *child_watch_source;
4076 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
4078 child_watch_source = (GChildWatchSource *) source;
4082 g_warning ("Child watch source dispatched without callback\n"
4083 "You must call g_source_set_callback().");
4087 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
4089 /* We never keep a child watch source around as the child is gone */
4096 g_child_watch_signal_handler (int signum)
4098 child_watch_count ++;
4100 if (child_watch_init_state == CHILD_WATCH_INITIALIZED_THREADED)
4102 write (child_watch_wake_up_pipe[1], "B", 1);
4106 /* We count on the signal interrupting the poll in the same thread.
4112 g_child_watch_source_init_single (void)
4114 struct sigaction action;
4116 g_assert (! g_thread_supported());
4117 g_assert (child_watch_init_state == CHILD_WATCH_UNINITIALIZED);
4119 child_watch_init_state = CHILD_WATCH_INITIALIZED_SINGLE;
4121 action.sa_handler = g_child_watch_signal_handler;
4122 sigemptyset (&action.sa_mask);
4123 action.sa_flags = SA_NOCLDSTOP;
4124 sigaction (SIGCHLD, &action, NULL);
4127 G_GNUC_NORETURN static gpointer
4128 child_watch_helper_thread (gpointer data)
4135 read (child_watch_wake_up_pipe[0], b, 20);
4137 /* We were woken up. Wake up all other contexts in all other threads */
4138 G_LOCK (main_context_list);
4139 for (list = main_context_list; list; list = list->next)
4141 GMainContext *context;
4143 context = list->data;
4144 if (g_atomic_int_get (&context->ref_count) > 0)
4145 /* Due to racing conditions we can find ref_count == 0, in
4146 * that case, however, the context is still not destroyed
4147 * and no poll can be active, otherwise the ref_count
4149 g_main_context_wakeup (context);
4151 G_UNLOCK (main_context_list);
4156 g_child_watch_source_init_multi_threaded (void)
4158 GError *error = NULL;
4159 struct sigaction action;
4161 g_assert (g_thread_supported());
4163 if (pipe (child_watch_wake_up_pipe) < 0)
4164 g_error ("Cannot create wake up pipe: %s\n", g_strerror (errno));
4165 fcntl (child_watch_wake_up_pipe[1], F_SETFL, O_NONBLOCK | fcntl (child_watch_wake_up_pipe[1], F_GETFL));
4167 /* We create a helper thread that polls on the wakeup pipe indefinitely */
4168 /* FIXME: Think this through for races */
4169 if (g_thread_create (child_watch_helper_thread, NULL, FALSE, &error) == NULL)
4170 g_error ("Cannot create a thread to monitor child exit status: %s\n", error->message);
4171 child_watch_init_state = CHILD_WATCH_INITIALIZED_THREADED;
4173 action.sa_handler = g_child_watch_signal_handler;
4174 sigemptyset (&action.sa_mask);
4175 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4176 sigaction (SIGCHLD, &action, NULL);
4180 g_child_watch_source_init_promote_single_to_threaded (void)
4182 g_child_watch_source_init_multi_threaded ();
4186 g_child_watch_source_init (void)
4188 if (g_thread_supported())
4190 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
4191 g_child_watch_source_init_multi_threaded ();
4192 else if (child_watch_init_state == CHILD_WATCH_INITIALIZED_SINGLE)
4193 g_child_watch_source_init_promote_single_to_threaded ();
4197 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
4198 g_child_watch_source_init_single ();
4202 #endif /* !G_OS_WIN32 */
4205 * g_child_watch_source_new:
4206 * @pid: process to watch. On POSIX the pid of a child process. On
4207 * Windows a handle for a process (which doesn't have to be a child).
4209 * Creates a new child_watch source.
4211 * The source will not initially be associated with any #GMainContext
4212 * and must be added to one with g_source_attach() before it will be
4215 * Note that child watch sources can only be used in conjunction with
4216 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4219 * Note that on platforms where #GPid must be explicitly closed
4220 * (see g_spawn_close_pid()) @pid must not be closed while the
4221 * source is still active. Typically, you will want to call
4222 * g_spawn_close_pid() in the callback function for the source.
4224 * Note further that using g_child_watch_source_new() is not
4225 * compatible with calling <literal>waitpid(-1)</literal> in
4226 * the application. Calling waitpid() for individual pids will
4229 * Return value: the newly-created child watch source
4234 g_child_watch_source_new (GPid pid)
4236 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4237 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4240 child_watch_source->poll.fd = (gintptr) pid;
4241 child_watch_source->poll.events = G_IO_IN;
4243 g_source_add_poll (source, &child_watch_source->poll);
4244 #else /* G_OS_WIN32 */
4245 g_child_watch_source_init ();
4246 #endif /* G_OS_WIN32 */
4248 child_watch_source->pid = pid;
4254 * g_child_watch_add_full:
4255 * @priority: the priority of the idle source. Typically this will be in the
4256 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4257 * @pid: process to watch. On POSIX the pid of a child process. On
4258 * Windows a handle for a process (which doesn't have to be a child).
4259 * @function: function to call
4260 * @data: data to pass to @function
4261 * @notify: function to call when the idle is removed, or %NULL
4263 * Sets a function to be called when the child indicated by @pid
4264 * exits, at the priority @priority.
4266 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4267 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4268 * the spawn function for the child watching to work.
4270 * Note that on platforms where #GPid must be explicitly closed
4271 * (see g_spawn_close_pid()) @pid must not be closed while the
4272 * source is still active. Typically, you will want to call
4273 * g_spawn_close_pid() in the callback function for the source.
4275 * GLib supports only a single callback per process id.
4277 * This internally creates a main loop source using
4278 * g_child_watch_source_new() and attaches it to the main loop context
4279 * using g_source_attach(). You can do these steps manually if you
4280 * need greater control.
4282 * Return value: the ID (greater than 0) of the event source.
4287 g_child_watch_add_full (gint priority,
4289 GChildWatchFunc function,
4291 GDestroyNotify notify)
4296 g_return_val_if_fail (function != NULL, 0);
4298 source = g_child_watch_source_new (pid);
4300 if (priority != G_PRIORITY_DEFAULT)
4301 g_source_set_priority (source, priority);
4303 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4304 id = g_source_attach (source, NULL);
4305 g_source_unref (source);
4311 * g_child_watch_add:
4312 * @pid: process id to watch. On POSIX the pid of a child process. On
4313 * Windows a handle for a process (which doesn't have to be a child).
4314 * @function: function to call
4315 * @data: data to pass to @function
4317 * Sets a function to be called when the child indicated by @pid
4318 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4320 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4321 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4322 * the spawn function for the child watching to work.
4324 * Note that on platforms where #GPid must be explicitly closed
4325 * (see g_spawn_close_pid()) @pid must not be closed while the
4326 * source is still active. Typically, you will want to call
4327 * g_spawn_close_pid() in the callback function for the source.
4329 * GLib supports only a single callback per process id.
4331 * This internally creates a main loop source using
4332 * g_child_watch_source_new() and attaches it to the main loop context
4333 * using g_source_attach(). You can do these steps manually if you
4334 * need greater control.
4336 * Return value: the ID (greater than 0) of the event source.
4341 g_child_watch_add (GPid pid,
4342 GChildWatchFunc function,
4345 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4349 /* Idle functions */
4352 g_idle_prepare (GSource *source,
4361 g_idle_check (GSource *source)
4367 g_idle_dispatch (GSource *source,
4368 GSourceFunc callback,
4373 g_warning ("Idle source dispatched without callback\n"
4374 "You must call g_source_set_callback().");
4378 return callback (user_data);
4382 * g_idle_source_new:
4384 * Creates a new idle source.
4386 * The source will not initially be associated with any #GMainContext
4387 * and must be added to one with g_source_attach() before it will be
4388 * executed. Note that the default priority for idle sources is
4389 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4390 * have a default priority of %G_PRIORITY_DEFAULT.
4392 * Return value: the newly-created idle source
4395 g_idle_source_new (void)
4399 source = g_source_new (&g_idle_funcs, sizeof (GSource));
4400 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4407 * @priority: the priority of the idle source. Typically this will be in the
4408 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4409 * @function: function to call
4410 * @data: data to pass to @function
4411 * @notify: function to call when the idle is removed, or %NULL
4413 * Adds a function to be called whenever there are no higher priority
4414 * events pending. If the function returns %FALSE it is automatically
4415 * removed from the list of event sources and will not be called again.
4417 * This internally creates a main loop source using g_idle_source_new()
4418 * and attaches it to the main loop context using g_source_attach().
4419 * You can do these steps manually if you need greater control.
4421 * Return value: the ID (greater than 0) of the event source.
4424 g_idle_add_full (gint priority,
4425 GSourceFunc function,
4427 GDestroyNotify notify)
4432 g_return_val_if_fail (function != NULL, 0);
4434 source = g_idle_source_new ();
4436 if (priority != G_PRIORITY_DEFAULT_IDLE)
4437 g_source_set_priority (source, priority);
4439 g_source_set_callback (source, function, data, notify);
4440 id = g_source_attach (source, NULL);
4441 g_source_unref (source);
4448 * @function: function to call
4449 * @data: data to pass to @function.
4451 * Adds a function to be called whenever there are no higher priority
4452 * events pending to the default main loop. The function is given the
4453 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4454 * returns %FALSE it is automatically removed from the list of event
4455 * sources and will not be called again.
4457 * This internally creates a main loop source using g_idle_source_new()
4458 * and attaches it to the main loop context using g_source_attach().
4459 * You can do these steps manually if you need greater control.
4461 * Return value: the ID (greater than 0) of the event source.
4464 g_idle_add (GSourceFunc function,
4467 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4471 * g_idle_remove_by_data:
4472 * @data: the data for the idle source's callback.
4474 * Removes the idle function with the given data.
4476 * Return value: %TRUE if an idle source was found and removed.
4479 g_idle_remove_by_data (gpointer data)
4481 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4485 * g_main_context_invoke:
4486 * @context: a #GMainContext, or %NULL
4487 * @function: function to call
4488 * @data: data to pass to @function
4490 * Invokes a function in such a way that @context is owned during the
4491 * invocation of @function.
4493 * If @context is %NULL then the global default main context — as
4494 * returned by g_main_context_default() — is used.
4496 * If @context is owned by the current thread, @function is called
4497 * directly. Otherwise, if @context is the thread-default main context
4498 * of the current thread and g_main_context_acquire() succeeds, then
4499 * @function is called and g_main_context_release() is called
4502 * In any other case, an idle source is created to call @function and
4503 * that source is attached to @context (presumably to be run in another
4504 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
4505 * priority. If you want a different priority, use
4506 * g_main_context_invoke_full().
4508 * Note that, as with normal idle functions, @function should probably
4509 * return %FALSE. If it returns %TRUE, it will be continuously run in a
4510 * loop (and may prevent this call from returning).
4515 g_main_context_invoke (GMainContext *context,
4516 GSourceFunc function,
4519 g_main_context_invoke_full (context,
4521 function, data, NULL);
4525 * g_main_context_invoke_full:
4526 * @context: a #GMainContext, or %NULL
4527 * @priority: the priority at which to run @function
4528 * @function: function to call
4529 * @data: data to pass to @function
4530 * @notify: a function to call when @data is no longer in use, or %NULL.
4532 * Invokes a function in such a way that @context is owned during the
4533 * invocation of @function.
4535 * This function is the same as g_main_context_invoke() except that it
4536 * lets you specify the priority incase @function ends up being
4537 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
4539 * @notify should not assume that it is called from any particular
4540 * thread or with any particular context acquired.
4545 g_main_context_invoke_full (GMainContext *context,
4547 GSourceFunc function,
4549 GDestroyNotify notify)
4551 g_return_if_fail (function != NULL);
4554 context = g_main_context_default ();
4556 if (g_main_context_is_owner (context))
4558 while (function (data));
4565 GMainContext *thread_default;
4567 thread_default = g_main_context_get_thread_default ();
4569 if (!thread_default)
4570 thread_default = g_main_context_default ();
4572 if (thread_default == context && g_main_context_acquire (context))
4574 while (function (data));
4576 g_main_context_release (context);
4585 source = g_idle_source_new ();
4586 g_source_set_priority (source, priority);
4587 g_source_set_callback (source, function, data, notify);
4588 g_source_attach (source, context);
4589 g_source_unref (source);