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 */
267 GTimeVal current_time;
268 gboolean time_is_current;
271 struct _GSourceCallback
276 GDestroyNotify notify;
281 GMainContext *context;
286 struct _GTimeoutSource
294 struct _GChildWatchSource
301 #else /* G_OS_WIN32 */
303 gboolean child_exited;
304 #endif /* G_OS_WIN32 */
314 #ifdef G_THREADS_ENABLED
315 #define LOCK_CONTEXT(context) g_static_mutex_lock (&context->mutex)
316 #define UNLOCK_CONTEXT(context) g_static_mutex_unlock (&context->mutex)
317 #define G_THREAD_SELF g_thread_self ()
319 #define LOCK_CONTEXT(context) (void)0
320 #define UNLOCK_CONTEXT(context) (void)0
321 #define G_THREAD_SELF NULL
324 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
325 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
326 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
328 #define SOURCE_UNREF(source, context) \
330 if ((source)->ref_count > 1) \
331 (source)->ref_count--; \
333 g_source_unref_internal ((source), (context), TRUE); \
337 /* Forward declarations */
339 static void g_source_unref_internal (GSource *source,
340 GMainContext *context,
342 static void g_source_destroy_internal (GSource *source,
343 GMainContext *context,
345 static void g_main_context_poll (GMainContext *context,
350 static void g_main_context_add_poll_unlocked (GMainContext *context,
353 static void g_main_context_remove_poll_unlocked (GMainContext *context,
355 static void g_main_context_wakeup_unlocked (GMainContext *context);
357 static gboolean g_timeout_prepare (GSource *source,
359 static gboolean g_timeout_check (GSource *source);
360 static gboolean g_timeout_dispatch (GSource *source,
361 GSourceFunc callback,
363 static gboolean g_child_watch_prepare (GSource *source,
365 static gboolean g_child_watch_check (GSource *source);
366 static gboolean g_child_watch_dispatch (GSource *source,
367 GSourceFunc callback,
369 static gboolean g_idle_prepare (GSource *source,
371 static gboolean g_idle_check (GSource *source);
372 static gboolean g_idle_dispatch (GSource *source,
373 GSourceFunc callback,
376 G_LOCK_DEFINE_STATIC (main_loop);
377 static GMainContext *default_main_context;
378 static GSList *main_contexts_without_pipe = NULL;
381 /* Child status monitoring code */
383 CHILD_WATCH_UNINITIALIZED,
384 CHILD_WATCH_INITIALIZED_SINGLE,
385 CHILD_WATCH_INITIALIZED_THREADED
387 static gint child_watch_init_state = CHILD_WATCH_UNINITIALIZED;
388 static gint child_watch_count = 1;
389 static gint child_watch_wake_up_pipe[2] = {0, 0};
390 #endif /* !G_OS_WIN32 */
391 G_LOCK_DEFINE_STATIC (main_context_list);
392 static GSList *main_context_list = NULL;
394 static gint timer_perturb = -1;
396 GSourceFuncs g_timeout_funcs =
404 GSourceFuncs g_child_watch_funcs =
406 g_child_watch_prepare,
408 g_child_watch_dispatch,
412 GSourceFuncs g_idle_funcs =
421 * g_main_context_ref:
422 * @context: a #GMainContext
424 * Increases the reference count on a #GMainContext object by one.
426 * Returns: the @context that was passed in (since 2.6)
429 g_main_context_ref (GMainContext *context)
431 g_return_val_if_fail (context != NULL, NULL);
432 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
434 g_atomic_int_inc (&context->ref_count);
440 poll_rec_list_free (GMainContext *context,
443 g_slice_free_chain (GPollRec, list, next);
447 * g_main_context_unref:
448 * @context: a #GMainContext
450 * Decreases the reference count on a #GMainContext object by one. If
451 * the result is zero, free the context and free all associated memory.
454 g_main_context_unref (GMainContext *context)
457 g_return_if_fail (context != NULL);
458 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
460 if (!g_atomic_int_dec_and_test (&context->ref_count))
463 G_LOCK (main_context_list);
464 main_context_list = g_slist_remove (main_context_list, context);
465 G_UNLOCK (main_context_list);
467 source = context->source_list;
470 GSource *next = source->next;
471 g_source_destroy_internal (source, context, FALSE);
475 #ifdef G_THREADS_ENABLED
476 g_static_mutex_free (&context->mutex);
479 g_ptr_array_free (context->pending_dispatches, TRUE);
480 g_free (context->cached_poll_array);
482 poll_rec_list_free (context, context->poll_records);
484 #ifdef G_THREADS_ENABLED
485 if (g_thread_supported())
488 close (context->wake_up_pipe[0]);
489 close (context->wake_up_pipe[1]);
491 CloseHandle (context->wake_up_semaphore);
495 main_contexts_without_pipe = g_slist_remove (main_contexts_without_pipe,
498 if (context->cond != NULL)
499 g_cond_free (context->cond);
505 #ifdef G_THREADS_ENABLED
507 g_main_context_init_pipe (GMainContext *context)
510 if (context->wake_up_pipe[0] != -1)
514 /* if this fails, we fall through and try pipe */
515 pipe2 (context->wake_up_pipe, O_CLOEXEC);
517 if (context->wake_up_pipe[0] == -1)
519 if (pipe (context->wake_up_pipe) < 0)
520 g_error ("Cannot create pipe main loop wake-up: %s\n",
523 fcntl (context->wake_up_pipe[0], F_SETFD, FD_CLOEXEC);
524 fcntl (context->wake_up_pipe[1], F_SETFD, FD_CLOEXEC);
527 context->wake_up_rec.fd = context->wake_up_pipe[0];
528 context->wake_up_rec.events = G_IO_IN;
530 if (context->wake_up_semaphore != NULL)
532 context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
533 if (context->wake_up_semaphore == NULL)
534 g_error ("Cannot create wake-up semaphore: %s",
535 g_win32_error_message (GetLastError ()));
536 context->wake_up_rec.fd = (gintptr) context->wake_up_semaphore;
537 context->wake_up_rec.events = G_IO_IN;
539 if (_g_main_poll_debug)
540 g_print ("wake-up semaphore: %p\n", context->wake_up_semaphore);
542 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
546 _g_main_thread_init (void)
548 GSList *curr = main_contexts_without_pipe;
551 g_main_context_init_pipe ((GMainContext *)curr->data);
554 g_slist_free (main_contexts_without_pipe);
555 main_contexts_without_pipe = NULL;
557 #endif /* G_THREADS_ENABLED */
560 * g_main_context_new:
562 * Creates a new #GMainContext structure.
564 * Return value: the new #GMainContext
567 g_main_context_new (void)
569 GMainContext *context = g_new0 (GMainContext, 1);
571 #ifdef G_MAIN_POLL_DEBUG
573 static gboolean beenhere = FALSE;
577 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
578 _g_main_poll_debug = TRUE;
584 #ifdef G_THREADS_ENABLED
585 g_static_mutex_init (&context->mutex);
587 context->owner = NULL;
588 context->waiters = NULL;
591 context->wake_up_pipe[0] = -1;
592 context->wake_up_pipe[1] = -1;
594 context->wake_up_semaphore = NULL;
598 context->ref_count = 1;
600 context->next_id = 1;
602 context->source_list = NULL;
604 context->poll_func = g_poll;
606 context->cached_poll_array = NULL;
607 context->cached_poll_array_size = 0;
609 context->pending_dispatches = g_ptr_array_new ();
611 context->time_is_current = FALSE;
613 #ifdef G_THREADS_ENABLED
614 if (g_thread_supported ())
615 g_main_context_init_pipe (context);
617 main_contexts_without_pipe = g_slist_prepend (main_contexts_without_pipe,
621 G_LOCK (main_context_list);
622 main_context_list = g_slist_append (main_context_list, context);
624 #ifdef G_MAIN_POLL_DEBUG
625 if (_g_main_poll_debug)
626 g_print ("created context=%p\n", context);
629 G_UNLOCK (main_context_list);
635 * g_main_context_default:
637 * Returns the global default main context. This is the main context
638 * used for main loop functions when a main loop is not explicitly
639 * specified, and corresponds to the "main" main loop. See also
640 * g_main_context_get_thread_default().
642 * Return value: the global default main context.
645 g_main_context_default (void)
651 if (!default_main_context)
653 default_main_context = g_main_context_new ();
654 #ifdef G_MAIN_POLL_DEBUG
655 if (_g_main_poll_debug)
656 g_print ("default context=%p\n", default_main_context);
660 G_UNLOCK (main_loop);
662 return default_main_context;
665 static GStaticPrivate thread_context_stack = G_STATIC_PRIVATE_INIT;
668 free_context_stack (gpointer data)
670 GQueue *stack = data;
671 GMainContext *context;
673 while (!g_queue_is_empty (stack))
675 context = g_queue_pop_head (stack);
676 g_main_context_release (context);
678 g_main_context_unref (context);
680 g_queue_free (stack);
684 * g_main_context_push_thread_default:
685 * @context: a #GMainContext, or %NULL for the global default context
687 * Acquires @context and sets it as the thread-default context for the
688 * current thread. This will cause certain asynchronous operations
689 * (such as most <link linkend="gio">gio</link>-based I/O) which are
690 * started in this thread to run under @context and deliver their
691 * results to its main loop, rather than running under the global
692 * default context in the main thread. Note that calling this function
693 * changes the context returned by
694 * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
695 * one returned by g_main_context_default(), so it does not affect the
696 * context used by functions like g_idle_add().
698 * Normally you would call this function shortly after creating a new
699 * thread, passing it a #GMainContext which will be run by a
700 * #GMainLoop in that thread, to set a new default context for all
701 * async operations in that thread. (In this case, you don't need to
702 * ever call g_main_context_pop_thread_default().) In some cases
703 * however, you may want to schedule a single operation in a
704 * non-default context, or temporarily use a non-default context in
705 * the main thread. In that case, you can wrap the call to the
706 * asynchronous operation inside a
707 * g_main_context_push_thread_default() /
708 * g_main_context_pop_thread_default() pair, but it is up to you to
709 * ensure that no other asynchronous operations accidentally get
710 * started while the non-default context is active.
712 * Beware that libraries that predate this function may not correctly
713 * handle being used from a thread with a thread-default context. Eg,
714 * see g_file_supports_thread_contexts().
719 g_main_context_push_thread_default (GMainContext *context)
722 gboolean acquired_context;
724 acquired_context = g_main_context_acquire (context);
725 g_return_if_fail (acquired_context);
727 if (context == g_main_context_default ())
730 g_main_context_ref (context);
732 stack = g_static_private_get (&thread_context_stack);
735 stack = g_queue_new ();
736 g_static_private_set (&thread_context_stack, stack,
740 g_queue_push_head (stack, context);
744 * g_main_context_pop_thread_default:
745 * @context: a #GMainContext object, or %NULL
747 * Pops @context off the thread-default context stack (verifying that
748 * it was on the top of the stack).
753 g_main_context_pop_thread_default (GMainContext *context)
757 if (context == g_main_context_default ())
760 stack = g_static_private_get (&thread_context_stack);
762 g_return_if_fail (stack != NULL);
763 g_return_if_fail (g_queue_peek_head (stack) == context);
765 g_queue_pop_head (stack);
767 g_main_context_release (context);
769 g_main_context_unref (context);
773 * g_main_context_get_thread_default:
775 * Gets the thread-default #GMainContext for this thread. Asynchronous
776 * operations that want to be able to be run in contexts other than
777 * the default one should call this method to get a #GMainContext to
778 * add their #GSource<!-- -->s to. (Note that even in single-threaded
779 * programs applications may sometimes want to temporarily push a
780 * non-default context, so it is not safe to assume that this will
781 * always return %NULL if threads are not initialized.)
783 * Returns: the thread-default #GMainContext, or %NULL if the
784 * thread-default context is the global default context.
789 g_main_context_get_thread_default (void)
793 stack = g_static_private_get (&thread_context_stack);
795 return g_queue_peek_head (stack);
800 /* Hooks for adding to the main loop */
804 * @source_funcs: structure containing functions that implement
805 * the sources behavior.
806 * @struct_size: size of the #GSource structure to create.
808 * Creates a new #GSource structure. The size is specified to
809 * allow creating structures derived from #GSource that contain
810 * additional data. The size passed in must be at least
811 * <literal>sizeof (GSource)</literal>.
813 * The source will not initially be associated with any #GMainContext
814 * and must be added to one with g_source_attach() before it will be
817 * Return value: the newly-created #GSource.
820 g_source_new (GSourceFuncs *source_funcs,
825 g_return_val_if_fail (source_funcs != NULL, NULL);
826 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
828 source = (GSource*) g_malloc0 (struct_size);
830 source->source_funcs = source_funcs;
831 source->ref_count = 1;
833 source->priority = G_PRIORITY_DEFAULT;
835 source->flags = G_HOOK_FLAG_ACTIVE;
837 /* NULL/0 initialization for all other fields */
842 /* Holds context's lock
845 g_source_list_add (GSource *source,
846 GMainContext *context)
848 GSource *tmp_source, *last_source;
851 tmp_source = context->source_list;
852 while (tmp_source && tmp_source->priority <= source->priority)
854 last_source = tmp_source;
855 tmp_source = tmp_source->next;
858 source->next = tmp_source;
860 tmp_source->prev = source;
862 source->prev = last_source;
864 last_source->next = source;
866 context->source_list = source;
869 /* Holds context's lock
872 g_source_list_remove (GSource *source,
873 GMainContext *context)
876 source->prev->next = source->next;
878 context->source_list = source->next;
881 source->next->prev = source->prev;
889 * @source: a #GSource
890 * @context: a #GMainContext (if %NULL, the default context will be used)
892 * Adds a #GSource to a @context so that it will be executed within
893 * that context. Remove it by calling g_source_destroy().
895 * Return value: the ID (greater than 0) for the source within the
899 g_source_attach (GSource *source,
900 GMainContext *context)
905 g_return_val_if_fail (source->context == NULL, 0);
906 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
909 context = g_main_context_default ();
911 LOCK_CONTEXT (context);
913 source->context = context;
914 result = source->source_id = context->next_id++;
917 g_source_list_add (source, context);
919 tmp_list = source->poll_fds;
922 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
923 tmp_list = tmp_list->next;
926 #ifdef G_THREADS_ENABLED
927 /* Now wake up the main loop if it is waiting in the poll() */
928 g_main_context_wakeup_unlocked (context);
931 UNLOCK_CONTEXT (context);
937 g_source_destroy_internal (GSource *source,
938 GMainContext *context,
942 LOCK_CONTEXT (context);
944 if (!SOURCE_DESTROYED (source))
947 gpointer old_cb_data;
948 GSourceCallbackFuncs *old_cb_funcs;
950 source->flags &= ~G_HOOK_FLAG_ACTIVE;
952 old_cb_data = source->callback_data;
953 old_cb_funcs = source->callback_funcs;
955 source->callback_data = NULL;
956 source->callback_funcs = NULL;
960 UNLOCK_CONTEXT (context);
961 old_cb_funcs->unref (old_cb_data);
962 LOCK_CONTEXT (context);
965 if (!SOURCE_BLOCKED (source))
967 tmp_list = source->poll_fds;
970 g_main_context_remove_poll_unlocked (context, tmp_list->data);
971 tmp_list = tmp_list->next;
975 g_source_unref_internal (source, context, TRUE);
979 UNLOCK_CONTEXT (context);
984 * @source: a #GSource
986 * Removes a source from its #GMainContext, if any, and mark it as
987 * destroyed. The source cannot be subsequently added to another
991 g_source_destroy (GSource *source)
993 GMainContext *context;
995 g_return_if_fail (source != NULL);
997 context = source->context;
1000 g_source_destroy_internal (source, context, FALSE);
1002 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1007 * @source: a #GSource
1009 * Returns the numeric ID for a particular source. The ID of a source
1010 * is a positive integer which is unique within a particular main loop
1011 * context. The reverse
1012 * mapping from ID to source is done by g_main_context_find_source_by_id().
1014 * Return value: the ID (greater than 0) for the source
1017 g_source_get_id (GSource *source)
1021 g_return_val_if_fail (source != NULL, 0);
1022 g_return_val_if_fail (source->context != NULL, 0);
1024 LOCK_CONTEXT (source->context);
1025 result = source->source_id;
1026 UNLOCK_CONTEXT (source->context);
1032 * g_source_get_context:
1033 * @source: a #GSource
1035 * Gets the #GMainContext with which the source is associated.
1036 * Calling this function on a destroyed source is an error.
1038 * Return value: the #GMainContext with which the source is associated,
1039 * or %NULL if the context has not yet been added
1043 g_source_get_context (GSource *source)
1045 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1047 return source->context;
1051 * g_source_add_poll:
1052 * @source:a #GSource
1053 * @fd: a #GPollFD structure holding information about a file
1054 * descriptor to watch.
1056 * Adds a file descriptor to the set of file descriptors polled for
1057 * this source. This is usually combined with g_source_new() to add an
1058 * event source. The event source's check function will typically test
1059 * the @revents field in the #GPollFD struct and return %TRUE if events need
1063 g_source_add_poll (GSource *source,
1066 GMainContext *context;
1068 g_return_if_fail (source != NULL);
1069 g_return_if_fail (fd != NULL);
1070 g_return_if_fail (!SOURCE_DESTROYED (source));
1072 context = source->context;
1075 LOCK_CONTEXT (context);
1077 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1081 if (!SOURCE_BLOCKED (source))
1082 g_main_context_add_poll_unlocked (context, source->priority, fd);
1083 UNLOCK_CONTEXT (context);
1088 * g_source_remove_poll:
1089 * @source:a #GSource
1090 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1092 * Removes a file descriptor from the set of file descriptors polled for
1096 g_source_remove_poll (GSource *source,
1099 GMainContext *context;
1101 g_return_if_fail (source != NULL);
1102 g_return_if_fail (fd != NULL);
1103 g_return_if_fail (!SOURCE_DESTROYED (source));
1105 context = source->context;
1108 LOCK_CONTEXT (context);
1110 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1114 if (!SOURCE_BLOCKED (source))
1115 g_main_context_remove_poll_unlocked (context, fd);
1116 UNLOCK_CONTEXT (context);
1121 * g_source_set_callback_indirect:
1122 * @source: the source
1123 * @callback_data: pointer to callback data "object"
1124 * @callback_funcs: functions for reference counting @callback_data
1125 * and getting the callback and data
1127 * Sets the callback function storing the data as a refcounted callback
1128 * "object". This is used internally. Note that calling
1129 * g_source_set_callback_indirect() assumes
1130 * an initial reference count on @callback_data, and thus
1131 * @callback_funcs->unref will eventually be called once more
1132 * than @callback_funcs->ref.
1135 g_source_set_callback_indirect (GSource *source,
1136 gpointer callback_data,
1137 GSourceCallbackFuncs *callback_funcs)
1139 GMainContext *context;
1140 gpointer old_cb_data;
1141 GSourceCallbackFuncs *old_cb_funcs;
1143 g_return_if_fail (source != NULL);
1144 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1146 context = source->context;
1149 LOCK_CONTEXT (context);
1151 old_cb_data = source->callback_data;
1152 old_cb_funcs = source->callback_funcs;
1154 source->callback_data = callback_data;
1155 source->callback_funcs = callback_funcs;
1158 UNLOCK_CONTEXT (context);
1161 old_cb_funcs->unref (old_cb_data);
1165 g_source_callback_ref (gpointer cb_data)
1167 GSourceCallback *callback = cb_data;
1169 callback->ref_count++;
1174 g_source_callback_unref (gpointer cb_data)
1176 GSourceCallback *callback = cb_data;
1178 callback->ref_count--;
1179 if (callback->ref_count == 0)
1181 if (callback->notify)
1182 callback->notify (callback->data);
1188 g_source_callback_get (gpointer cb_data,
1193 GSourceCallback *callback = cb_data;
1195 *func = callback->func;
1196 *data = callback->data;
1199 static GSourceCallbackFuncs g_source_callback_funcs = {
1200 g_source_callback_ref,
1201 g_source_callback_unref,
1202 g_source_callback_get,
1206 * g_source_set_callback:
1207 * @source: the source
1208 * @func: a callback function
1209 * @data: the data to pass to callback function
1210 * @notify: a function to call when @data is no longer in use, or %NULL.
1212 * Sets the callback function for a source. The callback for a source is
1213 * called from the source's dispatch function.
1215 * The exact type of @func depends on the type of source; ie. you
1216 * should not count on @func being called with @data as its first
1219 * Typically, you won't use this function. Instead use functions specific
1220 * to the type of source you are using.
1223 g_source_set_callback (GSource *source,
1226 GDestroyNotify notify)
1228 GSourceCallback *new_callback;
1230 g_return_if_fail (source != NULL);
1232 new_callback = g_new (GSourceCallback, 1);
1234 new_callback->ref_count = 1;
1235 new_callback->func = func;
1236 new_callback->data = data;
1237 new_callback->notify = notify;
1239 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1244 * g_source_set_funcs:
1245 * @source: a #GSource
1246 * @funcs: the new #GSourceFuncs
1248 * Sets the source functions (can be used to override
1249 * default implementations) of an unattached source.
1254 g_source_set_funcs (GSource *source,
1255 GSourceFuncs *funcs)
1257 g_return_if_fail (source != NULL);
1258 g_return_if_fail (source->context == NULL);
1259 g_return_if_fail (source->ref_count > 0);
1260 g_return_if_fail (funcs != NULL);
1262 source->source_funcs = funcs;
1266 * g_source_set_priority:
1267 * @source: a #GSource
1268 * @priority: the new priority.
1270 * Sets the priority of a source. While the main loop is being
1271 * run, a source will be dispatched if it is ready to be dispatched and no sources
1272 * at a higher (numerically smaller) priority are ready to be dispatched.
1275 g_source_set_priority (GSource *source,
1279 GMainContext *context;
1281 g_return_if_fail (source != NULL);
1283 context = source->context;
1286 LOCK_CONTEXT (context);
1288 source->priority = priority;
1292 /* Remove the source from the context's source and then
1293 * add it back so it is sorted in the correct plcae
1295 g_source_list_remove (source, source->context);
1296 g_source_list_add (source, source->context);
1298 if (!SOURCE_BLOCKED (source))
1300 tmp_list = source->poll_fds;
1303 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1304 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1306 tmp_list = tmp_list->next;
1310 UNLOCK_CONTEXT (source->context);
1315 * g_source_get_priority:
1316 * @source: a #GSource
1318 * Gets the priority of a source.
1320 * Return value: the priority of the source
1323 g_source_get_priority (GSource *source)
1325 g_return_val_if_fail (source != NULL, 0);
1327 return source->priority;
1331 * g_source_set_can_recurse:
1332 * @source: a #GSource
1333 * @can_recurse: whether recursion is allowed for this source
1335 * Sets whether a source can be called recursively. If @can_recurse is
1336 * %TRUE, then while the source is being dispatched then this source
1337 * will be processed normally. Otherwise, all processing of this
1338 * source is blocked until the dispatch function returns.
1341 g_source_set_can_recurse (GSource *source,
1342 gboolean can_recurse)
1344 GMainContext *context;
1346 g_return_if_fail (source != NULL);
1348 context = source->context;
1351 LOCK_CONTEXT (context);
1354 source->flags |= G_SOURCE_CAN_RECURSE;
1356 source->flags &= ~G_SOURCE_CAN_RECURSE;
1359 UNLOCK_CONTEXT (context);
1363 * g_source_get_can_recurse:
1364 * @source: a #GSource
1366 * Checks whether a source is allowed to be called recursively.
1367 * see g_source_set_can_recurse().
1369 * Return value: whether recursion is allowed.
1372 g_source_get_can_recurse (GSource *source)
1374 g_return_val_if_fail (source != NULL, FALSE);
1376 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1381 * g_source_set_name:
1382 * @source: a #GSource
1383 * @name: debug name for the source
1385 * Sets a name for the source, used in debugging and profiling.
1386 * The name defaults to #NULL.
1388 * The source name should describe in a human-readable way
1389 * what the source does. For example, "X11 event queue"
1390 * or "GTK+ repaint idle handler" or whatever it is.
1392 * It is permitted to call this function multiple times, but is not
1393 * recommended due to the potential performance impact. For example,
1394 * one could change the name in the "check" function of a #GSourceFuncs
1395 * to include details like the event type in the source name.
1400 g_source_set_name (GSource *source,
1403 g_return_if_fail (source != NULL);
1405 /* setting back to NULL is allowed, just because it's
1406 * weird if get_name can return NULL but you can't
1410 g_free (source->name);
1411 source->name = g_strdup (name);
1415 * g_source_get_name:
1416 * @source: a #GSource
1418 * Gets a name for the source, used in debugging and profiling.
1419 * The name may be #NULL if it has never been set with
1420 * g_source_set_name().
1422 * Return value: the name of the source
1425 G_CONST_RETURN char*
1426 g_source_get_name (GSource *source)
1428 g_return_val_if_fail (source != NULL, NULL);
1430 return source->name;
1434 * g_source_set_name_by_id:
1435 * @tag: a #GSource ID
1436 * @name: debug name for the source
1438 * Sets the name of a source using its ID.
1440 * This is a convenience utility to set source names from the return
1441 * value of g_idle_add(), g_timeout_add(), etc.
1446 g_source_set_name_by_id (guint tag,
1451 g_return_if_fail (tag > 0);
1453 source = g_main_context_find_source_by_id (NULL, tag);
1457 g_source_set_name (source, name);
1463 * @source: a #GSource
1465 * Increases the reference count on a source by one.
1467 * Return value: @source
1470 g_source_ref (GSource *source)
1472 GMainContext *context;
1474 g_return_val_if_fail (source != NULL, NULL);
1476 context = source->context;
1479 LOCK_CONTEXT (context);
1481 source->ref_count++;
1484 UNLOCK_CONTEXT (context);
1489 /* g_source_unref() but possible to call within context lock
1492 g_source_unref_internal (GSource *source,
1493 GMainContext *context,
1496 gpointer old_cb_data = NULL;
1497 GSourceCallbackFuncs *old_cb_funcs = NULL;
1499 g_return_if_fail (source != NULL);
1501 if (!have_lock && context)
1502 LOCK_CONTEXT (context);
1504 source->ref_count--;
1505 if (source->ref_count == 0)
1507 old_cb_data = source->callback_data;
1508 old_cb_funcs = source->callback_funcs;
1510 source->callback_data = NULL;
1511 source->callback_funcs = NULL;
1513 if (context && !SOURCE_DESTROYED (source))
1515 g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1516 source->ref_count++;
1519 g_source_list_remove (source, context);
1521 if (source->source_funcs->finalize)
1522 source->source_funcs->finalize (source);
1524 g_free (source->name);
1525 source->name = NULL;
1527 g_slist_free (source->poll_fds);
1528 source->poll_fds = NULL;
1532 if (!have_lock && context)
1533 UNLOCK_CONTEXT (context);
1538 UNLOCK_CONTEXT (context);
1540 old_cb_funcs->unref (old_cb_data);
1543 LOCK_CONTEXT (context);
1549 * @source: a #GSource
1551 * Decreases the reference count of a source by one. If the
1552 * resulting reference count is zero the source and associated
1553 * memory will be destroyed.
1556 g_source_unref (GSource *source)
1558 g_return_if_fail (source != NULL);
1560 g_source_unref_internal (source, source->context, FALSE);
1564 * g_main_context_find_source_by_id:
1565 * @context: a #GMainContext (if %NULL, the default context will be used)
1566 * @source_id: the source ID, as returned by g_source_get_id().
1568 * Finds a #GSource given a pair of context and ID.
1570 * Return value: the #GSource if found, otherwise, %NULL
1573 g_main_context_find_source_by_id (GMainContext *context,
1578 g_return_val_if_fail (source_id > 0, NULL);
1580 if (context == NULL)
1581 context = g_main_context_default ();
1583 LOCK_CONTEXT (context);
1585 source = context->source_list;
1588 if (!SOURCE_DESTROYED (source) &&
1589 source->source_id == source_id)
1591 source = source->next;
1594 UNLOCK_CONTEXT (context);
1600 * g_main_context_find_source_by_funcs_user_data:
1601 * @context: a #GMainContext (if %NULL, the default context will be used).
1602 * @funcs: the @source_funcs passed to g_source_new().
1603 * @user_data: the user data from the callback.
1605 * Finds a source with the given source functions and user data. If
1606 * multiple sources exist with the same source function and user data,
1607 * the first one found will be returned.
1609 * Return value: the source, if one was found, otherwise %NULL
1612 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1613 GSourceFuncs *funcs,
1618 g_return_val_if_fail (funcs != NULL, NULL);
1620 if (context == NULL)
1621 context = g_main_context_default ();
1623 LOCK_CONTEXT (context);
1625 source = context->source_list;
1628 if (!SOURCE_DESTROYED (source) &&
1629 source->source_funcs == funcs &&
1630 source->callback_funcs)
1632 GSourceFunc callback;
1633 gpointer callback_data;
1635 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1637 if (callback_data == user_data)
1640 source = source->next;
1643 UNLOCK_CONTEXT (context);
1649 * g_main_context_find_source_by_user_data:
1650 * @context: a #GMainContext
1651 * @user_data: the user_data for the callback.
1653 * Finds a source with the given user data for the callback. If
1654 * multiple sources exist with the same user data, the first
1655 * one found will be returned.
1657 * Return value: the source, if one was found, otherwise %NULL
1660 g_main_context_find_source_by_user_data (GMainContext *context,
1665 if (context == NULL)
1666 context = g_main_context_default ();
1668 LOCK_CONTEXT (context);
1670 source = context->source_list;
1673 if (!SOURCE_DESTROYED (source) &&
1674 source->callback_funcs)
1676 GSourceFunc callback;
1677 gpointer callback_data = NULL;
1679 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1681 if (callback_data == user_data)
1684 source = source->next;
1687 UNLOCK_CONTEXT (context);
1694 * @tag: the ID of the source to remove.
1696 * Removes the source with the given id from the default main context.
1698 * a #GSource is given by g_source_get_id(), or will be returned by the
1699 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1700 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1701 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1703 * See also g_source_destroy(). You must use g_source_destroy() for sources
1704 * added to a non-default main context.
1706 * Return value: %TRUE if the source was found and removed.
1709 g_source_remove (guint tag)
1713 g_return_val_if_fail (tag > 0, FALSE);
1715 source = g_main_context_find_source_by_id (NULL, tag);
1717 g_source_destroy (source);
1719 return source != NULL;
1723 * g_source_remove_by_user_data:
1724 * @user_data: the user_data for the callback.
1726 * Removes a source from the default main loop context given the user
1727 * data for the callback. If multiple sources exist with the same user
1728 * data, only one will be destroyed.
1730 * Return value: %TRUE if a source was found and removed.
1733 g_source_remove_by_user_data (gpointer user_data)
1737 source = g_main_context_find_source_by_user_data (NULL, user_data);
1740 g_source_destroy (source);
1748 * g_source_remove_by_funcs_user_data:
1749 * @funcs: The @source_funcs passed to g_source_new()
1750 * @user_data: the user data for the callback
1752 * Removes a source from the default main loop context given the
1753 * source functions and user data. If multiple sources exist with the
1754 * same source functions and user data, only one will be destroyed.
1756 * Return value: %TRUE if a source was found and removed.
1759 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1764 g_return_val_if_fail (funcs != NULL, FALSE);
1766 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1769 g_source_destroy (source);
1777 * g_get_current_time:
1778 * @result: #GTimeVal structure in which to store current time.
1780 * Equivalent to the UNIX gettimeofday() function, but portable.
1783 g_get_current_time (GTimeVal *result)
1788 g_return_if_fail (result != NULL);
1790 /*this is required on alpha, there the timeval structs are int's
1791 not longs and a cast only would fail horribly*/
1792 gettimeofday (&r, NULL);
1793 result->tv_sec = r.tv_sec;
1794 result->tv_usec = r.tv_usec;
1799 g_return_if_fail (result != NULL);
1801 GetSystemTimeAsFileTime (&ft);
1802 memmove (&time64, &ft, sizeof (FILETIME));
1804 /* Convert from 100s of nanoseconds since 1601-01-01
1805 * to Unix epoch. Yes, this is Y2038 unsafe.
1807 time64 -= G_GINT64_CONSTANT (116444736000000000);
1810 result->tv_sec = time64 / 1000000;
1811 result->tv_usec = time64 % 1000000;
1818 * Represents a precise time, with seconds and nanoseconds. This is
1819 * similar to POSIX <structname>struct timespec</structname>. This
1820 * structure can be filled in with g_get_monotonic_time().
1826 * g_get_monotonic_time:
1827 * @result: #GTimeSpec structure in which to store the time
1829 * Queries the system monotonic time, if available.
1831 * On POSIX systems with clock_gettime() and %CLOCK_MONOTONIC this call
1832 * is a very shallow wrapper for that. Otherwise, we make a best effort
1833 * that probably involves returning the wall clock time (with at least
1834 * microsecond accuracy, subject to the limitations of the OS kernel).
1836 * Note that, on Windows, "limitations of the OS kernel" is a rather
1837 * substantial statement. Depending on the configuration of the system,
1838 * the wall clock time is updated as infrequently as 64 times a second
1839 * (which is approximately every 16ms).
1844 g_get_monotonic_time (GTimeSpec *result)
1846 g_return_if_fail (result != NULL);
1848 #ifdef HAVE_CLOCK_GETTIME
1849 /* librt clock_gettime() is our first choice */
1851 static int clockid = CLOCK_REALTIME;
1854 #ifdef HAVE_MONOTONIC_CLOCK
1855 /* We have to check if we actually have monotonic clock support.
1857 * There is no thread safety issue here since there is no harm if we
1861 static gboolean checked;
1863 if G_UNLIKELY (!checked)
1865 if (sysconf (_SC_MONOTONIC_CLOCK) >= 0)
1866 clockid = CLOCK_MONOTONIC;
1872 clock_gettime (clockid, &ts);
1873 result->tv_sec = ts.tv_sec;
1874 result->tv_nsec = ts.tv_nsec;
1877 /* It may look like we are discarding accuracy on Windows (since its
1878 * current time is expressed in 100s of nanoseconds) but according to
1879 * many sources, the time is only updated 64 times per second, so
1880 * microsecond accuracy is more than enough.
1885 g_get_current_time (&tv);
1886 result->tv_sec = tv.tv_sec;
1887 result->tv_nsec = tv.tv_usec * 1000;
1893 g_main_dispatch_free (gpointer dispatch)
1895 g_slice_free (GMainDispatch, dispatch);
1898 /* Running the main loop */
1900 static GMainDispatch *
1903 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
1904 GMainDispatch *dispatch = g_static_private_get (&depth_private);
1907 dispatch = g_slice_new0 (GMainDispatch);
1908 g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
1917 * Returns the depth of the stack of calls to
1918 * g_main_context_dispatch() on any #GMainContext in the current thread.
1919 * That is, when called from the toplevel, it gives 0. When
1920 * called from within a callback from g_main_context_iteration()
1921 * (or g_main_loop_run(), etc.) it returns 1. When called from within
1922 * a callback to a recursive call to g_main_context_iterate(),
1923 * it returns 2. And so forth.
1925 * This function is useful in a situation like the following:
1926 * Imagine an extremely simple "garbage collected" system.
1929 * static GList *free_list;
1932 * allocate_memory (gsize size)
1934 * gpointer result = g_malloc (size);
1935 * free_list = g_list_prepend (free_list, result);
1940 * free_allocated_memory (void)
1943 * for (l = free_list; l; l = l->next);
1945 * g_list_free (free_list);
1953 * g_main_context_iteration (NULL, TRUE);
1954 * free_allocated_memory();
1958 * This works from an application, however, if you want to do the same
1959 * thing from a library, it gets more difficult, since you no longer
1960 * control the main loop. You might think you can simply use an idle
1961 * function to make the call to free_allocated_memory(), but that
1962 * doesn't work, since the idle function could be called from a
1963 * recursive callback. This can be fixed by using g_main_depth()
1967 * allocate_memory (gsize size)
1969 * FreeListBlock *block = g_new (FreeListBlock, 1);
1970 * block->mem = g_malloc (size);
1971 * block->depth = g_main_depth ();
1972 * free_list = g_list_prepend (free_list, block);
1973 * return block->mem;
1977 * free_allocated_memory (void)
1981 * int depth = g_main_depth ();
1982 * for (l = free_list; l; );
1984 * GList *next = l->next;
1985 * FreeListBlock *block = l->data;
1986 * if (block->depth > depth)
1988 * g_free (block->mem);
1990 * free_list = g_list_delete_link (free_list, l);
1998 * There is a temptation to use g_main_depth() to solve
1999 * problems with reentrancy. For instance, while waiting for data
2000 * to be received from the network in response to a menu item,
2001 * the menu item might be selected again. It might seem that
2002 * one could make the menu item's callback return immediately
2003 * and do nothing if g_main_depth() returns a value greater than 1.
2004 * However, this should be avoided since the user then sees selecting
2005 * the menu item do nothing. Furthermore, you'll find yourself adding
2006 * these checks all over your code, since there are doubtless many,
2007 * many things that the user could do. Instead, you can use the
2008 * following techniques:
2013 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
2014 * the user from interacting with elements while the main
2015 * loop is recursing.
2020 * Avoid main loop recursion in situations where you can't handle
2021 * arbitrary callbacks. Instead, structure your code so that you
2022 * simply return to the main loop and then get called again when
2023 * there is more work to do.
2028 * Return value: The main loop recursion level in the current thread
2033 GMainDispatch *dispatch = get_dispatch ();
2034 return dispatch->depth;
2038 * g_main_current_source:
2040 * Returns the currently firing source for this thread.
2042 * Return value: The currently firing source or %NULL.
2047 g_main_current_source (void)
2049 GMainDispatch *dispatch = get_dispatch ();
2050 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
2054 * g_source_is_destroyed:
2055 * @source: a #GSource
2057 * Returns whether @source has been destroyed.
2059 * This is important when you operate upon your objects
2060 * from within idle handlers, but may have freed the object
2061 * before the dispatch of your idle handler.
2065 * idle_callback (gpointer data)
2067 * SomeWidget *self = data;
2069 * GDK_THREADS_ENTER (<!-- -->);
2070 * /<!-- -->* do stuff with self *<!-- -->/
2071 * self->idle_id = 0;
2072 * GDK_THREADS_LEAVE (<!-- -->);
2078 * some_widget_do_stuff_later (SomeWidget *self)
2080 * self->idle_id = g_idle_add (idle_callback, self);
2084 * some_widget_finalize (GObject *object)
2086 * SomeWidget *self = SOME_WIDGET (object);
2088 * if (self->idle_id)
2089 * g_source_remove (self->idle_id);
2091 * G_OBJECT_CLASS (parent_class)->finalize (object);
2095 * This will fail in a multi-threaded application if the
2096 * widget is destroyed before the idle handler fires due
2097 * to the use after free in the callback. A solution, to
2098 * this particular problem, is to check to if the source
2099 * has already been destroy within the callback.
2103 * idle_callback (gpointer data)
2105 * SomeWidget *self = data;
2107 * GDK_THREADS_ENTER ();
2108 * if (!g_source_is_destroyed (g_main_current_source ()))
2110 * /<!-- -->* do stuff with self *<!-- -->/
2112 * GDK_THREADS_LEAVE ();
2118 * Return value: %TRUE if the source has been destroyed
2123 g_source_is_destroyed (GSource *source)
2125 return SOURCE_DESTROYED (source);
2128 /* Temporarily remove all this source's file descriptors from the
2129 * poll(), so that if data comes available for one of the file descriptors
2130 * we don't continually spin in the poll()
2132 /* HOLDS: source->context's lock */
2134 block_source (GSource *source)
2138 g_return_if_fail (!SOURCE_BLOCKED (source));
2140 tmp_list = source->poll_fds;
2143 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2144 tmp_list = tmp_list->next;
2148 /* HOLDS: source->context's lock */
2150 unblock_source (GSource *source)
2154 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
2155 g_return_if_fail (!SOURCE_DESTROYED (source));
2157 tmp_list = source->poll_fds;
2160 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2161 tmp_list = tmp_list->next;
2165 /* HOLDS: context's lock */
2167 g_main_dispatch (GMainContext *context)
2169 GMainDispatch *current = get_dispatch ();
2172 for (i = 0; i < context->pending_dispatches->len; i++)
2174 GSource *source = context->pending_dispatches->pdata[i];
2176 context->pending_dispatches->pdata[i] = NULL;
2179 source->flags &= ~G_SOURCE_READY;
2181 if (!SOURCE_DESTROYED (source))
2183 gboolean was_in_call;
2184 gpointer user_data = NULL;
2185 GSourceFunc callback = NULL;
2186 GSourceCallbackFuncs *cb_funcs;
2188 gboolean need_destroy;
2190 gboolean (*dispatch) (GSource *,
2193 GSList current_source_link;
2195 dispatch = source->source_funcs->dispatch;
2196 cb_funcs = source->callback_funcs;
2197 cb_data = source->callback_data;
2200 cb_funcs->ref (cb_data);
2202 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2203 block_source (source);
2205 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2206 source->flags |= G_HOOK_FLAG_IN_CALL;
2209 cb_funcs->get (cb_data, source, &callback, &user_data);
2211 UNLOCK_CONTEXT (context);
2214 /* The on-stack allocation of the GSList is unconventional, but
2215 * we know that the lifetime of the link is bounded to this
2216 * function as the link is kept in a thread specific list and
2217 * not manipulated outside of this function and its descendants.
2218 * Avoiding the overhead of a g_slist_alloc() is useful as many
2219 * applications do little more than dispatch events.
2221 * This is a performance hack - do not revert to g_slist_prepend()!
2223 current_source_link.data = source;
2224 current_source_link.next = current->dispatching_sources;
2225 current->dispatching_sources = ¤t_source_link;
2226 need_destroy = ! dispatch (source,
2229 g_assert (current->dispatching_sources == ¤t_source_link);
2230 current->dispatching_sources = current_source_link.next;
2234 cb_funcs->unref (cb_data);
2236 LOCK_CONTEXT (context);
2239 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2241 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2242 !SOURCE_DESTROYED (source))
2243 unblock_source (source);
2245 /* Note: this depends on the fact that we can't switch
2246 * sources from one main context to another
2248 if (need_destroy && !SOURCE_DESTROYED (source))
2250 g_assert (source->context == context);
2251 g_source_destroy_internal (source, context, TRUE);
2255 SOURCE_UNREF (source, context);
2258 g_ptr_array_set_size (context->pending_dispatches, 0);
2261 /* Holds context's lock */
2262 static inline GSource *
2263 next_valid_source (GMainContext *context,
2266 GSource *new_source = source ? source->next : context->source_list;
2270 if (!SOURCE_DESTROYED (new_source))
2272 new_source->ref_count++;
2276 new_source = new_source->next;
2280 SOURCE_UNREF (source, context);
2286 * g_main_context_acquire:
2287 * @context: a #GMainContext
2289 * Tries to become the owner of the specified context.
2290 * If some other thread is the owner of the context,
2291 * returns %FALSE immediately. Ownership is properly
2292 * recursive: the owner can require ownership again
2293 * and will release ownership when g_main_context_release()
2294 * is called as many times as g_main_context_acquire().
2296 * You must be the owner of a context before you
2297 * can call g_main_context_prepare(), g_main_context_query(),
2298 * g_main_context_check(), g_main_context_dispatch().
2300 * Return value: %TRUE if the operation succeeded, and
2301 * this thread is now the owner of @context.
2304 g_main_context_acquire (GMainContext *context)
2306 #ifdef G_THREADS_ENABLED
2307 gboolean result = FALSE;
2308 GThread *self = G_THREAD_SELF;
2310 if (context == NULL)
2311 context = g_main_context_default ();
2313 LOCK_CONTEXT (context);
2315 if (!context->owner)
2317 context->owner = self;
2318 g_assert (context->owner_count == 0);
2321 if (context->owner == self)
2323 context->owner_count++;
2327 UNLOCK_CONTEXT (context);
2330 #else /* !G_THREADS_ENABLED */
2332 #endif /* G_THREADS_ENABLED */
2336 * g_main_context_release:
2337 * @context: a #GMainContext
2339 * Releases ownership of a context previously acquired by this thread
2340 * with g_main_context_acquire(). If the context was acquired multiple
2341 * times, the ownership will be released only when g_main_context_release()
2342 * is called as many times as it was acquired.
2345 g_main_context_release (GMainContext *context)
2347 #ifdef G_THREADS_ENABLED
2348 if (context == NULL)
2349 context = g_main_context_default ();
2351 LOCK_CONTEXT (context);
2353 context->owner_count--;
2354 if (context->owner_count == 0)
2356 context->owner = NULL;
2358 if (context->waiters)
2360 GMainWaiter *waiter = context->waiters->data;
2361 gboolean loop_internal_waiter =
2362 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
2363 context->waiters = g_slist_delete_link (context->waiters,
2365 if (!loop_internal_waiter)
2366 g_mutex_lock (waiter->mutex);
2368 g_cond_signal (waiter->cond);
2370 if (!loop_internal_waiter)
2371 g_mutex_unlock (waiter->mutex);
2375 UNLOCK_CONTEXT (context);
2376 #endif /* G_THREADS_ENABLED */
2380 * g_main_context_wait:
2381 * @context: a #GMainContext
2382 * @cond: a condition variable
2383 * @mutex: a mutex, currently held
2385 * Tries to become the owner of the specified context,
2386 * as with g_main_context_acquire(). But if another thread
2387 * is the owner, atomically drop @mutex and wait on @cond until
2388 * that owner releases ownership or until @cond is signaled, then
2389 * try again (once) to become the owner.
2391 * Return value: %TRUE if the operation succeeded, and
2392 * this thread is now the owner of @context.
2395 g_main_context_wait (GMainContext *context,
2399 #ifdef G_THREADS_ENABLED
2400 gboolean result = FALSE;
2401 GThread *self = G_THREAD_SELF;
2402 gboolean loop_internal_waiter;
2404 if (context == NULL)
2405 context = g_main_context_default ();
2407 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2409 if (!loop_internal_waiter)
2410 LOCK_CONTEXT (context);
2412 if (context->owner && context->owner != self)
2417 waiter.mutex = mutex;
2419 context->waiters = g_slist_append (context->waiters, &waiter);
2421 if (!loop_internal_waiter)
2422 UNLOCK_CONTEXT (context);
2423 g_cond_wait (cond, mutex);
2424 if (!loop_internal_waiter)
2425 LOCK_CONTEXT (context);
2427 context->waiters = g_slist_remove (context->waiters, &waiter);
2430 if (!context->owner)
2432 context->owner = self;
2433 g_assert (context->owner_count == 0);
2436 if (context->owner == self)
2438 context->owner_count++;
2442 if (!loop_internal_waiter)
2443 UNLOCK_CONTEXT (context);
2446 #else /* !G_THREADS_ENABLED */
2448 #endif /* G_THREADS_ENABLED */
2452 * g_main_context_prepare:
2453 * @context: a #GMainContext
2454 * @priority: location to store priority of highest priority
2455 * source already ready.
2457 * Prepares to poll sources within a main loop. The resulting information
2458 * for polling is determined by calling g_main_context_query ().
2460 * Return value: %TRUE if some source is ready to be dispatched
2464 g_main_context_prepare (GMainContext *context,
2469 gint current_priority = G_MAXINT;
2472 if (context == NULL)
2473 context = g_main_context_default ();
2475 LOCK_CONTEXT (context);
2477 context->time_is_current = FALSE;
2479 if (context->in_check_or_prepare)
2481 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2482 "prepare() member.");
2483 UNLOCK_CONTEXT (context);
2487 #ifdef G_THREADS_ENABLED
2488 if (context->poll_waiting)
2490 g_warning("g_main_context_prepare(): main loop already active in another thread");
2491 UNLOCK_CONTEXT (context);
2495 context->poll_waiting = TRUE;
2496 #endif /* G_THREADS_ENABLED */
2499 /* If recursing, finish up current dispatch, before starting over */
2500 if (context->pending_dispatches)
2503 g_main_dispatch (context, ¤t_time);
2505 UNLOCK_CONTEXT (context);
2510 /* If recursing, clear list of pending dispatches */
2512 for (i = 0; i < context->pending_dispatches->len; i++)
2514 if (context->pending_dispatches->pdata[i])
2515 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2517 g_ptr_array_set_size (context->pending_dispatches, 0);
2519 /* Prepare all sources */
2521 context->timeout = -1;
2523 source = next_valid_source (context, NULL);
2526 gint source_timeout = -1;
2528 if ((n_ready > 0) && (source->priority > current_priority))
2530 SOURCE_UNREF (source, context);
2533 if (SOURCE_BLOCKED (source))
2536 if (!(source->flags & G_SOURCE_READY))
2539 gboolean (*prepare) (GSource *source,
2542 prepare = source->source_funcs->prepare;
2543 context->in_check_or_prepare++;
2544 UNLOCK_CONTEXT (context);
2546 result = (*prepare) (source, &source_timeout);
2548 LOCK_CONTEXT (context);
2549 context->in_check_or_prepare--;
2552 source->flags |= G_SOURCE_READY;
2555 if (source->flags & G_SOURCE_READY)
2558 current_priority = source->priority;
2559 context->timeout = 0;
2562 if (source_timeout >= 0)
2564 if (context->timeout < 0)
2565 context->timeout = source_timeout;
2567 context->timeout = MIN (context->timeout, source_timeout);
2571 source = next_valid_source (context, source);
2574 UNLOCK_CONTEXT (context);
2577 *priority = current_priority;
2579 return (n_ready > 0);
2583 * g_main_context_query:
2584 * @context: a #GMainContext
2585 * @max_priority: maximum priority source to check
2586 * @timeout_: location to store timeout to be used in polling
2587 * @fds: location to store #GPollFD records that need to be polled.
2588 * @n_fds: length of @fds.
2590 * Determines information necessary to poll this main loop.
2592 * Return value: the number of records actually stored in @fds,
2593 * or, if more than @n_fds records need to be stored, the number
2594 * of records that need to be stored.
2597 g_main_context_query (GMainContext *context,
2606 LOCK_CONTEXT (context);
2608 pollrec = context->poll_records;
2610 while (pollrec && max_priority >= pollrec->priority)
2612 /* We need to include entries with fd->events == 0 in the array because
2613 * otherwise if the application changes fd->events behind our back and
2614 * makes it non-zero, we'll be out of sync when we check the fds[] array.
2615 * (Changing fd->events after adding an FD wasn't an anticipated use of
2616 * this API, but it occurs in practice.) */
2619 fds[n_poll].fd = pollrec->fd->fd;
2620 /* In direct contradiction to the Unix98 spec, IRIX runs into
2621 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2622 * flags in the events field of the pollfd while it should
2623 * just ignoring them. So we mask them out here.
2625 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2626 fds[n_poll].revents = 0;
2629 pollrec = pollrec->next;
2633 #ifdef G_THREADS_ENABLED
2634 context->poll_changed = FALSE;
2639 *timeout = context->timeout;
2641 context->time_is_current = FALSE;
2644 UNLOCK_CONTEXT (context);
2650 * g_main_context_check:
2651 * @context: a #GMainContext
2652 * @max_priority: the maximum numerical priority of sources to check
2653 * @fds: array of #GPollFD's that was passed to the last call to
2654 * g_main_context_query()
2655 * @n_fds: return value of g_main_context_query()
2657 * Passes the results of polling back to the main loop.
2659 * Return value: %TRUE if some sources are ready to be dispatched.
2662 g_main_context_check (GMainContext *context,
2672 LOCK_CONTEXT (context);
2674 if (context->in_check_or_prepare)
2676 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2677 "prepare() member.");
2678 UNLOCK_CONTEXT (context);
2682 #ifdef G_THREADS_ENABLED
2683 if (!context->poll_waiting)
2687 read (context->wake_up_pipe[0], &a, 1);
2691 context->poll_waiting = FALSE;
2693 /* If the set of poll file descriptors changed, bail out
2694 * and let the main loop rerun
2696 if (context->poll_changed)
2698 UNLOCK_CONTEXT (context);
2701 #endif /* G_THREADS_ENABLED */
2703 pollrec = context->poll_records;
2707 if (pollrec->fd->events)
2708 pollrec->fd->revents = fds[i].revents;
2710 pollrec = pollrec->next;
2714 source = next_valid_source (context, NULL);
2717 if ((n_ready > 0) && (source->priority > max_priority))
2719 SOURCE_UNREF (source, context);
2722 if (SOURCE_BLOCKED (source))
2725 if (!(source->flags & G_SOURCE_READY))
2728 gboolean (*check) (GSource *source);
2730 check = source->source_funcs->check;
2732 context->in_check_or_prepare++;
2733 UNLOCK_CONTEXT (context);
2735 result = (*check) (source);
2737 LOCK_CONTEXT (context);
2738 context->in_check_or_prepare--;
2741 source->flags |= G_SOURCE_READY;
2744 if (source->flags & G_SOURCE_READY)
2746 source->ref_count++;
2747 g_ptr_array_add (context->pending_dispatches, source);
2751 /* never dispatch sources with less priority than the first
2752 * one we choose to dispatch
2754 max_priority = source->priority;
2758 source = next_valid_source (context, source);
2761 UNLOCK_CONTEXT (context);
2767 * g_main_context_dispatch:
2768 * @context: a #GMainContext
2770 * Dispatches all pending sources.
2773 g_main_context_dispatch (GMainContext *context)
2775 LOCK_CONTEXT (context);
2777 if (context->pending_dispatches->len > 0)
2779 g_main_dispatch (context);
2782 UNLOCK_CONTEXT (context);
2785 /* HOLDS context lock */
2787 g_main_context_iterate (GMainContext *context,
2794 gboolean some_ready;
2795 gint nfds, allocated_nfds;
2796 GPollFD *fds = NULL;
2798 UNLOCK_CONTEXT (context);
2800 #ifdef G_THREADS_ENABLED
2801 if (!g_main_context_acquire (context))
2803 gboolean got_ownership;
2805 LOCK_CONTEXT (context);
2807 g_return_val_if_fail (g_thread_supported (), FALSE);
2813 context->cond = g_cond_new ();
2815 got_ownership = g_main_context_wait (context,
2817 g_static_mutex_get_mutex (&context->mutex));
2823 LOCK_CONTEXT (context);
2824 #endif /* G_THREADS_ENABLED */
2826 if (!context->cached_poll_array)
2828 context->cached_poll_array_size = context->n_poll_records;
2829 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2832 allocated_nfds = context->cached_poll_array_size;
2833 fds = context->cached_poll_array;
2835 UNLOCK_CONTEXT (context);
2837 g_main_context_prepare (context, &max_priority);
2839 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
2840 allocated_nfds)) > allocated_nfds)
2842 LOCK_CONTEXT (context);
2844 context->cached_poll_array_size = allocated_nfds = nfds;
2845 context->cached_poll_array = fds = g_new (GPollFD, nfds);
2846 UNLOCK_CONTEXT (context);
2852 g_main_context_poll (context, timeout, max_priority, fds, nfds);
2854 some_ready = g_main_context_check (context, max_priority, fds, nfds);
2857 g_main_context_dispatch (context);
2859 #ifdef G_THREADS_ENABLED
2860 g_main_context_release (context);
2861 #endif /* G_THREADS_ENABLED */
2863 LOCK_CONTEXT (context);
2869 * g_main_context_pending:
2870 * @context: a #GMainContext (if %NULL, the default context will be used)
2872 * Checks if any sources have pending events for the given context.
2874 * Return value: %TRUE if events are pending.
2877 g_main_context_pending (GMainContext *context)
2882 context = g_main_context_default();
2884 LOCK_CONTEXT (context);
2885 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
2886 UNLOCK_CONTEXT (context);
2892 * g_main_context_iteration:
2893 * @context: a #GMainContext (if %NULL, the default context will be used)
2894 * @may_block: whether the call may block.
2896 * Runs a single iteration for the given main loop. This involves
2897 * checking to see if any event sources are ready to be processed,
2898 * then if no events sources are ready and @may_block is %TRUE, waiting
2899 * for a source to become ready, then dispatching the highest priority
2900 * events sources that are ready. Otherwise, if @may_block is %FALSE
2901 * sources are not waited to become ready, only those highest priority
2902 * events sources will be dispatched (if any), that are ready at this
2903 * given moment without further waiting.
2905 * Note that even when @may_block is %TRUE, it is still possible for
2906 * g_main_context_iteration() to return %FALSE, since the the wait may
2907 * be interrupted for other reasons than an event source becoming ready.
2909 * Return value: %TRUE if events were dispatched.
2912 g_main_context_iteration (GMainContext *context, gboolean may_block)
2917 context = g_main_context_default();
2919 LOCK_CONTEXT (context);
2920 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
2921 UNLOCK_CONTEXT (context);
2928 * @context: a #GMainContext (if %NULL, the default context will be used).
2929 * @is_running: set to %TRUE to indicate that the loop is running. This
2930 * is not very important since calling g_main_loop_run() will set this to
2933 * Creates a new #GMainLoop structure.
2935 * Return value: a new #GMainLoop.
2938 g_main_loop_new (GMainContext *context,
2939 gboolean is_running)
2944 context = g_main_context_default();
2946 g_main_context_ref (context);
2948 loop = g_new0 (GMainLoop, 1);
2949 loop->context = context;
2950 loop->is_running = is_running != FALSE;
2951 loop->ref_count = 1;
2958 * @loop: a #GMainLoop
2960 * Increases the reference count on a #GMainLoop object by one.
2962 * Return value: @loop
2965 g_main_loop_ref (GMainLoop *loop)
2967 g_return_val_if_fail (loop != NULL, NULL);
2968 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2970 g_atomic_int_inc (&loop->ref_count);
2976 * g_main_loop_unref:
2977 * @loop: a #GMainLoop
2979 * Decreases the reference count on a #GMainLoop object by one. If
2980 * the result is zero, free the loop and free all associated memory.
2983 g_main_loop_unref (GMainLoop *loop)
2985 g_return_if_fail (loop != NULL);
2986 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2988 if (!g_atomic_int_dec_and_test (&loop->ref_count))
2991 g_main_context_unref (loop->context);
2997 * @loop: a #GMainLoop
2999 * Runs a main loop until g_main_loop_quit() is called on the loop.
3000 * If this is called for the thread of the loop's #GMainContext,
3001 * it will process events from the loop, otherwise it will
3005 g_main_loop_run (GMainLoop *loop)
3007 GThread *self = G_THREAD_SELF;
3009 g_return_if_fail (loop != NULL);
3010 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3012 #ifdef G_THREADS_ENABLED
3013 if (!g_main_context_acquire (loop->context))
3015 gboolean got_ownership = FALSE;
3017 /* Another thread owns this context */
3018 if (!g_thread_supported ())
3020 g_warning ("g_main_loop_run() was called from second thread but "
3021 "g_thread_init() was never called.");
3025 LOCK_CONTEXT (loop->context);
3027 g_atomic_int_inc (&loop->ref_count);
3029 if (!loop->is_running)
3030 loop->is_running = TRUE;
3032 if (!loop->context->cond)
3033 loop->context->cond = g_cond_new ();
3035 while (loop->is_running && !got_ownership)
3036 got_ownership = g_main_context_wait (loop->context,
3037 loop->context->cond,
3038 g_static_mutex_get_mutex (&loop->context->mutex));
3040 if (!loop->is_running)
3042 UNLOCK_CONTEXT (loop->context);
3044 g_main_context_release (loop->context);
3045 g_main_loop_unref (loop);
3049 g_assert (got_ownership);
3052 LOCK_CONTEXT (loop->context);
3053 #endif /* G_THREADS_ENABLED */
3055 if (loop->context->in_check_or_prepare)
3057 g_warning ("g_main_loop_run(): called recursively from within a source's "
3058 "check() or prepare() member, iteration not possible.");
3062 g_atomic_int_inc (&loop->ref_count);
3063 loop->is_running = TRUE;
3064 while (loop->is_running)
3065 g_main_context_iterate (loop->context, TRUE, TRUE, self);
3067 UNLOCK_CONTEXT (loop->context);
3069 #ifdef G_THREADS_ENABLED
3070 g_main_context_release (loop->context);
3071 #endif /* G_THREADS_ENABLED */
3073 g_main_loop_unref (loop);
3078 * @loop: a #GMainLoop
3080 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3081 * for the loop will return.
3083 * Note that sources that have already been dispatched when
3084 * g_main_loop_quit() is called will still be executed.
3087 g_main_loop_quit (GMainLoop *loop)
3089 g_return_if_fail (loop != NULL);
3090 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3092 LOCK_CONTEXT (loop->context);
3093 loop->is_running = FALSE;
3094 g_main_context_wakeup_unlocked (loop->context);
3096 #ifdef G_THREADS_ENABLED
3097 if (loop->context->cond)
3098 g_cond_broadcast (loop->context->cond);
3099 #endif /* G_THREADS_ENABLED */
3101 UNLOCK_CONTEXT (loop->context);
3105 * g_main_loop_is_running:
3106 * @loop: a #GMainLoop.
3108 * Checks to see if the main loop is currently being run via g_main_loop_run().
3110 * Return value: %TRUE if the mainloop is currently being run.
3113 g_main_loop_is_running (GMainLoop *loop)
3115 g_return_val_if_fail (loop != NULL, FALSE);
3116 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3118 return loop->is_running;
3122 * g_main_loop_get_context:
3123 * @loop: a #GMainLoop.
3125 * Returns the #GMainContext of @loop.
3127 * Return value: the #GMainContext of @loop
3130 g_main_loop_get_context (GMainLoop *loop)
3132 g_return_val_if_fail (loop != NULL, NULL);
3133 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3135 return loop->context;
3138 /* HOLDS: context's lock */
3140 g_main_context_poll (GMainContext *context,
3146 #ifdef G_MAIN_POLL_DEBUG
3152 GPollFunc poll_func;
3154 if (n_fds || timeout != 0)
3156 #ifdef G_MAIN_POLL_DEBUG
3157 if (_g_main_poll_debug)
3159 g_print ("polling context=%p n=%d timeout=%d\n",
3160 context, n_fds, timeout);
3161 poll_timer = g_timer_new ();
3165 LOCK_CONTEXT (context);
3167 poll_func = context->poll_func;
3169 UNLOCK_CONTEXT (context);
3170 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3173 g_warning ("poll(2) failed due to: %s.",
3174 g_strerror (errno));
3176 /* If g_poll () returns -1, it has already called g_warning() */
3180 #ifdef G_MAIN_POLL_DEBUG
3181 if (_g_main_poll_debug)
3183 LOCK_CONTEXT (context);
3185 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3188 g_timer_elapsed (poll_timer, NULL));
3189 g_timer_destroy (poll_timer);
3190 pollrec = context->poll_records;
3192 while (pollrec != NULL)
3197 if (fds[i].fd == pollrec->fd->fd &&
3198 pollrec->fd->events &&
3201 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3202 if (fds[i].revents & G_IO_IN)
3204 if (fds[i].revents & G_IO_OUT)
3206 if (fds[i].revents & G_IO_PRI)
3208 if (fds[i].revents & G_IO_ERR)
3210 if (fds[i].revents & G_IO_HUP)
3212 if (fds[i].revents & G_IO_NVAL)
3218 pollrec = pollrec->next;
3222 UNLOCK_CONTEXT (context);
3225 } /* if (n_fds || timeout != 0) */
3229 * g_main_context_add_poll:
3230 * @context: a #GMainContext (or %NULL for the default context)
3231 * @fd: a #GPollFD structure holding information about a file
3232 * descriptor to watch.
3233 * @priority: the priority for this file descriptor which should be
3234 * the same as the priority used for g_source_attach() to ensure that the
3235 * file descriptor is polled whenever the results may be needed.
3237 * Adds a file descriptor to the set of file descriptors polled for
3238 * this context. This will very seldomly be used directly. Instead
3239 * a typical event source will use g_source_add_poll() instead.
3242 g_main_context_add_poll (GMainContext *context,
3247 context = g_main_context_default ();
3249 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3250 g_return_if_fail (fd);
3252 LOCK_CONTEXT (context);
3253 g_main_context_add_poll_unlocked (context, priority, fd);
3254 UNLOCK_CONTEXT (context);
3257 /* HOLDS: main_loop_lock */
3259 g_main_context_add_poll_unlocked (GMainContext *context,
3263 GPollRec *lastrec, *pollrec;
3264 GPollRec *newrec = g_slice_new (GPollRec);
3266 /* This file descriptor may be checked before we ever poll */
3269 newrec->priority = priority;
3272 pollrec = context->poll_records;
3273 while (pollrec && priority >= pollrec->priority)
3276 pollrec = pollrec->next;
3280 lastrec->next = newrec;
3282 context->poll_records = newrec;
3284 newrec->next = pollrec;
3286 context->n_poll_records++;
3288 #ifdef G_THREADS_ENABLED
3289 context->poll_changed = TRUE;
3291 /* Now wake up the main loop if it is waiting in the poll() */
3292 g_main_context_wakeup_unlocked (context);
3297 * g_main_context_remove_poll:
3298 * @context:a #GMainContext
3299 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3301 * Removes file descriptor from the set of file descriptors to be
3302 * polled for a particular context.
3305 g_main_context_remove_poll (GMainContext *context,
3309 context = g_main_context_default ();
3311 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3312 g_return_if_fail (fd);
3314 LOCK_CONTEXT (context);
3315 g_main_context_remove_poll_unlocked (context, fd);
3316 UNLOCK_CONTEXT (context);
3320 g_main_context_remove_poll_unlocked (GMainContext *context,
3323 GPollRec *pollrec, *lastrec;
3326 pollrec = context->poll_records;
3330 if (pollrec->fd == fd)
3332 if (lastrec != NULL)
3333 lastrec->next = pollrec->next;
3335 context->poll_records = pollrec->next;
3337 g_slice_free (GPollRec, pollrec);
3339 context->n_poll_records--;
3343 pollrec = pollrec->next;
3346 #ifdef G_THREADS_ENABLED
3347 context->poll_changed = TRUE;
3349 /* Now wake up the main loop if it is waiting in the poll() */
3350 g_main_context_wakeup_unlocked (context);
3355 * g_source_get_current_time:
3356 * @source: a #GSource
3357 * @timeval: #GTimeVal structure in which to store current time.
3359 * Gets the "current time" to be used when checking
3360 * this source. The advantage of calling this function over
3361 * calling g_get_current_time() directly is that when
3362 * checking multiple sources, GLib can cache a single value
3363 * instead of having to repeatedly get the system time.
3366 g_source_get_current_time (GSource *source,
3369 GMainContext *context;
3371 g_return_if_fail (source->context != NULL);
3373 context = source->context;
3375 LOCK_CONTEXT (context);
3377 if (!context->time_is_current)
3379 g_get_current_time (&context->current_time);
3380 context->time_is_current = TRUE;
3383 *timeval = context->current_time;
3385 UNLOCK_CONTEXT (context);
3389 * g_main_context_set_poll_func:
3390 * @context: a #GMainContext
3391 * @func: the function to call to poll all file descriptors
3393 * Sets the function to use to handle polling of file descriptors. It
3394 * will be used instead of the poll() system call
3395 * (or GLib's replacement function, which is used where
3396 * poll() isn't available).
3398 * This function could possibly be used to integrate the GLib event
3399 * loop with an external event loop.
3402 g_main_context_set_poll_func (GMainContext *context,
3406 context = g_main_context_default ();
3408 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3410 LOCK_CONTEXT (context);
3413 context->poll_func = func;
3415 context->poll_func = g_poll;
3417 UNLOCK_CONTEXT (context);
3421 * g_main_context_get_poll_func:
3422 * @context: a #GMainContext
3424 * Gets the poll function set by g_main_context_set_poll_func().
3426 * Return value: the poll function
3429 g_main_context_get_poll_func (GMainContext *context)
3434 context = g_main_context_default ();
3436 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3438 LOCK_CONTEXT (context);
3439 result = context->poll_func;
3440 UNLOCK_CONTEXT (context);
3445 /* HOLDS: context's lock */
3446 /* Wake the main loop up from a poll() */
3448 g_main_context_wakeup_unlocked (GMainContext *context)
3450 #ifdef G_THREADS_ENABLED
3451 if (g_thread_supported() && context->poll_waiting)
3453 context->poll_waiting = FALSE;
3455 write (context->wake_up_pipe[1], "A", 1);
3457 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
3464 * g_main_context_wakeup:
3465 * @context: a #GMainContext
3467 * If @context is currently waiting in a poll(), interrupt
3468 * the poll(), and continue the iteration process.
3471 g_main_context_wakeup (GMainContext *context)
3474 context = g_main_context_default ();
3476 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3478 LOCK_CONTEXT (context);
3479 g_main_context_wakeup_unlocked (context);
3480 UNLOCK_CONTEXT (context);
3484 * g_main_context_is_owner:
3485 * @context: a #GMainContext
3487 * Determines whether this thread holds the (recursive)
3488 * ownership of this #GMaincontext. This is useful to
3489 * know before waiting on another thread that may be
3490 * blocking to get ownership of @context.
3492 * Returns: %TRUE if current thread is owner of @context.
3497 g_main_context_is_owner (GMainContext *context)
3502 context = g_main_context_default ();
3504 #ifdef G_THREADS_ENABLED
3505 LOCK_CONTEXT (context);
3506 is_owner = context->owner == G_THREAD_SELF;
3507 UNLOCK_CONTEXT (context);
3518 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3519 GTimeVal *current_time)
3521 guint seconds = timeout_source->interval / 1000;
3522 guint msecs = timeout_source->interval - seconds * 1000;
3524 timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
3525 timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
3526 if (timeout_source->expiration.tv_usec >= 1000000)
3528 timeout_source->expiration.tv_usec -= 1000000;
3529 timeout_source->expiration.tv_sec++;
3531 if (timer_perturb==-1)
3534 * we want a per machine/session unique 'random' value; try the dbus
3535 * address first, that has a UUID in it. If there is no dbus, use the
3536 * hostname for hashing.
3538 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3539 if (!session_bus_address)
3540 session_bus_address = g_getenv ("HOSTNAME");
3541 if (session_bus_address)
3542 timer_perturb = ABS ((gint) g_str_hash (session_bus_address));
3546 if (timeout_source->granularity)
3549 gint gran; /* in usecs */
3552 gran = timeout_source->granularity * 1000;
3553 perturb = timer_perturb % gran;
3555 * We want to give each machine a per machine pertubation;
3556 * shift time back first, and forward later after the rounding
3559 timeout_source->expiration.tv_usec -= perturb;
3560 if (timeout_source->expiration.tv_usec < 0)
3562 timeout_source->expiration.tv_usec += 1000000;
3563 timeout_source->expiration.tv_sec--;
3566 remainder = timeout_source->expiration.tv_usec % gran;
3567 if (remainder >= gran/4) /* round up */
3568 timeout_source->expiration.tv_usec += gran;
3569 timeout_source->expiration.tv_usec -= remainder;
3571 timeout_source->expiration.tv_usec += perturb;
3573 /* the rounding may have overflown tv_usec */
3574 while (timeout_source->expiration.tv_usec > 1000000)
3576 timeout_source->expiration.tv_usec -= 1000000;
3577 timeout_source->expiration.tv_sec++;
3583 g_timeout_prepare (GSource *source,
3588 GTimeVal current_time;
3590 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3592 g_source_get_current_time (source, ¤t_time);
3594 sec = timeout_source->expiration.tv_sec - current_time.tv_sec;
3595 msec = (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000;
3597 /* We do the following in a rather convoluted fashion to deal with
3598 * the fact that we don't have an integral type big enough to hold
3599 * the difference of two timevals in millseconds.
3601 if (sec < 0 || (sec == 0 && msec < 0))
3605 glong interval_sec = timeout_source->interval / 1000;
3606 glong interval_msec = timeout_source->interval % 1000;
3614 if (sec > interval_sec ||
3615 (sec == interval_sec && msec > interval_msec))
3617 /* The system time has been set backwards, so we
3618 * reset the expiration time to now + timeout_source->interval;
3619 * this at least avoids hanging for long periods of time.
3621 g_timeout_set_expiration (timeout_source, ¤t_time);
3622 msec = MIN (G_MAXINT, timeout_source->interval);
3626 msec = MIN (G_MAXINT, (guint)msec + 1000 * (guint)sec);
3630 *timeout = (gint)msec;
3636 g_timeout_check (GSource *source)
3638 GTimeVal current_time;
3639 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3641 g_source_get_current_time (source, ¤t_time);
3643 return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
3644 ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
3645 (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
3649 g_timeout_dispatch (GSource *source,
3650 GSourceFunc callback,
3653 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3657 g_warning ("Timeout source dispatched without callback\n"
3658 "You must call g_source_set_callback().");
3662 if (callback (user_data))
3664 GTimeVal current_time;
3666 g_source_get_current_time (source, ¤t_time);
3667 g_timeout_set_expiration (timeout_source, ¤t_time);
3676 * g_timeout_source_new:
3677 * @interval: the timeout interval in milliseconds.
3679 * Creates a new timeout source.
3681 * The source will not initially be associated with any #GMainContext
3682 * and must be added to one with g_source_attach() before it will be
3685 * Return value: the newly-created timeout source
3688 g_timeout_source_new (guint interval)
3690 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3691 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3692 GTimeVal current_time;
3694 timeout_source->interval = interval;
3696 g_get_current_time (¤t_time);
3697 g_timeout_set_expiration (timeout_source, ¤t_time);
3703 * g_timeout_source_new_seconds:
3704 * @interval: the timeout interval in seconds
3706 * Creates a new timeout source.
3708 * The source will not initially be associated with any #GMainContext
3709 * and must be added to one with g_source_attach() before it will be
3712 * The scheduling granularity/accuracy of this timeout source will be
3715 * Return value: the newly-created timeout source
3720 g_timeout_source_new_seconds (guint interval)
3722 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3723 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3724 GTimeVal current_time;
3726 timeout_source->interval = 1000*interval;
3727 timeout_source->granularity = 1000;
3729 g_get_current_time (¤t_time);
3730 g_timeout_set_expiration (timeout_source, ¤t_time);
3737 * g_timeout_add_full:
3738 * @priority: the priority of the timeout source. Typically this will be in
3739 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3740 * @interval: the time between calls to the function, in milliseconds
3741 * (1/1000ths of a second)
3742 * @function: function to call
3743 * @data: data to pass to @function
3744 * @notify: function to call when the timeout is removed, or %NULL
3746 * Sets a function to be called at regular intervals, with the given
3747 * priority. The function is called repeatedly until it returns
3748 * %FALSE, at which point the timeout is automatically destroyed and
3749 * the function will not be called again. The @notify function is
3750 * called when the timeout is destroyed. The first call to the
3751 * function will be at the end of the first @interval.
3753 * Note that timeout functions may be delayed, due to the processing of other
3754 * event sources. Thus they should not be relied on for precise timing.
3755 * After each call to the timeout function, the time of the next
3756 * timeout is recalculated based on the current time and the given interval
3757 * (it does not try to 'catch up' time lost in delays).
3759 * This internally creates a main loop source using g_timeout_source_new()
3760 * and attaches it to the main loop context using g_source_attach(). You can
3761 * do these steps manually if you need greater control.
3763 * Return value: the ID (greater than 0) of the event source.
3766 g_timeout_add_full (gint priority,
3768 GSourceFunc function,
3770 GDestroyNotify notify)
3775 g_return_val_if_fail (function != NULL, 0);
3777 source = g_timeout_source_new (interval);
3779 if (priority != G_PRIORITY_DEFAULT)
3780 g_source_set_priority (source, priority);
3782 g_source_set_callback (source, function, data, notify);
3783 id = g_source_attach (source, NULL);
3784 g_source_unref (source);
3791 * @interval: the time between calls to the function, in milliseconds
3792 * (1/1000ths of a second)
3793 * @function: function to call
3794 * @data: data to pass to @function
3796 * Sets a function to be called at regular intervals, with the default
3797 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
3798 * until it returns %FALSE, at which point the timeout is automatically
3799 * destroyed and the function will not be called again. The first call
3800 * to the function will be at the end of the first @interval.
3802 * Note that timeout functions may be delayed, due to the processing of other
3803 * event sources. Thus they should not be relied on for precise timing.
3804 * After each call to the timeout function, the time of the next
3805 * timeout is recalculated based on the current time and the given interval
3806 * (it does not try to 'catch up' time lost in delays).
3808 * If you want to have a timer in the "seconds" range and do not care
3809 * about the exact time of the first call of the timer, use the
3810 * g_timeout_add_seconds() function; this function allows for more
3811 * optimizations and more efficient system power usage.
3813 * This internally creates a main loop source using g_timeout_source_new()
3814 * and attaches it to the main loop context using g_source_attach(). You can
3815 * do these steps manually if you need greater control.
3817 * Return value: the ID (greater than 0) of the event source.
3820 g_timeout_add (guint32 interval,
3821 GSourceFunc function,
3824 return g_timeout_add_full (G_PRIORITY_DEFAULT,
3825 interval, function, data, NULL);
3829 * g_timeout_add_seconds_full:
3830 * @priority: the priority of the timeout source. Typically this will be in
3831 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3832 * @interval: the time between calls to the function, in seconds
3833 * @function: function to call
3834 * @data: data to pass to @function
3835 * @notify: function to call when the timeout is removed, or %NULL
3837 * Sets a function to be called at regular intervals, with @priority.
3838 * The function is called repeatedly until it returns %FALSE, at which
3839 * point the timeout is automatically destroyed and the function will
3840 * not be called again.
3842 * Unlike g_timeout_add(), this function operates at whole second granularity.
3843 * The initial starting point of the timer is determined by the implementation
3844 * and the implementation is expected to group multiple timers together so that
3845 * they fire all at the same time.
3846 * To allow this grouping, the @interval to the first timer is rounded
3847 * and can deviate up to one second from the specified interval.
3848 * Subsequent timer iterations will generally run at the specified interval.
3850 * Note that timeout functions may be delayed, due to the processing of other
3851 * event sources. Thus they should not be relied on for precise timing.
3852 * After each call to the timeout function, the time of the next
3853 * timeout is recalculated based on the current time and the given @interval
3855 * If you want timing more precise than whole seconds, use g_timeout_add()
3858 * The grouping of timers to fire at the same time results in a more power
3859 * and CPU efficient behavior so if your timer is in multiples of seconds
3860 * and you don't require the first timer exactly one second from now, the
3861 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
3863 * This internally creates a main loop source using
3864 * g_timeout_source_new_seconds() and attaches it to the main loop context
3865 * using g_source_attach(). You can do these steps manually if you need
3868 * Return value: the ID (greater than 0) of the event source.
3873 g_timeout_add_seconds_full (gint priority,
3875 GSourceFunc function,
3877 GDestroyNotify notify)
3882 g_return_val_if_fail (function != NULL, 0);
3884 source = g_timeout_source_new_seconds (interval);
3886 if (priority != G_PRIORITY_DEFAULT)
3887 g_source_set_priority (source, priority);
3889 g_source_set_callback (source, function, data, notify);
3890 id = g_source_attach (source, NULL);
3891 g_source_unref (source);
3897 * g_timeout_add_seconds:
3898 * @interval: the time between calls to the function, in seconds
3899 * @function: function to call
3900 * @data: data to pass to @function
3902 * Sets a function to be called at regular intervals with the default
3903 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
3904 * it returns %FALSE, at which point the timeout is automatically destroyed
3905 * and the function will not be called again.
3907 * This internally creates a main loop source using
3908 * g_timeout_source_new_seconds() and attaches it to the main loop context
3909 * using g_source_attach(). You can do these steps manually if you need
3910 * greater control. Also see g_timout_add_seconds_full().
3912 * Return value: the ID (greater than 0) of the event source.
3917 g_timeout_add_seconds (guint interval,
3918 GSourceFunc function,
3921 g_return_val_if_fail (function != NULL, 0);
3923 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
3926 /* Child watch functions */
3931 g_child_watch_prepare (GSource *source,
3940 g_child_watch_check (GSource *source)
3942 GChildWatchSource *child_watch_source;
3943 gboolean child_exited;
3945 child_watch_source = (GChildWatchSource *) source;
3947 child_exited = child_watch_source->poll.revents & G_IO_IN;
3954 * Note: We do _not_ check for the special value of STILL_ACTIVE
3955 * since we know that the process has exited and doing so runs into
3956 * problems if the child process "happens to return STILL_ACTIVE(259)"
3957 * as Microsoft's Platform SDK puts it.
3959 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
3961 gchar *emsg = g_win32_error_message (GetLastError ());
3962 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
3965 child_watch_source->child_status = -1;
3968 child_watch_source->child_status = child_status;
3971 return child_exited;
3974 #else /* G_OS_WIN32 */
3977 check_for_child_exited (GSource *source)
3979 GChildWatchSource *child_watch_source;
3982 /* protect against another SIGCHLD in the middle of this call */
3983 count = child_watch_count;
3985 child_watch_source = (GChildWatchSource *) source;
3987 if (child_watch_source->child_exited)
3990 if (child_watch_source->count < count)
3994 if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
3996 child_watch_source->child_status = child_status;
3997 child_watch_source->child_exited = TRUE;
3999 child_watch_source->count = count;
4002 return child_watch_source->child_exited;
4006 g_child_watch_prepare (GSource *source,
4011 return check_for_child_exited (source);
4016 g_child_watch_check (GSource *source)
4018 return check_for_child_exited (source);
4021 #endif /* G_OS_WIN32 */
4024 g_child_watch_dispatch (GSource *source,
4025 GSourceFunc callback,
4028 GChildWatchSource *child_watch_source;
4029 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
4031 child_watch_source = (GChildWatchSource *) source;
4035 g_warning ("Child watch source dispatched without callback\n"
4036 "You must call g_source_set_callback().");
4040 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
4042 /* We never keep a child watch source around as the child is gone */
4049 g_child_watch_signal_handler (int signum)
4051 child_watch_count ++;
4053 if (child_watch_init_state == CHILD_WATCH_INITIALIZED_THREADED)
4055 write (child_watch_wake_up_pipe[1], "B", 1);
4059 /* We count on the signal interrupting the poll in the same thread.
4065 g_child_watch_source_init_single (void)
4067 struct sigaction action;
4069 g_assert (! g_thread_supported());
4070 g_assert (child_watch_init_state == CHILD_WATCH_UNINITIALIZED);
4072 child_watch_init_state = CHILD_WATCH_INITIALIZED_SINGLE;
4074 action.sa_handler = g_child_watch_signal_handler;
4075 sigemptyset (&action.sa_mask);
4076 action.sa_flags = SA_NOCLDSTOP;
4077 sigaction (SIGCHLD, &action, NULL);
4080 G_GNUC_NORETURN static gpointer
4081 child_watch_helper_thread (gpointer data)
4088 read (child_watch_wake_up_pipe[0], b, 20);
4090 /* We were woken up. Wake up all other contexts in all other threads */
4091 G_LOCK (main_context_list);
4092 for (list = main_context_list; list; list = list->next)
4094 GMainContext *context;
4096 context = list->data;
4097 if (g_atomic_int_get (&context->ref_count) > 0)
4098 /* Due to racing conditions we can find ref_count == 0, in
4099 * that case, however, the context is still not destroyed
4100 * and no poll can be active, otherwise the ref_count
4102 g_main_context_wakeup (context);
4104 G_UNLOCK (main_context_list);
4109 g_child_watch_source_init_multi_threaded (void)
4111 GError *error = NULL;
4112 struct sigaction action;
4114 g_assert (g_thread_supported());
4116 if (pipe (child_watch_wake_up_pipe) < 0)
4117 g_error ("Cannot create wake up pipe: %s\n", g_strerror (errno));
4118 fcntl (child_watch_wake_up_pipe[1], F_SETFL, O_NONBLOCK | fcntl (child_watch_wake_up_pipe[1], F_GETFL));
4120 /* We create a helper thread that polls on the wakeup pipe indefinitely */
4121 /* FIXME: Think this through for races */
4122 if (g_thread_create (child_watch_helper_thread, NULL, FALSE, &error) == NULL)
4123 g_error ("Cannot create a thread to monitor child exit status: %s\n", error->message);
4124 child_watch_init_state = CHILD_WATCH_INITIALIZED_THREADED;
4126 action.sa_handler = g_child_watch_signal_handler;
4127 sigemptyset (&action.sa_mask);
4128 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4129 sigaction (SIGCHLD, &action, NULL);
4133 g_child_watch_source_init_promote_single_to_threaded (void)
4135 g_child_watch_source_init_multi_threaded ();
4139 g_child_watch_source_init (void)
4141 if (g_thread_supported())
4143 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
4144 g_child_watch_source_init_multi_threaded ();
4145 else if (child_watch_init_state == CHILD_WATCH_INITIALIZED_SINGLE)
4146 g_child_watch_source_init_promote_single_to_threaded ();
4150 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
4151 g_child_watch_source_init_single ();
4155 #endif /* !G_OS_WIN32 */
4158 * g_child_watch_source_new:
4159 * @pid: process to watch. On POSIX the pid of a child process. On
4160 * Windows a handle for a process (which doesn't have to be a child).
4162 * Creates a new child_watch source.
4164 * The source will not initially be associated with any #GMainContext
4165 * and must be added to one with g_source_attach() before it will be
4168 * Note that child watch sources can only be used in conjunction with
4169 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4172 * Note that on platforms where #GPid must be explicitly closed
4173 * (see g_spawn_close_pid()) @pid must not be closed while the
4174 * source is still active. Typically, you will want to call
4175 * g_spawn_close_pid() in the callback function for the source.
4177 * Note further that using g_child_watch_source_new() is not
4178 * compatible with calling <literal>waitpid(-1)</literal> in
4179 * the application. Calling waitpid() for individual pids will
4182 * Return value: the newly-created child watch source
4187 g_child_watch_source_new (GPid pid)
4189 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4190 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4193 child_watch_source->poll.fd = (gintptr) pid;
4194 child_watch_source->poll.events = G_IO_IN;
4196 g_source_add_poll (source, &child_watch_source->poll);
4197 #else /* G_OS_WIN32 */
4198 g_child_watch_source_init ();
4199 #endif /* G_OS_WIN32 */
4201 child_watch_source->pid = pid;
4207 * g_child_watch_add_full:
4208 * @priority: the priority of the idle source. Typically this will be in the
4209 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4210 * @pid: process to watch. On POSIX the pid of a child process. On
4211 * Windows a handle for a process (which doesn't have to be a child).
4212 * @function: function to call
4213 * @data: data to pass to @function
4214 * @notify: function to call when the idle is removed, or %NULL
4216 * Sets a function to be called when the child indicated by @pid
4217 * exits, at the priority @priority.
4219 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4220 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4221 * the spawn function for the child watching to work.
4223 * Note that on platforms where #GPid must be explicitly closed
4224 * (see g_spawn_close_pid()) @pid must not be closed while the
4225 * source is still active. Typically, you will want to call
4226 * g_spawn_close_pid() in the callback function for the source.
4228 * GLib supports only a single callback per process id.
4230 * This internally creates a main loop source using
4231 * g_child_watch_source_new() and attaches it to the main loop context
4232 * using g_source_attach(). You can do these steps manually if you
4233 * need greater control.
4235 * Return value: the ID (greater than 0) of the event source.
4240 g_child_watch_add_full (gint priority,
4242 GChildWatchFunc function,
4244 GDestroyNotify notify)
4249 g_return_val_if_fail (function != NULL, 0);
4251 source = g_child_watch_source_new (pid);
4253 if (priority != G_PRIORITY_DEFAULT)
4254 g_source_set_priority (source, priority);
4256 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4257 id = g_source_attach (source, NULL);
4258 g_source_unref (source);
4264 * g_child_watch_add:
4265 * @pid: process id to watch. On POSIX the pid of a child process. On
4266 * Windows a handle for a process (which doesn't have to be a child).
4267 * @function: function to call
4268 * @data: data to pass to @function
4270 * Sets a function to be called when the child indicated by @pid
4271 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4273 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4274 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4275 * the spawn function for the child watching to work.
4277 * Note that on platforms where #GPid must be explicitly closed
4278 * (see g_spawn_close_pid()) @pid must not be closed while the
4279 * source is still active. Typically, you will want to call
4280 * g_spawn_close_pid() in the callback function for the source.
4282 * GLib supports only a single callback per process id.
4284 * This internally creates a main loop source using
4285 * g_child_watch_source_new() and attaches it to the main loop context
4286 * using g_source_attach(). You can do these steps manually if you
4287 * need greater control.
4289 * Return value: the ID (greater than 0) of the event source.
4294 g_child_watch_add (GPid pid,
4295 GChildWatchFunc function,
4298 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4302 /* Idle functions */
4305 g_idle_prepare (GSource *source,
4314 g_idle_check (GSource *source)
4320 g_idle_dispatch (GSource *source,
4321 GSourceFunc callback,
4326 g_warning ("Idle source dispatched without callback\n"
4327 "You must call g_source_set_callback().");
4331 return callback (user_data);
4335 * g_idle_source_new:
4337 * Creates a new idle source.
4339 * The source will not initially be associated with any #GMainContext
4340 * and must be added to one with g_source_attach() before it will be
4341 * executed. Note that the default priority for idle sources is
4342 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4343 * have a default priority of %G_PRIORITY_DEFAULT.
4345 * Return value: the newly-created idle source
4348 g_idle_source_new (void)
4352 source = g_source_new (&g_idle_funcs, sizeof (GSource));
4353 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4360 * @priority: the priority of the idle source. Typically this will be in the
4361 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4362 * @function: function to call
4363 * @data: data to pass to @function
4364 * @notify: function to call when the idle is removed, or %NULL
4366 * Adds a function to be called whenever there are no higher priority
4367 * events pending. If the function returns %FALSE it is automatically
4368 * removed from the list of event sources and will not be called again.
4370 * This internally creates a main loop source using g_idle_source_new()
4371 * and attaches it to the main loop context using g_source_attach().
4372 * You can do these steps manually if you need greater control.
4374 * Return value: the ID (greater than 0) of the event source.
4377 g_idle_add_full (gint priority,
4378 GSourceFunc function,
4380 GDestroyNotify notify)
4385 g_return_val_if_fail (function != NULL, 0);
4387 source = g_idle_source_new ();
4389 if (priority != G_PRIORITY_DEFAULT_IDLE)
4390 g_source_set_priority (source, priority);
4392 g_source_set_callback (source, function, data, notify);
4393 id = g_source_attach (source, NULL);
4394 g_source_unref (source);
4401 * @function: function to call
4402 * @data: data to pass to @function.
4404 * Adds a function to be called whenever there are no higher priority
4405 * events pending to the default main loop. The function is given the
4406 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4407 * returns %FALSE it is automatically removed from the list of event
4408 * sources and will not be called again.
4410 * This internally creates a main loop source using g_idle_source_new()
4411 * and attaches it to the main loop context using g_source_attach().
4412 * You can do these steps manually if you need greater control.
4414 * Return value: the ID (greater than 0) of the event source.
4417 g_idle_add (GSourceFunc function,
4420 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4424 * g_idle_remove_by_data:
4425 * @data: the data for the idle source's callback.
4427 * Removes the idle function with the given data.
4429 * Return value: %TRUE if an idle source was found and removed.
4432 g_idle_remove_by_data (gpointer data)
4434 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4438 * g_main_context_invoke:
4439 * @context: a #GMainContext, or %NULL
4440 * @function: function to call
4441 * @data: data to pass to @function
4443 * Invokes a function in such a way that @context is owned during the
4444 * invocation of @function.
4446 * If @context is %NULL then the global default main context — as
4447 * returned by g_main_context_default() — is used.
4449 * If @context is owned by the current thread, @function is called
4450 * directly. Otherwise, if @context is the thread-default main context
4451 * of the current thread and g_main_context_acquire() succeeds, then
4452 * @function is called and g_main_context_release() is called
4455 * In any other case, an idle source is created to call @function and
4456 * that source is attached to @context (presumably to be run in another
4457 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
4458 * priority. If you want a different priority, use
4459 * g_main_context_invoke_full().
4461 * Note that, as with normal idle functions, @function should probably
4462 * return %FALSE. If it returns %TRUE, it will be continuously run in a
4463 * loop (and may prevent this call from returning).
4468 g_main_context_invoke (GMainContext *context,
4469 GSourceFunc function,
4472 g_main_context_invoke_full (context,
4474 function, data, NULL);
4478 * g_main_context_invoke_full:
4479 * @context: a #GMainContext, or %NULL
4480 * @priority: the priority at which to run @function
4481 * @function: function to call
4482 * @data: data to pass to @function
4483 * @notify: a function to call when @data is no longer in use, or %NULL.
4485 * Invokes a function in such a way that @context is owned during the
4486 * invocation of @function.
4488 * This function is the same as g_main_context_invoke() except that it
4489 * lets you specify the priority incase @function ends up being
4490 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
4492 * @notify should not assume that it is called from any particular
4493 * thread or with any particular context acquired.
4498 g_main_context_invoke_full (GMainContext *context,
4500 GSourceFunc function,
4502 GDestroyNotify notify)
4504 g_return_if_fail (function != NULL);
4507 context = g_main_context_default ();
4509 if (g_main_context_is_owner (context))
4511 while (function (data));
4518 GMainContext *thread_default;
4520 thread_default = g_main_context_get_thread_default ();
4522 if (!thread_default)
4523 thread_default = g_main_context_default ();
4525 if (thread_default == context && g_main_context_acquire (context))
4527 while (function (data));
4529 g_main_context_release (context);
4538 source = g_idle_source_new ();
4539 g_source_set_priority (source, priority);
4540 g_source_set_callback (source, function, data, notify);
4541 g_source_attach (source, context);
4542 g_source_unref (source);