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/.
34 /* for pipe2; need to define it first to avoid
35 * other headers pulling in unistd.h
40 #include "glibconfig.h"
42 /* Uncomment the next line (and the corresponding line in gpoll.c) to
43 * enable debugging printouts if the environment variable
44 * G_MAIN_POLL_DEBUG is set to some value.
46 /* #define G_MAIN_POLL_DEBUG */
49 /* Always enable debugging printout on Windows, as it is more often
52 #define G_MAIN_POLL_DEBUG
56 #include <sys/types.h>
59 #ifdef HAVE_SYS_TIME_H
61 #endif /* HAVE_SYS_TIME_H */
64 #endif /* HAVE_UNISTD_H */
70 #endif /* G_OS_WIN32 */
73 #include <sys/socket.h>
75 #endif /* G_OS_BEOS */
85 #include "giochannel.h"
89 #include "gstrfuncs.h"
90 #include "gtestutils.h"
91 #include "gthreadprivate.h"
95 * @title: The Main Event Loop
96 * @short_description: manages all available sources of events
98 * The main event loop manages all the available sources of events for
99 * GLib and GTK+ applications. These events can come from any number of
100 * different types of sources such as file descriptors (plain files,
101 * pipes or sockets) and timeouts. New types of event sources can also
102 * be added using g_source_attach().
104 * To allow multiple independent sets of sources to be handled in
105 * different threads, each source is associated with a #GMainContext.
106 * A GMainContext can only be running in a single thread, but
107 * sources can be added to it and removed from it from other threads.
109 * Each event source is assigned a priority. The default priority,
110 * #G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
111 * Values greater than 0 denote lower priorities. Events from high priority
112 * sources are always processed before events from lower priority sources.
114 * Idle functions can also be added, and assigned a priority. These will
115 * be run whenever no events with a higher priority are ready to be processed.
117 * The #GMainLoop data type represents a main event loop. A GMainLoop is
118 * created with g_main_loop_new(). After adding the initial event sources,
119 * g_main_loop_run() is called. This continuously checks for new events from
120 * each of the event sources and dispatches them. Finally, the processing of
121 * an event from one of the sources leads to a call to g_main_loop_quit() to
122 * exit the main loop, and g_main_loop_run() returns.
124 * It is possible to create new instances of #GMainLoop recursively.
125 * This is often used in GTK+ applications when showing modal dialog
126 * boxes. Note that event sources are associated with a particular
127 * #GMainContext, and will be checked and dispatched for all main
128 * loops associated with that GMainContext.
130 * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
131 * gtk_main_quit() and gtk_events_pending().
133 * <refsect2><title>Creating new source types</title>
134 * <para>One of the unusual features of the #GMainLoop functionality
135 * is that new types of event source can be created and used in
136 * addition to the builtin type of event source. A new event source
137 * type is used for handling GDK events. A new source type is created
138 * by <firstterm>deriving</firstterm> from the #GSource structure.
139 * The derived type of source is represented by a structure that has
140 * the #GSource structure as a first element, and other elements specific
141 * to the new source type. To create an instance of the new source type,
142 * call g_source_new() passing in the size of the derived structure and
143 * a table of functions. These #GSourceFuncs determine the behavior of
144 * the new source type.</para>
145 * <para>New source types basically interact with the main context
146 * in two ways. Their prepare function in #GSourceFuncs can set a timeout
147 * to determine the maximum amount of time that the main loop will sleep
148 * before checking the source again. In addition, or as well, the source
149 * can add file descriptors to the set that the main context checks using
150 * g_source_add_poll().</para>
152 * <refsect2><title>Customizing the main loop iteration</title>
153 * <para>Single iterations of a #GMainContext can be run with
154 * g_main_context_iteration(). In some cases, more detailed control
155 * of exactly how the details of the main loop work is desired, for
156 * instance, when integrating the #GMainLoop with an external main loop.
157 * In such cases, you can call the component functions of
158 * g_main_context_iteration() directly. These functions are
159 * g_main_context_prepare(), g_main_context_query(),
160 * g_main_context_check() and g_main_context_dispatch().</para>
161 * <para>The operation of these functions can best be seen in terms
162 * of a state diagram, as shown in <xref linkend="mainloop-states"/>.</para>
163 * <figure id="mainloop-states"><title>States of a Main Context</title>
164 * <graphic fileref="mainloop-states.gif" format="GIF"></graphic>
171 typedef struct _GTimeoutSource GTimeoutSource;
172 typedef struct _GChildWatchSource GChildWatchSource;
173 typedef struct _GPollRec GPollRec;
174 typedef struct _GSourceCallback GSourceCallback;
178 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
179 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
182 #ifdef G_THREADS_ENABLED
183 typedef struct _GMainWaiter GMainWaiter;
192 typedef struct _GMainDispatch GMainDispatch;
194 struct _GMainDispatch
197 GSList *dispatching_sources; /* stack of current sources */
200 #ifdef G_MAIN_POLL_DEBUG
201 gboolean _g_main_poll_debug = FALSE;
206 #ifdef G_THREADS_ENABLED
207 /* The following lock is used for both the list of sources
208 * and the list of poll records
219 GPtrArray *pending_dispatches;
220 gint timeout; /* Timeout for current iteration */
223 GSource *source_list;
224 gint in_check_or_prepare;
226 GPollRec *poll_records;
227 guint n_poll_records;
228 GPollFD *cached_poll_array;
229 guint cached_poll_array_size;
231 #ifdef G_THREADS_ENABLED
233 /* this pipe is used to wake up the main loop when a source is added.
235 gint wake_up_pipe[2];
236 #else /* G_OS_WIN32 */
237 HANDLE wake_up_semaphore;
238 #endif /* G_OS_WIN32 */
241 gboolean poll_waiting;
243 /* Flag indicating whether the set of fd's changed during a poll */
244 gboolean poll_changed;
245 #endif /* G_THREADS_ENABLED */
249 GTimeVal current_time;
250 gboolean time_is_current;
253 struct _GSourceCallback
258 GDestroyNotify notify;
263 GMainContext *context;
268 struct _GTimeoutSource
276 struct _GChildWatchSource
283 #else /* G_OS_WIN32 */
285 gboolean child_exited;
286 #endif /* G_OS_WIN32 */
296 #ifdef G_THREADS_ENABLED
297 #define LOCK_CONTEXT(context) g_static_mutex_lock (&context->mutex)
298 #define UNLOCK_CONTEXT(context) g_static_mutex_unlock (&context->mutex)
299 #define G_THREAD_SELF g_thread_self ()
301 #define LOCK_CONTEXT(context) (void)0
302 #define UNLOCK_CONTEXT(context) (void)0
303 #define G_THREAD_SELF NULL
306 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
307 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
308 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
310 #define SOURCE_UNREF(source, context) \
312 if ((source)->ref_count > 1) \
313 (source)->ref_count--; \
315 g_source_unref_internal ((source), (context), TRUE); \
319 /* Forward declarations */
321 static void g_source_unref_internal (GSource *source,
322 GMainContext *context,
324 static void g_source_destroy_internal (GSource *source,
325 GMainContext *context,
327 static void g_main_context_poll (GMainContext *context,
332 static void g_main_context_add_poll_unlocked (GMainContext *context,
335 static void g_main_context_remove_poll_unlocked (GMainContext *context,
337 static void g_main_context_wakeup_unlocked (GMainContext *context);
339 static gboolean g_timeout_prepare (GSource *source,
341 static gboolean g_timeout_check (GSource *source);
342 static gboolean g_timeout_dispatch (GSource *source,
343 GSourceFunc callback,
345 static gboolean g_child_watch_prepare (GSource *source,
347 static gboolean g_child_watch_check (GSource *source);
348 static gboolean g_child_watch_dispatch (GSource *source,
349 GSourceFunc callback,
351 static gboolean g_idle_prepare (GSource *source,
353 static gboolean g_idle_check (GSource *source);
354 static gboolean g_idle_dispatch (GSource *source,
355 GSourceFunc callback,
358 G_LOCK_DEFINE_STATIC (main_loop);
359 static GMainContext *default_main_context;
360 static GSList *main_contexts_without_pipe = NULL;
363 /* Child status monitoring code */
365 CHILD_WATCH_UNINITIALIZED,
366 CHILD_WATCH_INITIALIZED_SINGLE,
367 CHILD_WATCH_INITIALIZED_THREADED
369 static gint child_watch_init_state = CHILD_WATCH_UNINITIALIZED;
370 static gint child_watch_count = 1;
371 static gint child_watch_wake_up_pipe[2] = {0, 0};
372 #endif /* !G_OS_WIN32 */
373 G_LOCK_DEFINE_STATIC (main_context_list);
374 static GSList *main_context_list = NULL;
376 static gint timer_perturb = -1;
378 GSourceFuncs g_timeout_funcs =
386 GSourceFuncs g_child_watch_funcs =
388 g_child_watch_prepare,
390 g_child_watch_dispatch,
394 GSourceFuncs g_idle_funcs =
403 * g_main_context_ref:
404 * @context: a #GMainContext
406 * Increases the reference count on a #GMainContext object by one.
408 * Returns: the @context that was passed in (since 2.6)
411 g_main_context_ref (GMainContext *context)
413 g_return_val_if_fail (context != NULL, NULL);
414 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
416 g_atomic_int_inc (&context->ref_count);
422 poll_rec_list_free (GMainContext *context,
425 g_slice_free_chain (GPollRec, list, next);
429 * g_main_context_unref:
430 * @context: a #GMainContext
432 * Decreases the reference count on a #GMainContext object by one. If
433 * the result is zero, free the context and free all associated memory.
436 g_main_context_unref (GMainContext *context)
439 g_return_if_fail (context != NULL);
440 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
442 if (!g_atomic_int_dec_and_test (&context->ref_count))
445 G_LOCK (main_context_list);
446 main_context_list = g_slist_remove (main_context_list, context);
447 G_UNLOCK (main_context_list);
449 source = context->source_list;
452 GSource *next = source->next;
453 g_source_destroy_internal (source, context, FALSE);
457 #ifdef G_THREADS_ENABLED
458 g_static_mutex_free (&context->mutex);
461 g_ptr_array_free (context->pending_dispatches, TRUE);
462 g_free (context->cached_poll_array);
464 poll_rec_list_free (context, context->poll_records);
466 #ifdef G_THREADS_ENABLED
467 if (g_thread_supported())
470 close (context->wake_up_pipe[0]);
471 close (context->wake_up_pipe[1]);
473 CloseHandle (context->wake_up_semaphore);
477 main_contexts_without_pipe = g_slist_remove (main_contexts_without_pipe,
480 if (context->cond != NULL)
481 g_cond_free (context->cond);
487 #ifdef G_THREADS_ENABLED
489 g_main_context_init_pipe (GMainContext *context)
492 if (context->wake_up_pipe[0] != -1)
496 /* if this fails, we fall through and try pipe */
497 pipe2 (context->wake_up_pipe, O_CLOEXEC);
499 if (context->wake_up_pipe[0] == -1)
501 if (pipe (context->wake_up_pipe) < 0)
502 g_error ("Cannot create pipe main loop wake-up: %s\n",
505 fcntl (context->wake_up_pipe[0], F_SETFD, FD_CLOEXEC);
506 fcntl (context->wake_up_pipe[1], F_SETFD, FD_CLOEXEC);
509 context->wake_up_rec.fd = context->wake_up_pipe[0];
510 context->wake_up_rec.events = G_IO_IN;
512 if (context->wake_up_semaphore != NULL)
514 context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
515 if (context->wake_up_semaphore == NULL)
516 g_error ("Cannot create wake-up semaphore: %s",
517 g_win32_error_message (GetLastError ()));
518 context->wake_up_rec.fd = (gintptr) context->wake_up_semaphore;
519 context->wake_up_rec.events = G_IO_IN;
521 if (_g_main_poll_debug)
522 g_print ("wake-up semaphore: %p\n", context->wake_up_semaphore);
524 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
528 _g_main_thread_init (void)
530 GSList *curr = main_contexts_without_pipe;
533 g_main_context_init_pipe ((GMainContext *)curr->data);
536 g_slist_free (main_contexts_without_pipe);
537 main_contexts_without_pipe = NULL;
539 #endif /* G_THREADS_ENABLED */
542 * g_main_context_new:
544 * Creates a new #GMainContext structure.
546 * Return value: the new #GMainContext
549 g_main_context_new (void)
551 GMainContext *context = g_new0 (GMainContext, 1);
553 #ifdef G_MAIN_POLL_DEBUG
555 static gboolean beenhere = FALSE;
559 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
560 _g_main_poll_debug = TRUE;
566 #ifdef G_THREADS_ENABLED
567 g_static_mutex_init (&context->mutex);
569 context->owner = NULL;
570 context->waiters = NULL;
573 context->wake_up_pipe[0] = -1;
574 context->wake_up_pipe[1] = -1;
576 context->wake_up_semaphore = NULL;
580 context->ref_count = 1;
582 context->next_id = 1;
584 context->source_list = NULL;
586 context->poll_func = g_poll;
588 context->cached_poll_array = NULL;
589 context->cached_poll_array_size = 0;
591 context->pending_dispatches = g_ptr_array_new ();
593 context->time_is_current = FALSE;
595 #ifdef G_THREADS_ENABLED
596 if (g_thread_supported ())
597 g_main_context_init_pipe (context);
599 main_contexts_without_pipe = g_slist_prepend (main_contexts_without_pipe,
603 G_LOCK (main_context_list);
604 main_context_list = g_slist_append (main_context_list, context);
606 #ifdef G_MAIN_POLL_DEBUG
607 if (_g_main_poll_debug)
608 g_print ("created context=%p\n", context);
611 G_UNLOCK (main_context_list);
617 * g_main_context_default:
619 * Returns the global default main context. This is the main context
620 * used for main loop functions when a main loop is not explicitly
621 * specified, and corresponds to the "main" main loop. See also
622 * g_main_context_get_thread_default().
624 * Return value: the global default main context.
627 g_main_context_default (void)
633 if (!default_main_context)
635 default_main_context = g_main_context_new ();
636 #ifdef G_MAIN_POLL_DEBUG
637 if (_g_main_poll_debug)
638 g_print ("default context=%p\n", default_main_context);
642 G_UNLOCK (main_loop);
644 return default_main_context;
647 static GStaticPrivate thread_context_stack = G_STATIC_PRIVATE_INIT;
650 free_context_stack (gpointer data)
652 GQueue *stack = data;
653 GMainContext *context;
655 while (!g_queue_is_empty (stack))
657 context = g_queue_pop_head (stack);
658 g_main_context_release (context);
660 g_main_context_unref (context);
662 g_queue_free (stack);
666 * g_main_context_push_thread_default:
667 * @context: a #GMainContext, or %NULL for the global default context
669 * Acquires @context and sets it as the thread-default context for the
670 * current thread. This will cause certain asynchronous operations
671 * (such as most <link linkend="gio">gio</link>-based I/O) which are
672 * started in this thread to run under @context and deliver their
673 * results to its main loop, rather than running under the global
674 * default context in the main thread. Note that calling this function
675 * changes the context returned by
676 * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
677 * one returned by g_main_context_default(), so it does not affect the
678 * context used by functions like g_idle_add().
680 * Normally you would call this function shortly after creating a new
681 * thread, passing it a #GMainContext which will be run by a
682 * #GMainLoop in that thread, to set a new default context for all
683 * async operations in that thread. (In this case, you don't need to
684 * ever call g_main_context_pop_thread_default().) In some cases
685 * however, you may want to schedule a single operation in a
686 * non-default context, or temporarily use a non-default context in
687 * the main thread. In that case, you can wrap the call to the
688 * asynchronous operation inside a
689 * g_main_context_push_thread_default() /
690 * g_main_context_pop_thread_default() pair, but it is up to you to
691 * ensure that no other asynchronous operations accidentally get
692 * started while the non-default context is active.
694 * Beware that libraries that predate this function may not correctly
695 * handle being used from a thread with a thread-default context. Eg,
696 * see g_file_supports_thread_contexts().
701 g_main_context_push_thread_default (GMainContext *context)
704 gboolean acquired_context;
706 acquired_context = g_main_context_acquire (context);
707 g_return_if_fail (acquired_context);
709 if (context == g_main_context_default ())
712 g_main_context_ref (context);
714 stack = g_static_private_get (&thread_context_stack);
717 stack = g_queue_new ();
718 g_static_private_set (&thread_context_stack, stack,
722 g_queue_push_head (stack, context);
726 * g_main_context_pop_thread_default:
727 * @context: a #GMainContext object, or %NULL
729 * Pops @context off the thread-default context stack (verifying that
730 * it was on the top of the stack).
735 g_main_context_pop_thread_default (GMainContext *context)
739 if (context == g_main_context_default ())
742 stack = g_static_private_get (&thread_context_stack);
744 g_return_if_fail (stack != NULL);
745 g_return_if_fail (g_queue_peek_head (stack) == context);
747 g_queue_pop_head (stack);
749 g_main_context_release (context);
751 g_main_context_unref (context);
755 * g_main_context_get_thread_default:
757 * Gets the thread-default #GMainContext for this thread. Asynchronous
758 * operations that want to be able to be run in contexts other than
759 * the default one should call this method to get a #GMainContext to
760 * add their #GSource<!-- -->s to. (Note that even in single-threaded
761 * programs applications may sometimes want to temporarily push a
762 * non-default context, so it is not safe to assume that this will
763 * always return %NULL if threads are not initialized.)
765 * Returns: the thread-default #GMainContext, or %NULL if the
766 * thread-default context is the global default context.
771 g_main_context_get_thread_default (void)
775 stack = g_static_private_get (&thread_context_stack);
777 return g_queue_peek_head (stack);
782 /* Hooks for adding to the main loop */
786 * @source_funcs: structure containing functions that implement
787 * the sources behavior.
788 * @struct_size: size of the #GSource structure to create.
790 * Creates a new #GSource structure. The size is specified to
791 * allow creating structures derived from #GSource that contain
792 * additional data. The size passed in must be at least
793 * <literal>sizeof (GSource)</literal>.
795 * The source will not initially be associated with any #GMainContext
796 * and must be added to one with g_source_attach() before it will be
799 * Return value: the newly-created #GSource.
802 g_source_new (GSourceFuncs *source_funcs,
807 g_return_val_if_fail (source_funcs != NULL, NULL);
808 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
810 source = (GSource*) g_malloc0 (struct_size);
812 source->source_funcs = source_funcs;
813 source->ref_count = 1;
815 source->priority = G_PRIORITY_DEFAULT;
817 source->flags = G_HOOK_FLAG_ACTIVE;
819 /* NULL/0 initialization for all other fields */
824 /* Holds context's lock
827 g_source_list_add (GSource *source,
828 GMainContext *context)
830 GSource *tmp_source, *last_source;
833 tmp_source = context->source_list;
834 while (tmp_source && tmp_source->priority <= source->priority)
836 last_source = tmp_source;
837 tmp_source = tmp_source->next;
840 source->next = tmp_source;
842 tmp_source->prev = source;
844 source->prev = last_source;
846 last_source->next = source;
848 context->source_list = source;
851 /* Holds context's lock
854 g_source_list_remove (GSource *source,
855 GMainContext *context)
858 source->prev->next = source->next;
860 context->source_list = source->next;
863 source->next->prev = source->prev;
871 * @source: a #GSource
872 * @context: a #GMainContext (if %NULL, the default context will be used)
874 * Adds a #GSource to a @context so that it will be executed within
875 * that context. Remove it by calling g_source_destroy().
877 * Return value: the ID (greater than 0) for the source within the
881 g_source_attach (GSource *source,
882 GMainContext *context)
887 g_return_val_if_fail (source->context == NULL, 0);
888 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
891 context = g_main_context_default ();
893 LOCK_CONTEXT (context);
895 source->context = context;
896 result = source->source_id = context->next_id++;
899 g_source_list_add (source, context);
901 tmp_list = source->poll_fds;
904 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
905 tmp_list = tmp_list->next;
908 #ifdef G_THREADS_ENABLED
909 /* Now wake up the main loop if it is waiting in the poll() */
910 g_main_context_wakeup_unlocked (context);
913 UNLOCK_CONTEXT (context);
919 g_source_destroy_internal (GSource *source,
920 GMainContext *context,
924 LOCK_CONTEXT (context);
926 if (!SOURCE_DESTROYED (source))
929 gpointer old_cb_data;
930 GSourceCallbackFuncs *old_cb_funcs;
932 source->flags &= ~G_HOOK_FLAG_ACTIVE;
934 old_cb_data = source->callback_data;
935 old_cb_funcs = source->callback_funcs;
937 source->callback_data = NULL;
938 source->callback_funcs = NULL;
942 UNLOCK_CONTEXT (context);
943 old_cb_funcs->unref (old_cb_data);
944 LOCK_CONTEXT (context);
947 if (!SOURCE_BLOCKED (source))
949 tmp_list = source->poll_fds;
952 g_main_context_remove_poll_unlocked (context, tmp_list->data);
953 tmp_list = tmp_list->next;
957 g_source_unref_internal (source, context, TRUE);
961 UNLOCK_CONTEXT (context);
966 * @source: a #GSource
968 * Removes a source from its #GMainContext, if any, and mark it as
969 * destroyed. The source cannot be subsequently added to another
973 g_source_destroy (GSource *source)
975 GMainContext *context;
977 g_return_if_fail (source != NULL);
979 context = source->context;
982 g_source_destroy_internal (source, context, FALSE);
984 source->flags &= ~G_HOOK_FLAG_ACTIVE;
989 * @source: a #GSource
991 * Returns the numeric ID for a particular source. The ID of a source
992 * is a positive integer which is unique within a particular main loop
993 * context. The reverse
994 * mapping from ID to source is done by g_main_context_find_source_by_id().
996 * Return value: the ID (greater than 0) for the source
999 g_source_get_id (GSource *source)
1003 g_return_val_if_fail (source != NULL, 0);
1004 g_return_val_if_fail (source->context != NULL, 0);
1006 LOCK_CONTEXT (source->context);
1007 result = source->source_id;
1008 UNLOCK_CONTEXT (source->context);
1014 * g_source_get_context:
1015 * @source: a #GSource
1017 * Gets the #GMainContext with which the source is associated.
1018 * Calling this function on a destroyed source is an error.
1020 * Return value: the #GMainContext with which the source is associated,
1021 * or %NULL if the context has not yet been added
1025 g_source_get_context (GSource *source)
1027 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1029 return source->context;
1033 * g_source_add_poll:
1034 * @source:a #GSource
1035 * @fd: a #GPollFD structure holding information about a file
1036 * descriptor to watch.
1038 * Adds a file descriptor to the set of file descriptors polled for
1039 * this source. This is usually combined with g_source_new() to add an
1040 * event source. The event source's check function will typically test
1041 * the @revents field in the #GPollFD struct and return %TRUE if events need
1045 g_source_add_poll (GSource *source,
1048 GMainContext *context;
1050 g_return_if_fail (source != NULL);
1051 g_return_if_fail (fd != NULL);
1052 g_return_if_fail (!SOURCE_DESTROYED (source));
1054 context = source->context;
1057 LOCK_CONTEXT (context);
1059 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1063 if (!SOURCE_BLOCKED (source))
1064 g_main_context_add_poll_unlocked (context, source->priority, fd);
1065 UNLOCK_CONTEXT (context);
1070 * g_source_remove_poll:
1071 * @source:a #GSource
1072 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1074 * Removes a file descriptor from the set of file descriptors polled for
1078 g_source_remove_poll (GSource *source,
1081 GMainContext *context;
1083 g_return_if_fail (source != NULL);
1084 g_return_if_fail (fd != NULL);
1085 g_return_if_fail (!SOURCE_DESTROYED (source));
1087 context = source->context;
1090 LOCK_CONTEXT (context);
1092 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1096 if (!SOURCE_BLOCKED (source))
1097 g_main_context_remove_poll_unlocked (context, fd);
1098 UNLOCK_CONTEXT (context);
1103 * g_source_set_callback_indirect:
1104 * @source: the source
1105 * @callback_data: pointer to callback data "object"
1106 * @callback_funcs: functions for reference counting @callback_data
1107 * and getting the callback and data
1109 * Sets the callback function storing the data as a refcounted callback
1110 * "object". This is used internally. Note that calling
1111 * g_source_set_callback_indirect() assumes
1112 * an initial reference count on @callback_data, and thus
1113 * @callback_funcs->unref will eventually be called once more
1114 * than @callback_funcs->ref.
1117 g_source_set_callback_indirect (GSource *source,
1118 gpointer callback_data,
1119 GSourceCallbackFuncs *callback_funcs)
1121 GMainContext *context;
1122 gpointer old_cb_data;
1123 GSourceCallbackFuncs *old_cb_funcs;
1125 g_return_if_fail (source != NULL);
1126 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1128 context = source->context;
1131 LOCK_CONTEXT (context);
1133 old_cb_data = source->callback_data;
1134 old_cb_funcs = source->callback_funcs;
1136 source->callback_data = callback_data;
1137 source->callback_funcs = callback_funcs;
1140 UNLOCK_CONTEXT (context);
1143 old_cb_funcs->unref (old_cb_data);
1147 g_source_callback_ref (gpointer cb_data)
1149 GSourceCallback *callback = cb_data;
1151 callback->ref_count++;
1156 g_source_callback_unref (gpointer cb_data)
1158 GSourceCallback *callback = cb_data;
1160 callback->ref_count--;
1161 if (callback->ref_count == 0)
1163 if (callback->notify)
1164 callback->notify (callback->data);
1170 g_source_callback_get (gpointer cb_data,
1175 GSourceCallback *callback = cb_data;
1177 *func = callback->func;
1178 *data = callback->data;
1181 static GSourceCallbackFuncs g_source_callback_funcs = {
1182 g_source_callback_ref,
1183 g_source_callback_unref,
1184 g_source_callback_get,
1188 * g_source_set_callback:
1189 * @source: the source
1190 * @func: a callback function
1191 * @data: the data to pass to callback function
1192 * @notify: a function to call when @data is no longer in use, or %NULL.
1194 * Sets the callback function for a source. The callback for a source is
1195 * called from the source's dispatch function.
1197 * The exact type of @func depends on the type of source; ie. you
1198 * should not count on @func being called with @data as its first
1201 * Typically, you won't use this function. Instead use functions specific
1202 * to the type of source you are using.
1205 g_source_set_callback (GSource *source,
1208 GDestroyNotify notify)
1210 GSourceCallback *new_callback;
1212 g_return_if_fail (source != NULL);
1214 new_callback = g_new (GSourceCallback, 1);
1216 new_callback->ref_count = 1;
1217 new_callback->func = func;
1218 new_callback->data = data;
1219 new_callback->notify = notify;
1221 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1226 * g_source_set_funcs:
1227 * @source: a #GSource
1228 * @funcs: the new #GSourceFuncs
1230 * Sets the source functions (can be used to override
1231 * default implementations) of an unattached source.
1236 g_source_set_funcs (GSource *source,
1237 GSourceFuncs *funcs)
1239 g_return_if_fail (source != NULL);
1240 g_return_if_fail (source->context == NULL);
1241 g_return_if_fail (source->ref_count > 0);
1242 g_return_if_fail (funcs != NULL);
1244 source->source_funcs = funcs;
1248 * g_source_set_priority:
1249 * @source: a #GSource
1250 * @priority: the new priority.
1252 * Sets the priority of a source. While the main loop is being
1253 * run, a source will be dispatched if it is ready to be dispatched and no sources
1254 * at a higher (numerically smaller) priority are ready to be dispatched.
1257 g_source_set_priority (GSource *source,
1261 GMainContext *context;
1263 g_return_if_fail (source != NULL);
1265 context = source->context;
1268 LOCK_CONTEXT (context);
1270 source->priority = priority;
1274 /* Remove the source from the context's source and then
1275 * add it back so it is sorted in the correct plcae
1277 g_source_list_remove (source, source->context);
1278 g_source_list_add (source, source->context);
1280 if (!SOURCE_BLOCKED (source))
1282 tmp_list = source->poll_fds;
1285 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1286 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1288 tmp_list = tmp_list->next;
1292 UNLOCK_CONTEXT (source->context);
1297 * g_source_get_priority:
1298 * @source: a #GSource
1300 * Gets the priority of a source.
1302 * Return value: the priority of the source
1305 g_source_get_priority (GSource *source)
1307 g_return_val_if_fail (source != NULL, 0);
1309 return source->priority;
1313 * g_source_set_can_recurse:
1314 * @source: a #GSource
1315 * @can_recurse: whether recursion is allowed for this source
1317 * Sets whether a source can be called recursively. If @can_recurse is
1318 * %TRUE, then while the source is being dispatched then this source
1319 * will be processed normally. Otherwise, all processing of this
1320 * source is blocked until the dispatch function returns.
1323 g_source_set_can_recurse (GSource *source,
1324 gboolean can_recurse)
1326 GMainContext *context;
1328 g_return_if_fail (source != NULL);
1330 context = source->context;
1333 LOCK_CONTEXT (context);
1336 source->flags |= G_SOURCE_CAN_RECURSE;
1338 source->flags &= ~G_SOURCE_CAN_RECURSE;
1341 UNLOCK_CONTEXT (context);
1345 * g_source_get_can_recurse:
1346 * @source: a #GSource
1348 * Checks whether a source is allowed to be called recursively.
1349 * see g_source_set_can_recurse().
1351 * Return value: whether recursion is allowed.
1354 g_source_get_can_recurse (GSource *source)
1356 g_return_val_if_fail (source != NULL, FALSE);
1358 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1363 * g_source_set_name:
1364 * @source: a #GSource
1365 * @name: debug name for the source
1367 * Sets a name for the source, used in debugging and profiling.
1368 * The name defaults to #NULL.
1370 * The source name should describe in a human-readable way
1371 * what the source does. For example, "X11 event queue"
1372 * or "GTK+ repaint idle handler" or whatever it is.
1374 * It is permitted to call this function multiple times, but is not
1375 * recommended due to the potential performance impact. For example,
1376 * one could change the name in the "check" function of a #GSourceFuncs
1377 * to include details like the event type in the source name.
1382 g_source_set_name (GSource *source,
1385 g_return_if_fail (source != NULL);
1387 /* setting back to NULL is allowed, just because it's
1388 * weird if get_name can return NULL but you can't
1392 g_free (source->name);
1393 source->name = g_strdup (name);
1397 * g_source_get_name:
1398 * @source: a #GSource
1400 * Gets a name for the source, used in debugging and profiling.
1401 * The name may be #NULL if it has never been set with
1402 * g_source_set_name().
1404 * Return value: the name of the source
1407 G_CONST_RETURN char*
1408 g_source_get_name (GSource *source)
1410 g_return_val_if_fail (source != NULL, NULL);
1412 return source->name;
1416 * g_source_set_name_by_id:
1417 * @tag: a #GSource ID
1418 * @name: debug name for the source
1420 * Sets the name of a source using its ID.
1422 * This is a convenience utility to set source names from the return
1423 * value of g_idle_add(), g_timeout_add(), etc.
1428 g_source_set_name_by_id (guint tag,
1433 g_return_if_fail (tag > 0);
1435 source = g_main_context_find_source_by_id (NULL, tag);
1439 g_source_set_name (source, name);
1445 * @source: a #GSource
1447 * Increases the reference count on a source by one.
1449 * Return value: @source
1452 g_source_ref (GSource *source)
1454 GMainContext *context;
1456 g_return_val_if_fail (source != NULL, NULL);
1458 context = source->context;
1461 LOCK_CONTEXT (context);
1463 source->ref_count++;
1466 UNLOCK_CONTEXT (context);
1471 /* g_source_unref() but possible to call within context lock
1474 g_source_unref_internal (GSource *source,
1475 GMainContext *context,
1478 gpointer old_cb_data = NULL;
1479 GSourceCallbackFuncs *old_cb_funcs = NULL;
1481 g_return_if_fail (source != NULL);
1483 if (!have_lock && context)
1484 LOCK_CONTEXT (context);
1486 source->ref_count--;
1487 if (source->ref_count == 0)
1489 old_cb_data = source->callback_data;
1490 old_cb_funcs = source->callback_funcs;
1492 source->callback_data = NULL;
1493 source->callback_funcs = NULL;
1495 if (context && !SOURCE_DESTROYED (source))
1497 g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1498 source->ref_count++;
1501 g_source_list_remove (source, context);
1503 if (source->source_funcs->finalize)
1504 source->source_funcs->finalize (source);
1506 g_free (source->name);
1507 source->name = NULL;
1509 g_slist_free (source->poll_fds);
1510 source->poll_fds = NULL;
1514 if (!have_lock && context)
1515 UNLOCK_CONTEXT (context);
1520 UNLOCK_CONTEXT (context);
1522 old_cb_funcs->unref (old_cb_data);
1525 LOCK_CONTEXT (context);
1531 * @source: a #GSource
1533 * Decreases the reference count of a source by one. If the
1534 * resulting reference count is zero the source and associated
1535 * memory will be destroyed.
1538 g_source_unref (GSource *source)
1540 g_return_if_fail (source != NULL);
1542 g_source_unref_internal (source, source->context, FALSE);
1546 * g_main_context_find_source_by_id:
1547 * @context: a #GMainContext (if %NULL, the default context will be used)
1548 * @source_id: the source ID, as returned by g_source_get_id().
1550 * Finds a #GSource given a pair of context and ID.
1552 * Return value: the #GSource if found, otherwise, %NULL
1555 g_main_context_find_source_by_id (GMainContext *context,
1560 g_return_val_if_fail (source_id > 0, NULL);
1562 if (context == NULL)
1563 context = g_main_context_default ();
1565 LOCK_CONTEXT (context);
1567 source = context->source_list;
1570 if (!SOURCE_DESTROYED (source) &&
1571 source->source_id == source_id)
1573 source = source->next;
1576 UNLOCK_CONTEXT (context);
1582 * g_main_context_find_source_by_funcs_user_data:
1583 * @context: a #GMainContext (if %NULL, the default context will be used).
1584 * @funcs: the @source_funcs passed to g_source_new().
1585 * @user_data: the user data from the callback.
1587 * Finds a source with the given source functions and user data. If
1588 * multiple sources exist with the same source function and user data,
1589 * the first one found will be returned.
1591 * Return value: the source, if one was found, otherwise %NULL
1594 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1595 GSourceFuncs *funcs,
1600 g_return_val_if_fail (funcs != NULL, NULL);
1602 if (context == NULL)
1603 context = g_main_context_default ();
1605 LOCK_CONTEXT (context);
1607 source = context->source_list;
1610 if (!SOURCE_DESTROYED (source) &&
1611 source->source_funcs == funcs &&
1612 source->callback_funcs)
1614 GSourceFunc callback;
1615 gpointer callback_data;
1617 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1619 if (callback_data == user_data)
1622 source = source->next;
1625 UNLOCK_CONTEXT (context);
1631 * g_main_context_find_source_by_user_data:
1632 * @context: a #GMainContext
1633 * @user_data: the user_data for the callback.
1635 * Finds a source with the given user data for the callback. If
1636 * multiple sources exist with the same user data, the first
1637 * one found will be returned.
1639 * Return value: the source, if one was found, otherwise %NULL
1642 g_main_context_find_source_by_user_data (GMainContext *context,
1647 if (context == NULL)
1648 context = g_main_context_default ();
1650 LOCK_CONTEXT (context);
1652 source = context->source_list;
1655 if (!SOURCE_DESTROYED (source) &&
1656 source->callback_funcs)
1658 GSourceFunc callback;
1659 gpointer callback_data = NULL;
1661 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1663 if (callback_data == user_data)
1666 source = source->next;
1669 UNLOCK_CONTEXT (context);
1676 * @tag: the ID of the source to remove.
1678 * Removes the source with the given id from the default main context.
1680 * a #GSource is given by g_source_get_id(), or will be returned by the
1681 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1682 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1683 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1685 * See also g_source_destroy(). You must use g_source_destroy() for sources
1686 * added to a non-default main context.
1688 * Return value: %TRUE if the source was found and removed.
1691 g_source_remove (guint tag)
1695 g_return_val_if_fail (tag > 0, FALSE);
1697 source = g_main_context_find_source_by_id (NULL, tag);
1699 g_source_destroy (source);
1701 return source != NULL;
1705 * g_source_remove_by_user_data:
1706 * @user_data: the user_data for the callback.
1708 * Removes a source from the default main loop context given the user
1709 * data for the callback. If multiple sources exist with the same user
1710 * data, only one will be destroyed.
1712 * Return value: %TRUE if a source was found and removed.
1715 g_source_remove_by_user_data (gpointer user_data)
1719 source = g_main_context_find_source_by_user_data (NULL, user_data);
1722 g_source_destroy (source);
1730 * g_source_remove_by_funcs_user_data:
1731 * @funcs: The @source_funcs passed to g_source_new()
1732 * @user_data: the user data for the callback
1734 * Removes a source from the default main loop context given the
1735 * source functions and user data. If multiple sources exist with the
1736 * same source functions and user data, only one will be destroyed.
1738 * Return value: %TRUE if a source was found and removed.
1741 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1746 g_return_val_if_fail (funcs != NULL, FALSE);
1748 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1751 g_source_destroy (source);
1759 * g_get_current_time:
1760 * @result: #GTimeVal structure in which to store current time.
1762 * Equivalent to the UNIX gettimeofday() function, but portable.
1765 g_get_current_time (GTimeVal *result)
1770 g_return_if_fail (result != NULL);
1772 /*this is required on alpha, there the timeval structs are int's
1773 not longs and a cast only would fail horribly*/
1774 gettimeofday (&r, NULL);
1775 result->tv_sec = r.tv_sec;
1776 result->tv_usec = r.tv_usec;
1781 g_return_if_fail (result != NULL);
1783 GetSystemTimeAsFileTime (&ft);
1784 memmove (&time64, &ft, sizeof (FILETIME));
1786 /* Convert from 100s of nanoseconds since 1601-01-01
1787 * to Unix epoch. Yes, this is Y2038 unsafe.
1789 time64 -= G_GINT64_CONSTANT (116444736000000000);
1792 result->tv_sec = time64 / 1000000;
1793 result->tv_usec = time64 % 1000000;
1798 g_main_dispatch_free (gpointer dispatch)
1800 g_slice_free (GMainDispatch, dispatch);
1803 /* Running the main loop */
1805 static GMainDispatch *
1808 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
1809 GMainDispatch *dispatch = g_static_private_get (&depth_private);
1812 dispatch = g_slice_new0 (GMainDispatch);
1813 g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
1822 * Returns the depth of the stack of calls to
1823 * g_main_context_dispatch() on any #GMainContext in the current thread.
1824 * That is, when called from the toplevel, it gives 0. When
1825 * called from within a callback from g_main_context_iteration()
1826 * (or g_main_loop_run(), etc.) it returns 1. When called from within
1827 * a callback to a recursive call to g_main_context_iterate(),
1828 * it returns 2. And so forth.
1830 * This function is useful in a situation like the following:
1831 * Imagine an extremely simple "garbage collected" system.
1834 * static GList *free_list;
1837 * allocate_memory (gsize size)
1839 * gpointer result = g_malloc (size);
1840 * free_list = g_list_prepend (free_list, result);
1845 * free_allocated_memory (void)
1848 * for (l = free_list; l; l = l->next);
1850 * g_list_free (free_list);
1858 * g_main_context_iteration (NULL, TRUE);
1859 * free_allocated_memory();
1863 * This works from an application, however, if you want to do the same
1864 * thing from a library, it gets more difficult, since you no longer
1865 * control the main loop. You might think you can simply use an idle
1866 * function to make the call to free_allocated_memory(), but that
1867 * doesn't work, since the idle function could be called from a
1868 * recursive callback. This can be fixed by using g_main_depth()
1872 * allocate_memory (gsize size)
1874 * FreeListBlock *block = g_new (FreeListBlock, 1);
1875 * block->mem = g_malloc (size);
1876 * block->depth = g_main_depth ();
1877 * free_list = g_list_prepend (free_list, block);
1878 * return block->mem;
1882 * free_allocated_memory (void)
1886 * int depth = g_main_depth ();
1887 * for (l = free_list; l; );
1889 * GList *next = l->next;
1890 * FreeListBlock *block = l->data;
1891 * if (block->depth > depth)
1893 * g_free (block->mem);
1895 * free_list = g_list_delete_link (free_list, l);
1903 * There is a temptation to use g_main_depth() to solve
1904 * problems with reentrancy. For instance, while waiting for data
1905 * to be received from the network in response to a menu item,
1906 * the menu item might be selected again. It might seem that
1907 * one could make the menu item's callback return immediately
1908 * and do nothing if g_main_depth() returns a value greater than 1.
1909 * However, this should be avoided since the user then sees selecting
1910 * the menu item do nothing. Furthermore, you'll find yourself adding
1911 * these checks all over your code, since there are doubtless many,
1912 * many things that the user could do. Instead, you can use the
1913 * following techniques:
1918 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
1919 * the user from interacting with elements while the main
1920 * loop is recursing.
1925 * Avoid main loop recursion in situations where you can't handle
1926 * arbitrary callbacks. Instead, structure your code so that you
1927 * simply return to the main loop and then get called again when
1928 * there is more work to do.
1933 * Return value: The main loop recursion level in the current thread
1938 GMainDispatch *dispatch = get_dispatch ();
1939 return dispatch->depth;
1943 * g_main_current_source:
1945 * Returns the currently firing source for this thread.
1947 * Return value: The currently firing source or %NULL.
1952 g_main_current_source (void)
1954 GMainDispatch *dispatch = get_dispatch ();
1955 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
1959 * g_source_is_destroyed:
1960 * @source: a #GSource
1962 * Returns whether @source has been destroyed.
1964 * This is important when you operate upon your objects
1965 * from within idle handlers, but may have freed the object
1966 * before the dispatch of your idle handler.
1970 * idle_callback (gpointer data)
1972 * SomeWidget *self = data;
1974 * GDK_THREADS_ENTER (<!-- -->);
1975 * /<!-- -->* do stuff with self *<!-- -->/
1976 * self->idle_id = 0;
1977 * GDK_THREADS_LEAVE (<!-- -->);
1983 * some_widget_do_stuff_later (SomeWidget *self)
1985 * self->idle_id = g_idle_add (idle_callback, self);
1989 * some_widget_finalize (GObject *object)
1991 * SomeWidget *self = SOME_WIDGET (object);
1993 * if (self->idle_id)
1994 * g_source_remove (self->idle_id);
1996 * G_OBJECT_CLASS (parent_class)->finalize (object);
2000 * This will fail in a multi-threaded application if the
2001 * widget is destroyed before the idle handler fires due
2002 * to the use after free in the callback. A solution, to
2003 * this particular problem, is to check to if the source
2004 * has already been destroy within the callback.
2008 * idle_callback (gpointer data)
2010 * SomeWidget *self = data;
2012 * GDK_THREADS_ENTER ();
2013 * if (!g_source_is_destroyed (g_main_current_source ()))
2015 * /<!-- -->* do stuff with self *<!-- -->/
2017 * GDK_THREADS_LEAVE ();
2023 * Return value: %TRUE if the source has been destroyed
2028 g_source_is_destroyed (GSource *source)
2030 return SOURCE_DESTROYED (source);
2033 /* Temporarily remove all this source's file descriptors from the
2034 * poll(), so that if data comes available for one of the file descriptors
2035 * we don't continually spin in the poll()
2037 /* HOLDS: source->context's lock */
2039 block_source (GSource *source)
2043 g_return_if_fail (!SOURCE_BLOCKED (source));
2045 tmp_list = source->poll_fds;
2048 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2049 tmp_list = tmp_list->next;
2053 /* HOLDS: source->context's lock */
2055 unblock_source (GSource *source)
2059 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
2060 g_return_if_fail (!SOURCE_DESTROYED (source));
2062 tmp_list = source->poll_fds;
2065 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2066 tmp_list = tmp_list->next;
2070 /* HOLDS: context's lock */
2072 g_main_dispatch (GMainContext *context)
2074 GMainDispatch *current = get_dispatch ();
2077 for (i = 0; i < context->pending_dispatches->len; i++)
2079 GSource *source = context->pending_dispatches->pdata[i];
2081 context->pending_dispatches->pdata[i] = NULL;
2084 source->flags &= ~G_SOURCE_READY;
2086 if (!SOURCE_DESTROYED (source))
2088 gboolean was_in_call;
2089 gpointer user_data = NULL;
2090 GSourceFunc callback = NULL;
2091 GSourceCallbackFuncs *cb_funcs;
2093 gboolean need_destroy;
2095 gboolean (*dispatch) (GSource *,
2098 GSList current_source_link;
2100 dispatch = source->source_funcs->dispatch;
2101 cb_funcs = source->callback_funcs;
2102 cb_data = source->callback_data;
2105 cb_funcs->ref (cb_data);
2107 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2108 block_source (source);
2110 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2111 source->flags |= G_HOOK_FLAG_IN_CALL;
2114 cb_funcs->get (cb_data, source, &callback, &user_data);
2116 UNLOCK_CONTEXT (context);
2119 /* The on-stack allocation of the GSList is unconventional, but
2120 * we know that the lifetime of the link is bounded to this
2121 * function as the link is kept in a thread specific list and
2122 * not manipulated outside of this function and its descendants.
2123 * Avoiding the overhead of a g_slist_alloc() is useful as many
2124 * applications do little more than dispatch events.
2126 * This is a performance hack - do not revert to g_slist_prepend()!
2128 current_source_link.data = source;
2129 current_source_link.next = current->dispatching_sources;
2130 current->dispatching_sources = ¤t_source_link;
2131 need_destroy = ! dispatch (source,
2134 g_assert (current->dispatching_sources == ¤t_source_link);
2135 current->dispatching_sources = current_source_link.next;
2139 cb_funcs->unref (cb_data);
2141 LOCK_CONTEXT (context);
2144 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2146 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2147 !SOURCE_DESTROYED (source))
2148 unblock_source (source);
2150 /* Note: this depends on the fact that we can't switch
2151 * sources from one main context to another
2153 if (need_destroy && !SOURCE_DESTROYED (source))
2155 g_assert (source->context == context);
2156 g_source_destroy_internal (source, context, TRUE);
2160 SOURCE_UNREF (source, context);
2163 g_ptr_array_set_size (context->pending_dispatches, 0);
2166 /* Holds context's lock */
2167 static inline GSource *
2168 next_valid_source (GMainContext *context,
2171 GSource *new_source = source ? source->next : context->source_list;
2175 if (!SOURCE_DESTROYED (new_source))
2177 new_source->ref_count++;
2181 new_source = new_source->next;
2185 SOURCE_UNREF (source, context);
2191 * g_main_context_acquire:
2192 * @context: a #GMainContext
2194 * Tries to become the owner of the specified context.
2195 * If some other thread is the owner of the context,
2196 * returns %FALSE immediately. Ownership is properly
2197 * recursive: the owner can require ownership again
2198 * and will release ownership when g_main_context_release()
2199 * is called as many times as g_main_context_acquire().
2201 * You must be the owner of a context before you
2202 * can call g_main_context_prepare(), g_main_context_query(),
2203 * g_main_context_check(), g_main_context_dispatch().
2205 * Return value: %TRUE if the operation succeeded, and
2206 * this thread is now the owner of @context.
2209 g_main_context_acquire (GMainContext *context)
2211 #ifdef G_THREADS_ENABLED
2212 gboolean result = FALSE;
2213 GThread *self = G_THREAD_SELF;
2215 if (context == NULL)
2216 context = g_main_context_default ();
2218 LOCK_CONTEXT (context);
2220 if (!context->owner)
2222 context->owner = self;
2223 g_assert (context->owner_count == 0);
2226 if (context->owner == self)
2228 context->owner_count++;
2232 UNLOCK_CONTEXT (context);
2235 #else /* !G_THREADS_ENABLED */
2237 #endif /* G_THREADS_ENABLED */
2241 * g_main_context_release:
2242 * @context: a #GMainContext
2244 * Releases ownership of a context previously acquired by this thread
2245 * with g_main_context_acquire(). If the context was acquired multiple
2246 * times, the ownership will be released only when g_main_context_release()
2247 * is called as many times as it was acquired.
2250 g_main_context_release (GMainContext *context)
2252 #ifdef G_THREADS_ENABLED
2253 if (context == NULL)
2254 context = g_main_context_default ();
2256 LOCK_CONTEXT (context);
2258 context->owner_count--;
2259 if (context->owner_count == 0)
2261 context->owner = NULL;
2263 if (context->waiters)
2265 GMainWaiter *waiter = context->waiters->data;
2266 gboolean loop_internal_waiter =
2267 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
2268 context->waiters = g_slist_delete_link (context->waiters,
2270 if (!loop_internal_waiter)
2271 g_mutex_lock (waiter->mutex);
2273 g_cond_signal (waiter->cond);
2275 if (!loop_internal_waiter)
2276 g_mutex_unlock (waiter->mutex);
2280 UNLOCK_CONTEXT (context);
2281 #endif /* G_THREADS_ENABLED */
2285 * g_main_context_wait:
2286 * @context: a #GMainContext
2287 * @cond: a condition variable
2288 * @mutex: a mutex, currently held
2290 * Tries to become the owner of the specified context,
2291 * as with g_main_context_acquire(). But if another thread
2292 * is the owner, atomically drop @mutex and wait on @cond until
2293 * that owner releases ownership or until @cond is signaled, then
2294 * try again (once) to become the owner.
2296 * Return value: %TRUE if the operation succeeded, and
2297 * this thread is now the owner of @context.
2300 g_main_context_wait (GMainContext *context,
2304 #ifdef G_THREADS_ENABLED
2305 gboolean result = FALSE;
2306 GThread *self = G_THREAD_SELF;
2307 gboolean loop_internal_waiter;
2309 if (context == NULL)
2310 context = g_main_context_default ();
2312 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2314 if (!loop_internal_waiter)
2315 LOCK_CONTEXT (context);
2317 if (context->owner && context->owner != self)
2322 waiter.mutex = mutex;
2324 context->waiters = g_slist_append (context->waiters, &waiter);
2326 if (!loop_internal_waiter)
2327 UNLOCK_CONTEXT (context);
2328 g_cond_wait (cond, mutex);
2329 if (!loop_internal_waiter)
2330 LOCK_CONTEXT (context);
2332 context->waiters = g_slist_remove (context->waiters, &waiter);
2335 if (!context->owner)
2337 context->owner = self;
2338 g_assert (context->owner_count == 0);
2341 if (context->owner == self)
2343 context->owner_count++;
2347 if (!loop_internal_waiter)
2348 UNLOCK_CONTEXT (context);
2351 #else /* !G_THREADS_ENABLED */
2353 #endif /* G_THREADS_ENABLED */
2357 * g_main_context_prepare:
2358 * @context: a #GMainContext
2359 * @priority: location to store priority of highest priority
2360 * source already ready.
2362 * Prepares to poll sources within a main loop. The resulting information
2363 * for polling is determined by calling g_main_context_query ().
2365 * Return value: %TRUE if some source is ready to be dispatched
2369 g_main_context_prepare (GMainContext *context,
2374 gint current_priority = G_MAXINT;
2377 if (context == NULL)
2378 context = g_main_context_default ();
2380 LOCK_CONTEXT (context);
2382 context->time_is_current = FALSE;
2384 if (context->in_check_or_prepare)
2386 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2387 "prepare() member.");
2388 UNLOCK_CONTEXT (context);
2392 #ifdef G_THREADS_ENABLED
2393 if (context->poll_waiting)
2395 g_warning("g_main_context_prepare(): main loop already active in another thread");
2396 UNLOCK_CONTEXT (context);
2400 context->poll_waiting = TRUE;
2401 #endif /* G_THREADS_ENABLED */
2404 /* If recursing, finish up current dispatch, before starting over */
2405 if (context->pending_dispatches)
2408 g_main_dispatch (context, ¤t_time);
2410 UNLOCK_CONTEXT (context);
2415 /* If recursing, clear list of pending dispatches */
2417 for (i = 0; i < context->pending_dispatches->len; i++)
2419 if (context->pending_dispatches->pdata[i])
2420 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2422 g_ptr_array_set_size (context->pending_dispatches, 0);
2424 /* Prepare all sources */
2426 context->timeout = -1;
2428 source = next_valid_source (context, NULL);
2431 gint source_timeout = -1;
2433 if ((n_ready > 0) && (source->priority > current_priority))
2435 SOURCE_UNREF (source, context);
2438 if (SOURCE_BLOCKED (source))
2441 if (!(source->flags & G_SOURCE_READY))
2444 gboolean (*prepare) (GSource *source,
2447 prepare = source->source_funcs->prepare;
2448 context->in_check_or_prepare++;
2449 UNLOCK_CONTEXT (context);
2451 result = (*prepare) (source, &source_timeout);
2453 LOCK_CONTEXT (context);
2454 context->in_check_or_prepare--;
2457 source->flags |= G_SOURCE_READY;
2460 if (source->flags & G_SOURCE_READY)
2463 current_priority = source->priority;
2464 context->timeout = 0;
2467 if (source_timeout >= 0)
2469 if (context->timeout < 0)
2470 context->timeout = source_timeout;
2472 context->timeout = MIN (context->timeout, source_timeout);
2476 source = next_valid_source (context, source);
2479 UNLOCK_CONTEXT (context);
2482 *priority = current_priority;
2484 return (n_ready > 0);
2488 * g_main_context_query:
2489 * @context: a #GMainContext
2490 * @max_priority: maximum priority source to check
2491 * @timeout_: location to store timeout to be used in polling
2492 * @fds: location to store #GPollFD records that need to be polled.
2493 * @n_fds: length of @fds.
2495 * Determines information necessary to poll this main loop.
2497 * Return value: the number of records actually stored in @fds,
2498 * or, if more than @n_fds records need to be stored, the number
2499 * of records that need to be stored.
2502 g_main_context_query (GMainContext *context,
2511 LOCK_CONTEXT (context);
2513 pollrec = context->poll_records;
2515 while (pollrec && max_priority >= pollrec->priority)
2517 /* We need to include entries with fd->events == 0 in the array because
2518 * otherwise if the application changes fd->events behind our back and
2519 * makes it non-zero, we'll be out of sync when we check the fds[] array.
2520 * (Changing fd->events after adding an FD wasn't an anticipated use of
2521 * this API, but it occurs in practice.) */
2524 fds[n_poll].fd = pollrec->fd->fd;
2525 /* In direct contradiction to the Unix98 spec, IRIX runs into
2526 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2527 * flags in the events field of the pollfd while it should
2528 * just ignoring them. So we mask them out here.
2530 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2531 fds[n_poll].revents = 0;
2534 pollrec = pollrec->next;
2538 #ifdef G_THREADS_ENABLED
2539 context->poll_changed = FALSE;
2544 *timeout = context->timeout;
2546 context->time_is_current = FALSE;
2549 UNLOCK_CONTEXT (context);
2555 * g_main_context_check:
2556 * @context: a #GMainContext
2557 * @max_priority: the maximum numerical priority of sources to check
2558 * @fds: array of #GPollFD's that was passed to the last call to
2559 * g_main_context_query()
2560 * @n_fds: return value of g_main_context_query()
2562 * Passes the results of polling back to the main loop.
2564 * Return value: %TRUE if some sources are ready to be dispatched.
2567 g_main_context_check (GMainContext *context,
2577 LOCK_CONTEXT (context);
2579 if (context->in_check_or_prepare)
2581 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2582 "prepare() member.");
2583 UNLOCK_CONTEXT (context);
2587 #ifdef G_THREADS_ENABLED
2588 if (!context->poll_waiting)
2592 read (context->wake_up_pipe[0], &a, 1);
2596 context->poll_waiting = FALSE;
2598 /* If the set of poll file descriptors changed, bail out
2599 * and let the main loop rerun
2601 if (context->poll_changed)
2603 UNLOCK_CONTEXT (context);
2606 #endif /* G_THREADS_ENABLED */
2608 pollrec = context->poll_records;
2612 if (pollrec->fd->events)
2613 pollrec->fd->revents = fds[i].revents;
2615 pollrec = pollrec->next;
2619 source = next_valid_source (context, NULL);
2622 if ((n_ready > 0) && (source->priority > max_priority))
2624 SOURCE_UNREF (source, context);
2627 if (SOURCE_BLOCKED (source))
2630 if (!(source->flags & G_SOURCE_READY))
2633 gboolean (*check) (GSource *source);
2635 check = source->source_funcs->check;
2637 context->in_check_or_prepare++;
2638 UNLOCK_CONTEXT (context);
2640 result = (*check) (source);
2642 LOCK_CONTEXT (context);
2643 context->in_check_or_prepare--;
2646 source->flags |= G_SOURCE_READY;
2649 if (source->flags & G_SOURCE_READY)
2651 source->ref_count++;
2652 g_ptr_array_add (context->pending_dispatches, source);
2656 /* never dispatch sources with less priority than the first
2657 * one we choose to dispatch
2659 max_priority = source->priority;
2663 source = next_valid_source (context, source);
2666 UNLOCK_CONTEXT (context);
2672 * g_main_context_dispatch:
2673 * @context: a #GMainContext
2675 * Dispatches all pending sources.
2678 g_main_context_dispatch (GMainContext *context)
2680 LOCK_CONTEXT (context);
2682 if (context->pending_dispatches->len > 0)
2684 g_main_dispatch (context);
2687 UNLOCK_CONTEXT (context);
2690 /* HOLDS context lock */
2692 g_main_context_iterate (GMainContext *context,
2699 gboolean some_ready;
2700 gint nfds, allocated_nfds;
2701 GPollFD *fds = NULL;
2703 UNLOCK_CONTEXT (context);
2705 #ifdef G_THREADS_ENABLED
2706 if (!g_main_context_acquire (context))
2708 gboolean got_ownership;
2710 LOCK_CONTEXT (context);
2712 g_return_val_if_fail (g_thread_supported (), FALSE);
2718 context->cond = g_cond_new ();
2720 got_ownership = g_main_context_wait (context,
2722 g_static_mutex_get_mutex (&context->mutex));
2728 LOCK_CONTEXT (context);
2729 #endif /* G_THREADS_ENABLED */
2731 if (!context->cached_poll_array)
2733 context->cached_poll_array_size = context->n_poll_records;
2734 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2737 allocated_nfds = context->cached_poll_array_size;
2738 fds = context->cached_poll_array;
2740 UNLOCK_CONTEXT (context);
2742 g_main_context_prepare (context, &max_priority);
2744 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
2745 allocated_nfds)) > allocated_nfds)
2747 LOCK_CONTEXT (context);
2749 context->cached_poll_array_size = allocated_nfds = nfds;
2750 context->cached_poll_array = fds = g_new (GPollFD, nfds);
2751 UNLOCK_CONTEXT (context);
2757 g_main_context_poll (context, timeout, max_priority, fds, nfds);
2759 some_ready = g_main_context_check (context, max_priority, fds, nfds);
2762 g_main_context_dispatch (context);
2764 #ifdef G_THREADS_ENABLED
2765 g_main_context_release (context);
2766 #endif /* G_THREADS_ENABLED */
2768 LOCK_CONTEXT (context);
2774 * g_main_context_pending:
2775 * @context: a #GMainContext (if %NULL, the default context will be used)
2777 * Checks if any sources have pending events for the given context.
2779 * Return value: %TRUE if events are pending.
2782 g_main_context_pending (GMainContext *context)
2787 context = g_main_context_default();
2789 LOCK_CONTEXT (context);
2790 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
2791 UNLOCK_CONTEXT (context);
2797 * g_main_context_iteration:
2798 * @context: a #GMainContext (if %NULL, the default context will be used)
2799 * @may_block: whether the call may block.
2801 * Runs a single iteration for the given main loop. This involves
2802 * checking to see if any event sources are ready to be processed,
2803 * then if no events sources are ready and @may_block is %TRUE, waiting
2804 * for a source to become ready, then dispatching the highest priority
2805 * events sources that are ready. Otherwise, if @may_block is %FALSE
2806 * sources are not waited to become ready, only those highest priority
2807 * events sources will be dispatched (if any), that are ready at this
2808 * given moment without further waiting.
2810 * Note that even when @may_block is %TRUE, it is still possible for
2811 * g_main_context_iteration() to return %FALSE, since the the wait may
2812 * be interrupted for other reasons than an event source becoming ready.
2814 * Return value: %TRUE if events were dispatched.
2817 g_main_context_iteration (GMainContext *context, gboolean may_block)
2822 context = g_main_context_default();
2824 LOCK_CONTEXT (context);
2825 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
2826 UNLOCK_CONTEXT (context);
2833 * @context: a #GMainContext (if %NULL, the default context will be used).
2834 * @is_running: set to %TRUE to indicate that the loop is running. This
2835 * is not very important since calling g_main_loop_run() will set this to
2838 * Creates a new #GMainLoop structure.
2840 * Return value: a new #GMainLoop.
2843 g_main_loop_new (GMainContext *context,
2844 gboolean is_running)
2849 context = g_main_context_default();
2851 g_main_context_ref (context);
2853 loop = g_new0 (GMainLoop, 1);
2854 loop->context = context;
2855 loop->is_running = is_running != FALSE;
2856 loop->ref_count = 1;
2863 * @loop: a #GMainLoop
2865 * Increases the reference count on a #GMainLoop object by one.
2867 * Return value: @loop
2870 g_main_loop_ref (GMainLoop *loop)
2872 g_return_val_if_fail (loop != NULL, NULL);
2873 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2875 g_atomic_int_inc (&loop->ref_count);
2881 * g_main_loop_unref:
2882 * @loop: a #GMainLoop
2884 * Decreases the reference count on a #GMainLoop object by one. If
2885 * the result is zero, free the loop and free all associated memory.
2888 g_main_loop_unref (GMainLoop *loop)
2890 g_return_if_fail (loop != NULL);
2891 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2893 if (!g_atomic_int_dec_and_test (&loop->ref_count))
2896 g_main_context_unref (loop->context);
2902 * @loop: a #GMainLoop
2904 * Runs a main loop until g_main_loop_quit() is called on the loop.
2905 * If this is called for the thread of the loop's #GMainContext,
2906 * it will process events from the loop, otherwise it will
2910 g_main_loop_run (GMainLoop *loop)
2912 GThread *self = G_THREAD_SELF;
2914 g_return_if_fail (loop != NULL);
2915 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2917 #ifdef G_THREADS_ENABLED
2918 if (!g_main_context_acquire (loop->context))
2920 gboolean got_ownership = FALSE;
2922 /* Another thread owns this context */
2923 if (!g_thread_supported ())
2925 g_warning ("g_main_loop_run() was called from second thread but "
2926 "g_thread_init() was never called.");
2930 LOCK_CONTEXT (loop->context);
2932 g_atomic_int_inc (&loop->ref_count);
2934 if (!loop->is_running)
2935 loop->is_running = TRUE;
2937 if (!loop->context->cond)
2938 loop->context->cond = g_cond_new ();
2940 while (loop->is_running && !got_ownership)
2941 got_ownership = g_main_context_wait (loop->context,
2942 loop->context->cond,
2943 g_static_mutex_get_mutex (&loop->context->mutex));
2945 if (!loop->is_running)
2947 UNLOCK_CONTEXT (loop->context);
2949 g_main_context_release (loop->context);
2950 g_main_loop_unref (loop);
2954 g_assert (got_ownership);
2957 LOCK_CONTEXT (loop->context);
2958 #endif /* G_THREADS_ENABLED */
2960 if (loop->context->in_check_or_prepare)
2962 g_warning ("g_main_loop_run(): called recursively from within a source's "
2963 "check() or prepare() member, iteration not possible.");
2967 g_atomic_int_inc (&loop->ref_count);
2968 loop->is_running = TRUE;
2969 while (loop->is_running)
2970 g_main_context_iterate (loop->context, TRUE, TRUE, self);
2972 UNLOCK_CONTEXT (loop->context);
2974 #ifdef G_THREADS_ENABLED
2975 g_main_context_release (loop->context);
2976 #endif /* G_THREADS_ENABLED */
2978 g_main_loop_unref (loop);
2983 * @loop: a #GMainLoop
2985 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
2986 * for the loop will return.
2988 * Note that sources that have already been dispatched when
2989 * g_main_loop_quit() is called will still be executed.
2992 g_main_loop_quit (GMainLoop *loop)
2994 g_return_if_fail (loop != NULL);
2995 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2997 LOCK_CONTEXT (loop->context);
2998 loop->is_running = FALSE;
2999 g_main_context_wakeup_unlocked (loop->context);
3001 #ifdef G_THREADS_ENABLED
3002 if (loop->context->cond)
3003 g_cond_broadcast (loop->context->cond);
3004 #endif /* G_THREADS_ENABLED */
3006 UNLOCK_CONTEXT (loop->context);
3010 * g_main_loop_is_running:
3011 * @loop: a #GMainLoop.
3013 * Checks to see if the main loop is currently being run via g_main_loop_run().
3015 * Return value: %TRUE if the mainloop is currently being run.
3018 g_main_loop_is_running (GMainLoop *loop)
3020 g_return_val_if_fail (loop != NULL, FALSE);
3021 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3023 return loop->is_running;
3027 * g_main_loop_get_context:
3028 * @loop: a #GMainLoop.
3030 * Returns the #GMainContext of @loop.
3032 * Return value: the #GMainContext of @loop
3035 g_main_loop_get_context (GMainLoop *loop)
3037 g_return_val_if_fail (loop != NULL, NULL);
3038 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3040 return loop->context;
3043 /* HOLDS: context's lock */
3045 g_main_context_poll (GMainContext *context,
3051 #ifdef G_MAIN_POLL_DEBUG
3057 GPollFunc poll_func;
3059 if (n_fds || timeout != 0)
3061 #ifdef G_MAIN_POLL_DEBUG
3062 if (_g_main_poll_debug)
3064 g_print ("polling context=%p n=%d timeout=%d\n",
3065 context, n_fds, timeout);
3066 poll_timer = g_timer_new ();
3070 LOCK_CONTEXT (context);
3072 poll_func = context->poll_func;
3074 UNLOCK_CONTEXT (context);
3075 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3078 g_warning ("poll(2) failed due to: %s.",
3079 g_strerror (errno));
3081 /* If g_poll () returns -1, it has already called g_warning() */
3085 #ifdef G_MAIN_POLL_DEBUG
3086 if (_g_main_poll_debug)
3088 LOCK_CONTEXT (context);
3090 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3093 g_timer_elapsed (poll_timer, NULL));
3094 g_timer_destroy (poll_timer);
3095 pollrec = context->poll_records;
3097 while (pollrec != NULL)
3102 if (fds[i].fd == pollrec->fd->fd &&
3103 pollrec->fd->events &&
3106 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3107 if (fds[i].revents & G_IO_IN)
3109 if (fds[i].revents & G_IO_OUT)
3111 if (fds[i].revents & G_IO_PRI)
3113 if (fds[i].revents & G_IO_ERR)
3115 if (fds[i].revents & G_IO_HUP)
3117 if (fds[i].revents & G_IO_NVAL)
3123 pollrec = pollrec->next;
3127 UNLOCK_CONTEXT (context);
3130 } /* if (n_fds || timeout != 0) */
3134 * g_main_context_add_poll:
3135 * @context: a #GMainContext (or %NULL for the default context)
3136 * @fd: a #GPollFD structure holding information about a file
3137 * descriptor to watch.
3138 * @priority: the priority for this file descriptor which should be
3139 * the same as the priority used for g_source_attach() to ensure that the
3140 * file descriptor is polled whenever the results may be needed.
3142 * Adds a file descriptor to the set of file descriptors polled for
3143 * this context. This will very seldomly be used directly. Instead
3144 * a typical event source will use g_source_add_poll() instead.
3147 g_main_context_add_poll (GMainContext *context,
3152 context = g_main_context_default ();
3154 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3155 g_return_if_fail (fd);
3157 LOCK_CONTEXT (context);
3158 g_main_context_add_poll_unlocked (context, priority, fd);
3159 UNLOCK_CONTEXT (context);
3162 /* HOLDS: main_loop_lock */
3164 g_main_context_add_poll_unlocked (GMainContext *context,
3168 GPollRec *lastrec, *pollrec;
3169 GPollRec *newrec = g_slice_new (GPollRec);
3171 /* This file descriptor may be checked before we ever poll */
3174 newrec->priority = priority;
3177 pollrec = context->poll_records;
3178 while (pollrec && priority >= pollrec->priority)
3181 pollrec = pollrec->next;
3185 lastrec->next = newrec;
3187 context->poll_records = newrec;
3189 newrec->next = pollrec;
3191 context->n_poll_records++;
3193 #ifdef G_THREADS_ENABLED
3194 context->poll_changed = TRUE;
3196 /* Now wake up the main loop if it is waiting in the poll() */
3197 g_main_context_wakeup_unlocked (context);
3202 * g_main_context_remove_poll:
3203 * @context:a #GMainContext
3204 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3206 * Removes file descriptor from the set of file descriptors to be
3207 * polled for a particular context.
3210 g_main_context_remove_poll (GMainContext *context,
3214 context = g_main_context_default ();
3216 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3217 g_return_if_fail (fd);
3219 LOCK_CONTEXT (context);
3220 g_main_context_remove_poll_unlocked (context, fd);
3221 UNLOCK_CONTEXT (context);
3225 g_main_context_remove_poll_unlocked (GMainContext *context,
3228 GPollRec *pollrec, *lastrec;
3231 pollrec = context->poll_records;
3235 if (pollrec->fd == fd)
3237 if (lastrec != NULL)
3238 lastrec->next = pollrec->next;
3240 context->poll_records = pollrec->next;
3242 g_slice_free (GPollRec, pollrec);
3244 context->n_poll_records--;
3248 pollrec = pollrec->next;
3251 #ifdef G_THREADS_ENABLED
3252 context->poll_changed = TRUE;
3254 /* Now wake up the main loop if it is waiting in the poll() */
3255 g_main_context_wakeup_unlocked (context);
3260 * g_source_get_current_time:
3261 * @source: a #GSource
3262 * @timeval: #GTimeVal structure in which to store current time.
3264 * Gets the "current time" to be used when checking
3265 * this source. The advantage of calling this function over
3266 * calling g_get_current_time() directly is that when
3267 * checking multiple sources, GLib can cache a single value
3268 * instead of having to repeatedly get the system time.
3271 g_source_get_current_time (GSource *source,
3274 GMainContext *context;
3276 g_return_if_fail (source->context != NULL);
3278 context = source->context;
3280 LOCK_CONTEXT (context);
3282 if (!context->time_is_current)
3284 g_get_current_time (&context->current_time);
3285 context->time_is_current = TRUE;
3288 *timeval = context->current_time;
3290 UNLOCK_CONTEXT (context);
3294 * g_main_context_set_poll_func:
3295 * @context: a #GMainContext
3296 * @func: the function to call to poll all file descriptors
3298 * Sets the function to use to handle polling of file descriptors. It
3299 * will be used instead of the poll() system call
3300 * (or GLib's replacement function, which is used where
3301 * poll() isn't available).
3303 * This function could possibly be used to integrate the GLib event
3304 * loop with an external event loop.
3307 g_main_context_set_poll_func (GMainContext *context,
3311 context = g_main_context_default ();
3313 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3315 LOCK_CONTEXT (context);
3318 context->poll_func = func;
3320 context->poll_func = g_poll;
3322 UNLOCK_CONTEXT (context);
3326 * g_main_context_get_poll_func:
3327 * @context: a #GMainContext
3329 * Gets the poll function set by g_main_context_set_poll_func().
3331 * Return value: the poll function
3334 g_main_context_get_poll_func (GMainContext *context)
3339 context = g_main_context_default ();
3341 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3343 LOCK_CONTEXT (context);
3344 result = context->poll_func;
3345 UNLOCK_CONTEXT (context);
3350 /* HOLDS: context's lock */
3351 /* Wake the main loop up from a poll() */
3353 g_main_context_wakeup_unlocked (GMainContext *context)
3355 #ifdef G_THREADS_ENABLED
3356 if (g_thread_supported() && context->poll_waiting)
3358 context->poll_waiting = FALSE;
3360 write (context->wake_up_pipe[1], "A", 1);
3362 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
3369 * g_main_context_wakeup:
3370 * @context: a #GMainContext
3372 * If @context is currently waiting in a poll(), interrupt
3373 * the poll(), and continue the iteration process.
3376 g_main_context_wakeup (GMainContext *context)
3379 context = g_main_context_default ();
3381 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3383 LOCK_CONTEXT (context);
3384 g_main_context_wakeup_unlocked (context);
3385 UNLOCK_CONTEXT (context);
3389 * g_main_context_is_owner:
3390 * @context: a #GMainContext
3392 * Determines whether this thread holds the (recursive)
3393 * ownership of this #GMaincontext. This is useful to
3394 * know before waiting on another thread that may be
3395 * blocking to get ownership of @context.
3397 * Returns: %TRUE if current thread is owner of @context.
3402 g_main_context_is_owner (GMainContext *context)
3407 context = g_main_context_default ();
3409 #ifdef G_THREADS_ENABLED
3410 LOCK_CONTEXT (context);
3411 is_owner = context->owner == G_THREAD_SELF;
3412 UNLOCK_CONTEXT (context);
3423 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3424 GTimeVal *current_time)
3426 guint seconds = timeout_source->interval / 1000;
3427 guint msecs = timeout_source->interval - seconds * 1000;
3429 timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
3430 timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
3431 if (timeout_source->expiration.tv_usec >= 1000000)
3433 timeout_source->expiration.tv_usec -= 1000000;
3434 timeout_source->expiration.tv_sec++;
3436 if (timer_perturb==-1)
3439 * we want a per machine/session unique 'random' value; try the dbus
3440 * address first, that has a UUID in it. If there is no dbus, use the
3441 * hostname for hashing.
3443 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3444 if (!session_bus_address)
3445 session_bus_address = g_getenv ("HOSTNAME");
3446 if (session_bus_address)
3447 timer_perturb = ABS ((gint) g_str_hash (session_bus_address));
3451 if (timeout_source->granularity)
3454 gint gran; /* in usecs */
3457 gran = timeout_source->granularity * 1000;
3458 perturb = timer_perturb % gran;
3460 * We want to give each machine a per machine pertubation;
3461 * shift time back first, and forward later after the rounding
3464 timeout_source->expiration.tv_usec -= perturb;
3465 if (timeout_source->expiration.tv_usec < 0)
3467 timeout_source->expiration.tv_usec += 1000000;
3468 timeout_source->expiration.tv_sec--;
3471 remainder = timeout_source->expiration.tv_usec % gran;
3472 if (remainder >= gran/4) /* round up */
3473 timeout_source->expiration.tv_usec += gran;
3474 timeout_source->expiration.tv_usec -= remainder;
3476 timeout_source->expiration.tv_usec += perturb;
3478 /* the rounding may have overflown tv_usec */
3479 while (timeout_source->expiration.tv_usec > 1000000)
3481 timeout_source->expiration.tv_usec -= 1000000;
3482 timeout_source->expiration.tv_sec++;
3488 g_timeout_prepare (GSource *source,
3493 GTimeVal current_time;
3495 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3497 g_source_get_current_time (source, ¤t_time);
3499 sec = timeout_source->expiration.tv_sec - current_time.tv_sec;
3500 msec = (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000;
3502 /* We do the following in a rather convoluted fashion to deal with
3503 * the fact that we don't have an integral type big enough to hold
3504 * the difference of two timevals in millseconds.
3506 if (sec < 0 || (sec == 0 && msec < 0))
3510 glong interval_sec = timeout_source->interval / 1000;
3511 glong interval_msec = timeout_source->interval % 1000;
3519 if (sec > interval_sec ||
3520 (sec == interval_sec && msec > interval_msec))
3522 /* The system time has been set backwards, so we
3523 * reset the expiration time to now + timeout_source->interval;
3524 * this at least avoids hanging for long periods of time.
3526 g_timeout_set_expiration (timeout_source, ¤t_time);
3527 msec = MIN (G_MAXINT, timeout_source->interval);
3531 msec = MIN (G_MAXINT, (guint)msec + 1000 * (guint)sec);
3535 *timeout = (gint)msec;
3541 g_timeout_check (GSource *source)
3543 GTimeVal current_time;
3544 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3546 g_source_get_current_time (source, ¤t_time);
3548 return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
3549 ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
3550 (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
3554 g_timeout_dispatch (GSource *source,
3555 GSourceFunc callback,
3558 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3562 g_warning ("Timeout source dispatched without callback\n"
3563 "You must call g_source_set_callback().");
3567 if (callback (user_data))
3569 GTimeVal current_time;
3571 g_source_get_current_time (source, ¤t_time);
3572 g_timeout_set_expiration (timeout_source, ¤t_time);
3581 * g_timeout_source_new:
3582 * @interval: the timeout interval in milliseconds.
3584 * Creates a new timeout source.
3586 * The source will not initially be associated with any #GMainContext
3587 * and must be added to one with g_source_attach() before it will be
3590 * Return value: the newly-created timeout source
3593 g_timeout_source_new (guint interval)
3595 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3596 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3597 GTimeVal current_time;
3599 timeout_source->interval = interval;
3601 g_get_current_time (¤t_time);
3602 g_timeout_set_expiration (timeout_source, ¤t_time);
3608 * g_timeout_source_new_seconds:
3609 * @interval: the timeout interval in seconds
3611 * Creates a new timeout source.
3613 * The source will not initially be associated with any #GMainContext
3614 * and must be added to one with g_source_attach() before it will be
3617 * The scheduling granularity/accuracy of this timeout source will be
3620 * Return value: the newly-created timeout source
3625 g_timeout_source_new_seconds (guint interval)
3627 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3628 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3629 GTimeVal current_time;
3631 timeout_source->interval = 1000*interval;
3632 timeout_source->granularity = 1000;
3634 g_get_current_time (¤t_time);
3635 g_timeout_set_expiration (timeout_source, ¤t_time);
3642 * g_timeout_add_full:
3643 * @priority: the priority of the timeout source. Typically this will be in
3644 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3645 * @interval: the time between calls to the function, in milliseconds
3646 * (1/1000ths of a second)
3647 * @function: function to call
3648 * @data: data to pass to @function
3649 * @notify: function to call when the timeout is removed, or %NULL
3651 * Sets a function to be called at regular intervals, with the given
3652 * priority. The function is called repeatedly until it returns
3653 * %FALSE, at which point the timeout is automatically destroyed and
3654 * the function will not be called again. The @notify function is
3655 * called when the timeout is destroyed. The first call to the
3656 * function will be at the end of the first @interval.
3658 * Note that timeout functions may be delayed, due to the processing of other
3659 * event sources. Thus they should not be relied on for precise timing.
3660 * After each call to the timeout function, the time of the next
3661 * timeout is recalculated based on the current time and the given interval
3662 * (it does not try to 'catch up' time lost in delays).
3664 * This internally creates a main loop source using g_timeout_source_new()
3665 * and attaches it to the main loop context using g_source_attach(). You can
3666 * do these steps manually if you need greater control.
3668 * Return value: the ID (greater than 0) of the event source.
3671 g_timeout_add_full (gint priority,
3673 GSourceFunc function,
3675 GDestroyNotify notify)
3680 g_return_val_if_fail (function != NULL, 0);
3682 source = g_timeout_source_new (interval);
3684 if (priority != G_PRIORITY_DEFAULT)
3685 g_source_set_priority (source, priority);
3687 g_source_set_callback (source, function, data, notify);
3688 id = g_source_attach (source, NULL);
3689 g_source_unref (source);
3696 * @interval: the time between calls to the function, in milliseconds
3697 * (1/1000ths of a second)
3698 * @function: function to call
3699 * @data: data to pass to @function
3701 * Sets a function to be called at regular intervals, with the default
3702 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
3703 * until it returns %FALSE, at which point the timeout is automatically
3704 * destroyed and the function will not be called again. The first call
3705 * to the function will be at the end of the first @interval.
3707 * Note that timeout functions may be delayed, due to the processing of other
3708 * event sources. Thus they should not be relied on for precise timing.
3709 * After each call to the timeout function, the time of the next
3710 * timeout is recalculated based on the current time and the given interval
3711 * (it does not try to 'catch up' time lost in delays).
3713 * If you want to have a timer in the "seconds" range and do not care
3714 * about the exact time of the first call of the timer, use the
3715 * g_timeout_add_seconds() function; this function allows for more
3716 * optimizations and more efficient system power usage.
3718 * This internally creates a main loop source using g_timeout_source_new()
3719 * and attaches it to the main loop context using g_source_attach(). You can
3720 * do these steps manually if you need greater control.
3722 * Return value: the ID (greater than 0) of the event source.
3725 g_timeout_add (guint32 interval,
3726 GSourceFunc function,
3729 return g_timeout_add_full (G_PRIORITY_DEFAULT,
3730 interval, function, data, NULL);
3734 * g_timeout_add_seconds_full:
3735 * @priority: the priority of the timeout source. Typically this will be in
3736 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3737 * @interval: the time between calls to the function, in seconds
3738 * @function: function to call
3739 * @data: data to pass to @function
3740 * @notify: function to call when the timeout is removed, or %NULL
3742 * Sets a function to be called at regular intervals, with @priority.
3743 * The function is called repeatedly until it returns %FALSE, at which
3744 * point the timeout is automatically destroyed and the function will
3745 * not be called again.
3747 * Unlike g_timeout_add(), this function operates at whole second granularity.
3748 * The initial starting point of the timer is determined by the implementation
3749 * and the implementation is expected to group multiple timers together so that
3750 * they fire all at the same time.
3751 * To allow this grouping, the @interval to the first timer is rounded
3752 * and can deviate up to one second from the specified interval.
3753 * Subsequent timer iterations will generally run at the specified interval.
3755 * Note that timeout functions may be delayed, due to the processing of other
3756 * event sources. Thus they should not be relied on for precise timing.
3757 * After each call to the timeout function, the time of the next
3758 * timeout is recalculated based on the current time and the given @interval
3760 * If you want timing more precise than whole seconds, use g_timeout_add()
3763 * The grouping of timers to fire at the same time results in a more power
3764 * and CPU efficient behavior so if your timer is in multiples of seconds
3765 * and you don't require the first timer exactly one second from now, the
3766 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
3768 * This internally creates a main loop source using
3769 * g_timeout_source_new_seconds() and attaches it to the main loop context
3770 * using g_source_attach(). You can do these steps manually if you need
3773 * Return value: the ID (greater than 0) of the event source.
3778 g_timeout_add_seconds_full (gint priority,
3780 GSourceFunc function,
3782 GDestroyNotify notify)
3787 g_return_val_if_fail (function != NULL, 0);
3789 source = g_timeout_source_new_seconds (interval);
3791 if (priority != G_PRIORITY_DEFAULT)
3792 g_source_set_priority (source, priority);
3794 g_source_set_callback (source, function, data, notify);
3795 id = g_source_attach (source, NULL);
3796 g_source_unref (source);
3802 * g_timeout_add_seconds:
3803 * @interval: the time between calls to the function, in seconds
3804 * @function: function to call
3805 * @data: data to pass to @function
3807 * Sets a function to be called at regular intervals with the default
3808 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
3809 * it returns %FALSE, at which point the timeout is automatically destroyed
3810 * and the function will not be called again.
3812 * This internally creates a main loop source using
3813 * g_timeout_source_new_seconds() and attaches it to the main loop context
3814 * using g_source_attach(). You can do these steps manually if you need
3815 * greater control. Also see g_timout_add_seconds_full().
3817 * Return value: the ID (greater than 0) of the event source.
3822 g_timeout_add_seconds (guint interval,
3823 GSourceFunc function,
3826 g_return_val_if_fail (function != NULL, 0);
3828 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
3831 /* Child watch functions */
3836 g_child_watch_prepare (GSource *source,
3845 g_child_watch_check (GSource *source)
3847 GChildWatchSource *child_watch_source;
3848 gboolean child_exited;
3850 child_watch_source = (GChildWatchSource *) source;
3852 child_exited = child_watch_source->poll.revents & G_IO_IN;
3859 * Note: We do _not_ check for the special value of STILL_ACTIVE
3860 * since we know that the process has exited and doing so runs into
3861 * problems if the child process "happens to return STILL_ACTIVE(259)"
3862 * as Microsoft's Platform SDK puts it.
3864 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
3866 gchar *emsg = g_win32_error_message (GetLastError ());
3867 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
3870 child_watch_source->child_status = -1;
3873 child_watch_source->child_status = child_status;
3876 return child_exited;
3879 #else /* G_OS_WIN32 */
3882 check_for_child_exited (GSource *source)
3884 GChildWatchSource *child_watch_source;
3887 /* protect against another SIGCHLD in the middle of this call */
3888 count = child_watch_count;
3890 child_watch_source = (GChildWatchSource *) source;
3892 if (child_watch_source->child_exited)
3895 if (child_watch_source->count < count)
3899 if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
3901 child_watch_source->child_status = child_status;
3902 child_watch_source->child_exited = TRUE;
3904 child_watch_source->count = count;
3907 return child_watch_source->child_exited;
3911 g_child_watch_prepare (GSource *source,
3916 return check_for_child_exited (source);
3921 g_child_watch_check (GSource *source)
3923 return check_for_child_exited (source);
3926 #endif /* G_OS_WIN32 */
3929 g_child_watch_dispatch (GSource *source,
3930 GSourceFunc callback,
3933 GChildWatchSource *child_watch_source;
3934 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
3936 child_watch_source = (GChildWatchSource *) source;
3940 g_warning ("Child watch source dispatched without callback\n"
3941 "You must call g_source_set_callback().");
3945 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
3947 /* We never keep a child watch source around as the child is gone */
3954 g_child_watch_signal_handler (int signum)
3956 child_watch_count ++;
3958 if (child_watch_init_state == CHILD_WATCH_INITIALIZED_THREADED)
3960 write (child_watch_wake_up_pipe[1], "B", 1);
3964 /* We count on the signal interrupting the poll in the same thread.
3970 g_child_watch_source_init_single (void)
3972 struct sigaction action;
3974 g_assert (! g_thread_supported());
3975 g_assert (child_watch_init_state == CHILD_WATCH_UNINITIALIZED);
3977 child_watch_init_state = CHILD_WATCH_INITIALIZED_SINGLE;
3979 action.sa_handler = g_child_watch_signal_handler;
3980 sigemptyset (&action.sa_mask);
3981 action.sa_flags = SA_NOCLDSTOP;
3982 sigaction (SIGCHLD, &action, NULL);
3985 G_GNUC_NORETURN static gpointer
3986 child_watch_helper_thread (gpointer data)
3993 read (child_watch_wake_up_pipe[0], b, 20);
3995 /* We were woken up. Wake up all other contexts in all other threads */
3996 G_LOCK (main_context_list);
3997 for (list = main_context_list; list; list = list->next)
3999 GMainContext *context;
4001 context = list->data;
4002 if (g_atomic_int_get (&context->ref_count) > 0)
4003 /* Due to racing conditions we can find ref_count == 0, in
4004 * that case, however, the context is still not destroyed
4005 * and no poll can be active, otherwise the ref_count
4007 g_main_context_wakeup (context);
4009 G_UNLOCK (main_context_list);
4014 g_child_watch_source_init_multi_threaded (void)
4016 GError *error = NULL;
4017 struct sigaction action;
4019 g_assert (g_thread_supported());
4021 if (pipe (child_watch_wake_up_pipe) < 0)
4022 g_error ("Cannot create wake up pipe: %s\n", g_strerror (errno));
4023 fcntl (child_watch_wake_up_pipe[1], F_SETFL, O_NONBLOCK | fcntl (child_watch_wake_up_pipe[1], F_GETFL));
4025 /* We create a helper thread that polls on the wakeup pipe indefinitely */
4026 /* FIXME: Think this through for races */
4027 if (g_thread_create (child_watch_helper_thread, NULL, FALSE, &error) == NULL)
4028 g_error ("Cannot create a thread to monitor child exit status: %s\n", error->message);
4029 child_watch_init_state = CHILD_WATCH_INITIALIZED_THREADED;
4031 action.sa_handler = g_child_watch_signal_handler;
4032 sigemptyset (&action.sa_mask);
4033 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4034 sigaction (SIGCHLD, &action, NULL);
4038 g_child_watch_source_init_promote_single_to_threaded (void)
4040 g_child_watch_source_init_multi_threaded ();
4044 g_child_watch_source_init (void)
4046 if (g_thread_supported())
4048 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
4049 g_child_watch_source_init_multi_threaded ();
4050 else if (child_watch_init_state == CHILD_WATCH_INITIALIZED_SINGLE)
4051 g_child_watch_source_init_promote_single_to_threaded ();
4055 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
4056 g_child_watch_source_init_single ();
4060 #endif /* !G_OS_WIN32 */
4063 * g_child_watch_source_new:
4064 * @pid: process to watch. On POSIX the pid of a child process. On
4065 * Windows a handle for a process (which doesn't have to be a child).
4067 * Creates a new child_watch source.
4069 * The source will not initially be associated with any #GMainContext
4070 * and must be added to one with g_source_attach() before it will be
4073 * Note that child watch sources can only be used in conjunction with
4074 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4077 * Note that on platforms where #GPid must be explicitly closed
4078 * (see g_spawn_close_pid()) @pid must not be closed while the
4079 * source is still active. Typically, you will want to call
4080 * g_spawn_close_pid() in the callback function for the source.
4082 * Note further that using g_child_watch_source_new() is not
4083 * compatible with calling <literal>waitpid(-1)</literal> in
4084 * the application. Calling waitpid() for individual pids will
4087 * Return value: the newly-created child watch source
4092 g_child_watch_source_new (GPid pid)
4094 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4095 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4098 child_watch_source->poll.fd = (gintptr) pid;
4099 child_watch_source->poll.events = G_IO_IN;
4101 g_source_add_poll (source, &child_watch_source->poll);
4102 #else /* G_OS_WIN32 */
4103 g_child_watch_source_init ();
4104 #endif /* G_OS_WIN32 */
4106 child_watch_source->pid = pid;
4112 * g_child_watch_add_full:
4113 * @priority: the priority of the idle source. Typically this will be in the
4114 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4115 * @pid: process to watch. On POSIX the pid of a child process. On
4116 * Windows a handle for a process (which doesn't have to be a child).
4117 * @function: function to call
4118 * @data: data to pass to @function
4119 * @notify: function to call when the idle is removed, or %NULL
4121 * Sets a function to be called when the child indicated by @pid
4122 * exits, at the priority @priority.
4124 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4125 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4126 * the spawn function for the child watching to work.
4128 * Note that on platforms where #GPid must be explicitly closed
4129 * (see g_spawn_close_pid()) @pid must not be closed while the
4130 * source is still active. Typically, you will want to call
4131 * g_spawn_close_pid() in the callback function for the source.
4133 * GLib supports only a single callback per process id.
4135 * This internally creates a main loop source using
4136 * g_child_watch_source_new() and attaches it to the main loop context
4137 * using g_source_attach(). You can do these steps manually if you
4138 * need greater control.
4140 * Return value: the ID (greater than 0) of the event source.
4145 g_child_watch_add_full (gint priority,
4147 GChildWatchFunc function,
4149 GDestroyNotify notify)
4154 g_return_val_if_fail (function != NULL, 0);
4156 source = g_child_watch_source_new (pid);
4158 if (priority != G_PRIORITY_DEFAULT)
4159 g_source_set_priority (source, priority);
4161 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4162 id = g_source_attach (source, NULL);
4163 g_source_unref (source);
4169 * g_child_watch_add:
4170 * @pid: process id to watch. On POSIX the pid of a child process. On
4171 * Windows a handle for a process (which doesn't have to be a child).
4172 * @function: function to call
4173 * @data: data to pass to @function
4175 * Sets a function to be called when the child indicated by @pid
4176 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4178 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4179 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4180 * the spawn function for the child watching to work.
4182 * Note that on platforms where #GPid must be explicitly closed
4183 * (see g_spawn_close_pid()) @pid must not be closed while the
4184 * source is still active. Typically, you will want to call
4185 * g_spawn_close_pid() in the callback function for the source.
4187 * GLib supports only a single callback per process id.
4189 * This internally creates a main loop source using
4190 * g_child_watch_source_new() and attaches it to the main loop context
4191 * using g_source_attach(). You can do these steps manually if you
4192 * need greater control.
4194 * Return value: the ID (greater than 0) of the event source.
4199 g_child_watch_add (GPid pid,
4200 GChildWatchFunc function,
4203 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4207 /* Idle functions */
4210 g_idle_prepare (GSource *source,
4219 g_idle_check (GSource *source)
4225 g_idle_dispatch (GSource *source,
4226 GSourceFunc callback,
4231 g_warning ("Idle source dispatched without callback\n"
4232 "You must call g_source_set_callback().");
4236 return callback (user_data);
4240 * g_idle_source_new:
4242 * Creates a new idle source.
4244 * The source will not initially be associated with any #GMainContext
4245 * and must be added to one with g_source_attach() before it will be
4246 * executed. Note that the default priority for idle sources is
4247 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4248 * have a default priority of %G_PRIORITY_DEFAULT.
4250 * Return value: the newly-created idle source
4253 g_idle_source_new (void)
4257 source = g_source_new (&g_idle_funcs, sizeof (GSource));
4258 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4265 * @priority: the priority of the idle source. Typically this will be in the
4266 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4267 * @function: function to call
4268 * @data: data to pass to @function
4269 * @notify: function to call when the idle is removed, or %NULL
4271 * Adds a function to be called whenever there are no higher priority
4272 * events pending. If the function returns %FALSE it is automatically
4273 * removed from the list of event sources and will not be called again.
4275 * This internally creates a main loop source using g_idle_source_new()
4276 * and attaches it to the main loop context using g_source_attach().
4277 * You can do these steps manually if you need greater control.
4279 * Return value: the ID (greater than 0) of the event source.
4282 g_idle_add_full (gint priority,
4283 GSourceFunc function,
4285 GDestroyNotify notify)
4290 g_return_val_if_fail (function != NULL, 0);
4292 source = g_idle_source_new ();
4294 if (priority != G_PRIORITY_DEFAULT_IDLE)
4295 g_source_set_priority (source, priority);
4297 g_source_set_callback (source, function, data, notify);
4298 id = g_source_attach (source, NULL);
4299 g_source_unref (source);
4306 * @function: function to call
4307 * @data: data to pass to @function.
4309 * Adds a function to be called whenever there are no higher priority
4310 * events pending to the default main loop. The function is given the
4311 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4312 * returns %FALSE it is automatically removed from the list of event
4313 * sources and will not be called again.
4315 * This internally creates a main loop source using g_idle_source_new()
4316 * and attaches it to the main loop context using g_source_attach().
4317 * You can do these steps manually if you need greater control.
4319 * Return value: the ID (greater than 0) of the event source.
4322 g_idle_add (GSourceFunc function,
4325 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4329 * g_idle_remove_by_data:
4330 * @data: the data for the idle source's callback.
4332 * Removes the idle function with the given data.
4334 * Return value: %TRUE if an idle source was found and removed.
4337 g_idle_remove_by_data (gpointer data)
4339 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);