1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * gmain.c: Main loop abstraction, timeouts, and idle functions
5 * Copyright 1998 Owen Taylor
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the
19 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 * Boston, MA 02111-1307, USA.
24 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
25 * file for a list of people on the GLib Team. See the ChangeLog
26 * files for a list of changes. These files are distributed with
27 * GLib at ftp://ftp.gtk.org/pub/gtk/.
35 /* for pipe2; need to define it first to avoid
36 * other headers pulling in unistd.h
38 /* The meaning of_GNU_SOURCE that is intended here is present only on
39 * Linux; avoid the possibility that some misguided header in MinGW
40 * looks at it. Ideally we should define _GNU_SOURCE only on platforms
41 * where we know what it means and that is what we want here
42 * (i.e. Linux with glibc). After all, there might be some other POSIX
43 * platform even where _GNU_SOURCE is used for some unrelated change
44 * in semantics that isn't wanted. Sigh.
50 #include "glibconfig.h"
52 /* Uncomment the next line (and the corresponding line in gpoll.c) to
53 * enable debugging printouts if the environment variable
54 * G_MAIN_POLL_DEBUG is set to some value.
56 /* #define G_MAIN_POLL_DEBUG */
59 /* Always enable debugging printout on Windows, as it is more often
62 #define G_MAIN_POLL_DEBUG
66 #include <sys/types.h>
69 #ifdef HAVE_SYS_TIME_H
71 #endif /* HAVE_SYS_TIME_H */
74 #endif /* HAVE_UNISTD_H */
80 #endif /* G_OS_WIN32 */
83 #include <sys/socket.h>
85 #endif /* G_OS_BEOS */
95 #include "giochannel.h"
99 #include "gstrfuncs.h"
100 #include "gtestutils.h"
101 #include "gthreadprivate.h"
107 #ifdef G_MAIN_POLL_DEBUG
113 * @title: The Main Event Loop
114 * @short_description: manages all available sources of events
116 * The main event loop manages all the available sources of events for
117 * GLib and GTK+ applications. These events can come from any number of
118 * different types of sources such as file descriptors (plain files,
119 * pipes or sockets) and timeouts. New types of event sources can also
120 * be added using g_source_attach().
122 * To allow multiple independent sets of sources to be handled in
123 * different threads, each source is associated with a #GMainContext.
124 * A GMainContext can only be running in a single thread, but
125 * sources can be added to it and removed from it from other threads.
127 * Each event source is assigned a priority. The default priority,
128 * #G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
129 * Values greater than 0 denote lower priorities. Events from high priority
130 * sources are always processed before events from lower priority sources.
132 * Idle functions can also be added, and assigned a priority. These will
133 * be run whenever no events with a higher priority are ready to be processed.
135 * The #GMainLoop data type represents a main event loop. A GMainLoop is
136 * created with g_main_loop_new(). After adding the initial event sources,
137 * g_main_loop_run() is called. This continuously checks for new events from
138 * each of the event sources and dispatches them. Finally, the processing of
139 * an event from one of the sources leads to a call to g_main_loop_quit() to
140 * exit the main loop, and g_main_loop_run() returns.
142 * It is possible to create new instances of #GMainLoop recursively.
143 * This is often used in GTK+ applications when showing modal dialog
144 * boxes. Note that event sources are associated with a particular
145 * #GMainContext, and will be checked and dispatched for all main
146 * loops associated with that GMainContext.
148 * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
149 * gtk_main_quit() and gtk_events_pending().
151 * <refsect2><title>Creating new source types</title>
152 * <para>One of the unusual features of the #GMainLoop functionality
153 * is that new types of event source can be created and used in
154 * addition to the builtin type of event source. A new event source
155 * type is used for handling GDK events. A new source type is created
156 * by <firstterm>deriving</firstterm> from the #GSource structure.
157 * The derived type of source is represented by a structure that has
158 * the #GSource structure as a first element, and other elements specific
159 * to the new source type. To create an instance of the new source type,
160 * call g_source_new() passing in the size of the derived structure and
161 * a table of functions. These #GSourceFuncs determine the behavior of
162 * the new source type.</para>
163 * <para>New source types basically interact with the main context
164 * in two ways. Their prepare function in #GSourceFuncs can set a timeout
165 * to determine the maximum amount of time that the main loop will sleep
166 * before checking the source again. In addition, or as well, the source
167 * can add file descriptors to the set that the main context checks using
168 * g_source_add_poll().</para>
170 * <refsect2><title>Customizing the main loop iteration</title>
171 * <para>Single iterations of a #GMainContext can be run with
172 * g_main_context_iteration(). In some cases, more detailed control
173 * of exactly how the details of the main loop work is desired, for
174 * instance, when integrating the #GMainLoop with an external main loop.
175 * In such cases, you can call the component functions of
176 * g_main_context_iteration() directly. These functions are
177 * g_main_context_prepare(), g_main_context_query(),
178 * g_main_context_check() and g_main_context_dispatch().</para>
179 * <para>The operation of these functions can best be seen in terms
180 * of a state diagram, as shown in <xref linkend="mainloop-states"/>.</para>
181 * <figure id="mainloop-states"><title>States of a Main Context</title>
182 * <graphic fileref="mainloop-states.gif" format="GIF"></graphic>
189 typedef struct _GTimeoutSource GTimeoutSource;
190 typedef struct _GChildWatchSource GChildWatchSource;
191 typedef struct _GPollRec GPollRec;
192 typedef struct _GSourceCallback GSourceCallback;
196 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
197 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
200 #ifdef G_THREADS_ENABLED
201 typedef struct _GMainWaiter GMainWaiter;
210 typedef struct _GMainDispatch GMainDispatch;
212 struct _GMainDispatch
215 GSList *dispatching_sources; /* stack of current sources */
218 #ifdef G_MAIN_POLL_DEBUG
219 gboolean _g_main_poll_debug = FALSE;
224 #ifdef G_THREADS_ENABLED
225 /* The following lock is used for both the list of sources
226 * and the list of poll records
237 GPtrArray *pending_dispatches;
238 gint timeout; /* Timeout for current iteration */
241 GSource *source_list;
242 gint in_check_or_prepare;
244 GPollRec *poll_records;
245 guint n_poll_records;
246 GPollFD *cached_poll_array;
247 guint cached_poll_array_size;
249 #ifdef G_THREADS_ENABLED
251 /* this pipe is used to wake up the main loop when a source is added.
253 gint wake_up_pipe[2];
254 #else /* G_OS_WIN32 */
255 HANDLE wake_up_semaphore;
256 #endif /* G_OS_WIN32 */
259 gboolean poll_waiting;
261 /* Flag indicating whether the set of fd's changed during a poll */
262 gboolean poll_changed;
263 #endif /* G_THREADS_ENABLED */
267 GTimeVal current_time;
268 gboolean time_is_current;
271 struct _GSourceCallback
276 GDestroyNotify notify;
281 GMainContext *context;
286 struct _GTimeoutSource
294 struct _GChildWatchSource
301 #else /* G_OS_WIN32 */
303 gboolean child_exited;
304 #endif /* G_OS_WIN32 */
314 #ifdef G_THREADS_ENABLED
315 #define LOCK_CONTEXT(context) g_static_mutex_lock (&context->mutex)
316 #define UNLOCK_CONTEXT(context) g_static_mutex_unlock (&context->mutex)
317 #define G_THREAD_SELF g_thread_self ()
319 #define LOCK_CONTEXT(context) (void)0
320 #define UNLOCK_CONTEXT(context) (void)0
321 #define G_THREAD_SELF NULL
324 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
325 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
326 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
328 #define SOURCE_UNREF(source, context) \
330 if ((source)->ref_count > 1) \
331 (source)->ref_count--; \
333 g_source_unref_internal ((source), (context), TRUE); \
337 /* Forward declarations */
339 static void g_source_unref_internal (GSource *source,
340 GMainContext *context,
342 static void g_source_destroy_internal (GSource *source,
343 GMainContext *context,
345 static void g_main_context_poll (GMainContext *context,
350 static void g_main_context_add_poll_unlocked (GMainContext *context,
353 static void g_main_context_remove_poll_unlocked (GMainContext *context,
355 static void g_main_context_wakeup_unlocked (GMainContext *context);
357 static gboolean g_timeout_prepare (GSource *source,
359 static gboolean g_timeout_check (GSource *source);
360 static gboolean g_timeout_dispatch (GSource *source,
361 GSourceFunc callback,
363 static gboolean g_child_watch_prepare (GSource *source,
365 static gboolean g_child_watch_check (GSource *source);
366 static gboolean g_child_watch_dispatch (GSource *source,
367 GSourceFunc callback,
369 static gboolean g_idle_prepare (GSource *source,
371 static gboolean g_idle_check (GSource *source);
372 static gboolean g_idle_dispatch (GSource *source,
373 GSourceFunc callback,
376 G_LOCK_DEFINE_STATIC (main_loop);
377 static GMainContext *default_main_context;
378 static GSList *main_contexts_without_pipe = NULL;
381 /* Child status monitoring code */
383 CHILD_WATCH_UNINITIALIZED,
384 CHILD_WATCH_INITIALIZED_SINGLE,
385 CHILD_WATCH_INITIALIZED_THREADED
387 static gint child_watch_init_state = CHILD_WATCH_UNINITIALIZED;
388 static gint child_watch_count = 1;
389 static gint child_watch_wake_up_pipe[2] = {0, 0};
390 #endif /* !G_OS_WIN32 */
391 G_LOCK_DEFINE_STATIC (main_context_list);
392 static GSList *main_context_list = NULL;
394 static gint timer_perturb = -1;
396 GSourceFuncs g_timeout_funcs =
404 GSourceFuncs g_child_watch_funcs =
406 g_child_watch_prepare,
408 g_child_watch_dispatch,
412 GSourceFuncs g_idle_funcs =
421 * g_main_context_ref:
422 * @context: a #GMainContext
424 * Increases the reference count on a #GMainContext object by one.
426 * Returns: the @context that was passed in (since 2.6)
429 g_main_context_ref (GMainContext *context)
431 g_return_val_if_fail (context != NULL, NULL);
432 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
434 g_atomic_int_inc (&context->ref_count);
440 poll_rec_list_free (GMainContext *context,
443 g_slice_free_chain (GPollRec, list, next);
447 * g_main_context_unref:
448 * @context: a #GMainContext
450 * Decreases the reference count on a #GMainContext object by one. If
451 * the result is zero, free the context and free all associated memory.
454 g_main_context_unref (GMainContext *context)
457 g_return_if_fail (context != NULL);
458 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
460 if (!g_atomic_int_dec_and_test (&context->ref_count))
463 G_LOCK (main_context_list);
464 main_context_list = g_slist_remove (main_context_list, context);
465 G_UNLOCK (main_context_list);
467 source = context->source_list;
470 GSource *next = source->next;
471 g_source_destroy_internal (source, context, FALSE);
475 #ifdef G_THREADS_ENABLED
476 g_static_mutex_free (&context->mutex);
479 g_ptr_array_free (context->pending_dispatches, TRUE);
480 g_free (context->cached_poll_array);
482 poll_rec_list_free (context, context->poll_records);
484 #ifdef G_THREADS_ENABLED
485 if (g_thread_supported())
488 close (context->wake_up_pipe[0]);
489 close (context->wake_up_pipe[1]);
491 CloseHandle (context->wake_up_semaphore);
495 main_contexts_without_pipe = g_slist_remove (main_contexts_without_pipe,
498 if (context->cond != NULL)
499 g_cond_free (context->cond);
505 #ifdef G_THREADS_ENABLED
507 g_main_context_init_pipe (GMainContext *context)
510 if (context->wake_up_pipe[0] != -1)
514 /* if this fails, we fall through and try pipe */
515 pipe2 (context->wake_up_pipe, O_CLOEXEC);
517 if (context->wake_up_pipe[0] == -1)
519 if (pipe (context->wake_up_pipe) < 0)
520 g_error ("Cannot create pipe main loop wake-up: %s\n",
523 fcntl (context->wake_up_pipe[0], F_SETFD, FD_CLOEXEC);
524 fcntl (context->wake_up_pipe[1], F_SETFD, FD_CLOEXEC);
527 context->wake_up_rec.fd = context->wake_up_pipe[0];
528 context->wake_up_rec.events = G_IO_IN;
530 if (context->wake_up_semaphore != NULL)
532 context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
533 if (context->wake_up_semaphore == NULL)
534 g_error ("Cannot create wake-up semaphore: %s",
535 g_win32_error_message (GetLastError ()));
536 context->wake_up_rec.fd = (gintptr) context->wake_up_semaphore;
537 context->wake_up_rec.events = G_IO_IN;
539 if (_g_main_poll_debug)
540 g_print ("wake-up semaphore: %p\n", context->wake_up_semaphore);
542 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
546 _g_main_thread_init (void)
548 GSList *curr = main_contexts_without_pipe;
551 g_main_context_init_pipe ((GMainContext *)curr->data);
554 g_slist_free (main_contexts_without_pipe);
555 main_contexts_without_pipe = NULL;
557 #endif /* G_THREADS_ENABLED */
560 * g_main_context_new:
562 * Creates a new #GMainContext structure.
564 * Return value: the new #GMainContext
567 g_main_context_new (void)
569 GMainContext *context = g_new0 (GMainContext, 1);
571 #ifdef G_MAIN_POLL_DEBUG
573 static gboolean beenhere = FALSE;
577 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
578 _g_main_poll_debug = TRUE;
584 #ifdef G_THREADS_ENABLED
585 g_static_mutex_init (&context->mutex);
587 context->owner = NULL;
588 context->waiters = NULL;
591 context->wake_up_pipe[0] = -1;
592 context->wake_up_pipe[1] = -1;
594 context->wake_up_semaphore = NULL;
598 context->ref_count = 1;
600 context->next_id = 1;
602 context->source_list = NULL;
604 context->poll_func = g_poll;
606 context->cached_poll_array = NULL;
607 context->cached_poll_array_size = 0;
609 context->pending_dispatches = g_ptr_array_new ();
611 context->time_is_current = FALSE;
613 #ifdef G_THREADS_ENABLED
614 if (g_thread_supported ())
615 g_main_context_init_pipe (context);
617 main_contexts_without_pipe = g_slist_prepend (main_contexts_without_pipe,
621 G_LOCK (main_context_list);
622 main_context_list = g_slist_append (main_context_list, context);
624 #ifdef G_MAIN_POLL_DEBUG
625 if (_g_main_poll_debug)
626 g_print ("created context=%p\n", context);
629 G_UNLOCK (main_context_list);
635 * g_main_context_default:
637 * Returns the global default main context. This is the main context
638 * used for main loop functions when a main loop is not explicitly
639 * specified, and corresponds to the "main" main loop. See also
640 * g_main_context_get_thread_default().
642 * Return value: the global default main context.
645 g_main_context_default (void)
651 if (!default_main_context)
653 default_main_context = g_main_context_new ();
654 #ifdef G_MAIN_POLL_DEBUG
655 if (_g_main_poll_debug)
656 g_print ("default context=%p\n", default_main_context);
660 G_UNLOCK (main_loop);
662 return default_main_context;
665 static GStaticPrivate thread_context_stack = G_STATIC_PRIVATE_INIT;
668 free_context_stack (gpointer data)
670 GQueue *stack = data;
671 GMainContext *context;
673 while (!g_queue_is_empty (stack))
675 context = g_queue_pop_head (stack);
676 g_main_context_release (context);
678 g_main_context_unref (context);
680 g_queue_free (stack);
684 * g_main_context_push_thread_default:
685 * @context: a #GMainContext, or %NULL for the global default context
687 * Acquires @context and sets it as the thread-default context for the
688 * current thread. This will cause certain asynchronous operations
689 * (such as most <link linkend="gio">gio</link>-based I/O) which are
690 * started in this thread to run under @context and deliver their
691 * results to its main loop, rather than running under the global
692 * default context in the main thread. Note that calling this function
693 * changes the context returned by
694 * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
695 * one returned by g_main_context_default(), so it does not affect the
696 * context used by functions like g_idle_add().
698 * Normally you would call this function shortly after creating a new
699 * thread, passing it a #GMainContext which will be run by a
700 * #GMainLoop in that thread, to set a new default context for all
701 * async operations in that thread. (In this case, you don't need to
702 * ever call g_main_context_pop_thread_default().) In some cases
703 * however, you may want to schedule a single operation in a
704 * non-default context, or temporarily use a non-default context in
705 * the main thread. In that case, you can wrap the call to the
706 * asynchronous operation inside a
707 * g_main_context_push_thread_default() /
708 * g_main_context_pop_thread_default() pair, but it is up to you to
709 * ensure that no other asynchronous operations accidentally get
710 * started while the non-default context is active.
712 * Beware that libraries that predate this function may not correctly
713 * handle being used from a thread with a thread-default context. Eg,
714 * see g_file_supports_thread_contexts().
719 g_main_context_push_thread_default (GMainContext *context)
722 gboolean acquired_context;
724 acquired_context = g_main_context_acquire (context);
725 g_return_if_fail (acquired_context);
727 if (context == g_main_context_default ())
730 g_main_context_ref (context);
732 stack = g_static_private_get (&thread_context_stack);
735 stack = g_queue_new ();
736 g_static_private_set (&thread_context_stack, stack,
740 g_queue_push_head (stack, context);
744 * g_main_context_pop_thread_default:
745 * @context: a #GMainContext object, or %NULL
747 * Pops @context off the thread-default context stack (verifying that
748 * it was on the top of the stack).
753 g_main_context_pop_thread_default (GMainContext *context)
757 if (context == g_main_context_default ())
760 stack = g_static_private_get (&thread_context_stack);
762 g_return_if_fail (stack != NULL);
763 g_return_if_fail (g_queue_peek_head (stack) == context);
765 g_queue_pop_head (stack);
767 g_main_context_release (context);
769 g_main_context_unref (context);
773 * g_main_context_get_thread_default:
775 * Gets the thread-default #GMainContext for this thread. Asynchronous
776 * operations that want to be able to be run in contexts other than
777 * the default one should call this method to get a #GMainContext to
778 * add their #GSource<!-- -->s to. (Note that even in single-threaded
779 * programs applications may sometimes want to temporarily push a
780 * non-default context, so it is not safe to assume that this will
781 * always return %NULL if threads are not initialized.)
783 * Returns: the thread-default #GMainContext, or %NULL if the
784 * thread-default context is the global default context.
789 g_main_context_get_thread_default (void)
793 stack = g_static_private_get (&thread_context_stack);
795 return g_queue_peek_head (stack);
800 /* Hooks for adding to the main loop */
804 * @source_funcs: structure containing functions that implement
805 * the sources behavior.
806 * @struct_size: size of the #GSource structure to create.
808 * Creates a new #GSource structure. The size is specified to
809 * allow creating structures derived from #GSource that contain
810 * additional data. The size passed in must be at least
811 * <literal>sizeof (GSource)</literal>.
813 * The source will not initially be associated with any #GMainContext
814 * and must be added to one with g_source_attach() before it will be
817 * Return value: the newly-created #GSource.
820 g_source_new (GSourceFuncs *source_funcs,
825 g_return_val_if_fail (source_funcs != NULL, NULL);
826 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
828 source = (GSource*) g_malloc0 (struct_size);
830 source->source_funcs = source_funcs;
831 source->ref_count = 1;
833 source->priority = G_PRIORITY_DEFAULT;
835 source->flags = G_HOOK_FLAG_ACTIVE;
837 /* NULL/0 initialization for all other fields */
842 /* Holds context's lock
845 g_source_list_add (GSource *source,
846 GMainContext *context)
848 GSource *tmp_source, *last_source;
851 tmp_source = context->source_list;
852 while (tmp_source && tmp_source->priority <= source->priority)
854 last_source = tmp_source;
855 tmp_source = tmp_source->next;
858 source->next = tmp_source;
860 tmp_source->prev = source;
862 source->prev = last_source;
864 last_source->next = source;
866 context->source_list = source;
869 /* Holds context's lock
872 g_source_list_remove (GSource *source,
873 GMainContext *context)
876 source->prev->next = source->next;
878 context->source_list = source->next;
881 source->next->prev = source->prev;
889 * @source: a #GSource
890 * @context: a #GMainContext (if %NULL, the default context will be used)
892 * Adds a #GSource to a @context so that it will be executed within
893 * that context. Remove it by calling g_source_destroy().
895 * Return value: the ID (greater than 0) for the source within the
899 g_source_attach (GSource *source,
900 GMainContext *context)
905 g_return_val_if_fail (source->context == NULL, 0);
906 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
909 context = g_main_context_default ();
911 LOCK_CONTEXT (context);
913 source->context = context;
914 result = source->source_id = context->next_id++;
917 g_source_list_add (source, context);
919 tmp_list = source->poll_fds;
922 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
923 tmp_list = tmp_list->next;
926 #ifdef G_THREADS_ENABLED
927 /* Now wake up the main loop if it is waiting in the poll() */
928 g_main_context_wakeup_unlocked (context);
931 UNLOCK_CONTEXT (context);
937 g_source_destroy_internal (GSource *source,
938 GMainContext *context,
942 LOCK_CONTEXT (context);
944 if (!SOURCE_DESTROYED (source))
947 gpointer old_cb_data;
948 GSourceCallbackFuncs *old_cb_funcs;
950 source->flags &= ~G_HOOK_FLAG_ACTIVE;
952 old_cb_data = source->callback_data;
953 old_cb_funcs = source->callback_funcs;
955 source->callback_data = NULL;
956 source->callback_funcs = NULL;
960 UNLOCK_CONTEXT (context);
961 old_cb_funcs->unref (old_cb_data);
962 LOCK_CONTEXT (context);
965 if (!SOURCE_BLOCKED (source))
967 tmp_list = source->poll_fds;
970 g_main_context_remove_poll_unlocked (context, tmp_list->data);
971 tmp_list = tmp_list->next;
975 g_source_unref_internal (source, context, TRUE);
979 UNLOCK_CONTEXT (context);
984 * @source: a #GSource
986 * Removes a source from its #GMainContext, if any, and mark it as
987 * destroyed. The source cannot be subsequently added to another
991 g_source_destroy (GSource *source)
993 GMainContext *context;
995 g_return_if_fail (source != NULL);
997 context = source->context;
1000 g_source_destroy_internal (source, context, FALSE);
1002 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1007 * @source: a #GSource
1009 * Returns the numeric ID for a particular source. The ID of a source
1010 * is a positive integer which is unique within a particular main loop
1011 * context. The reverse
1012 * mapping from ID to source is done by g_main_context_find_source_by_id().
1014 * Return value: the ID (greater than 0) for the source
1017 g_source_get_id (GSource *source)
1021 g_return_val_if_fail (source != NULL, 0);
1022 g_return_val_if_fail (source->context != NULL, 0);
1024 LOCK_CONTEXT (source->context);
1025 result = source->source_id;
1026 UNLOCK_CONTEXT (source->context);
1032 * g_source_get_context:
1033 * @source: a #GSource
1035 * Gets the #GMainContext with which the source is associated.
1036 * Calling this function on a destroyed source is an error.
1038 * Return value: the #GMainContext with which the source is associated,
1039 * or %NULL if the context has not yet been added
1043 g_source_get_context (GSource *source)
1045 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1047 return source->context;
1051 * g_source_add_poll:
1052 * @source:a #GSource
1053 * @fd: a #GPollFD structure holding information about a file
1054 * descriptor to watch.
1056 * Adds a file descriptor to the set of file descriptors polled for
1057 * this source. This is usually combined with g_source_new() to add an
1058 * event source. The event source's check function will typically test
1059 * the @revents field in the #GPollFD struct and return %TRUE if events need
1063 g_source_add_poll (GSource *source,
1066 GMainContext *context;
1068 g_return_if_fail (source != NULL);
1069 g_return_if_fail (fd != NULL);
1070 g_return_if_fail (!SOURCE_DESTROYED (source));
1072 context = source->context;
1075 LOCK_CONTEXT (context);
1077 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1081 if (!SOURCE_BLOCKED (source))
1082 g_main_context_add_poll_unlocked (context, source->priority, fd);
1083 UNLOCK_CONTEXT (context);
1088 * g_source_remove_poll:
1089 * @source:a #GSource
1090 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1092 * Removes a file descriptor from the set of file descriptors polled for
1096 g_source_remove_poll (GSource *source,
1099 GMainContext *context;
1101 g_return_if_fail (source != NULL);
1102 g_return_if_fail (fd != NULL);
1103 g_return_if_fail (!SOURCE_DESTROYED (source));
1105 context = source->context;
1108 LOCK_CONTEXT (context);
1110 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1114 if (!SOURCE_BLOCKED (source))
1115 g_main_context_remove_poll_unlocked (context, fd);
1116 UNLOCK_CONTEXT (context);
1121 * g_source_set_callback_indirect:
1122 * @source: the source
1123 * @callback_data: pointer to callback data "object"
1124 * @callback_funcs: functions for reference counting @callback_data
1125 * and getting the callback and data
1127 * Sets the callback function storing the data as a refcounted callback
1128 * "object". This is used internally. Note that calling
1129 * g_source_set_callback_indirect() assumes
1130 * an initial reference count on @callback_data, and thus
1131 * @callback_funcs->unref will eventually be called once more
1132 * than @callback_funcs->ref.
1135 g_source_set_callback_indirect (GSource *source,
1136 gpointer callback_data,
1137 GSourceCallbackFuncs *callback_funcs)
1139 GMainContext *context;
1140 gpointer old_cb_data;
1141 GSourceCallbackFuncs *old_cb_funcs;
1143 g_return_if_fail (source != NULL);
1144 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1146 context = source->context;
1149 LOCK_CONTEXT (context);
1151 old_cb_data = source->callback_data;
1152 old_cb_funcs = source->callback_funcs;
1154 source->callback_data = callback_data;
1155 source->callback_funcs = callback_funcs;
1158 UNLOCK_CONTEXT (context);
1161 old_cb_funcs->unref (old_cb_data);
1165 g_source_callback_ref (gpointer cb_data)
1167 GSourceCallback *callback = cb_data;
1169 callback->ref_count++;
1174 g_source_callback_unref (gpointer cb_data)
1176 GSourceCallback *callback = cb_data;
1178 callback->ref_count--;
1179 if (callback->ref_count == 0)
1181 if (callback->notify)
1182 callback->notify (callback->data);
1188 g_source_callback_get (gpointer cb_data,
1193 GSourceCallback *callback = cb_data;
1195 *func = callback->func;
1196 *data = callback->data;
1199 static GSourceCallbackFuncs g_source_callback_funcs = {
1200 g_source_callback_ref,
1201 g_source_callback_unref,
1202 g_source_callback_get,
1206 * g_source_set_callback:
1207 * @source: the source
1208 * @func: a callback function
1209 * @data: the data to pass to callback function
1210 * @notify: a function to call when @data is no longer in use, or %NULL.
1212 * Sets the callback function for a source. The callback for a source is
1213 * called from the source's dispatch function.
1215 * The exact type of @func depends on the type of source; ie. you
1216 * should not count on @func being called with @data as its first
1219 * Typically, you won't use this function. Instead use functions specific
1220 * to the type of source you are using.
1223 g_source_set_callback (GSource *source,
1226 GDestroyNotify notify)
1228 GSourceCallback *new_callback;
1230 g_return_if_fail (source != NULL);
1232 new_callback = g_new (GSourceCallback, 1);
1234 new_callback->ref_count = 1;
1235 new_callback->func = func;
1236 new_callback->data = data;
1237 new_callback->notify = notify;
1239 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1244 * g_source_set_funcs:
1245 * @source: a #GSource
1246 * @funcs: the new #GSourceFuncs
1248 * Sets the source functions (can be used to override
1249 * default implementations) of an unattached source.
1254 g_source_set_funcs (GSource *source,
1255 GSourceFuncs *funcs)
1257 g_return_if_fail (source != NULL);
1258 g_return_if_fail (source->context == NULL);
1259 g_return_if_fail (source->ref_count > 0);
1260 g_return_if_fail (funcs != NULL);
1262 source->source_funcs = funcs;
1266 * g_source_set_priority:
1267 * @source: a #GSource
1268 * @priority: the new priority.
1270 * Sets the priority of a source. While the main loop is being
1271 * run, a source will be dispatched if it is ready to be dispatched and no sources
1272 * at a higher (numerically smaller) priority are ready to be dispatched.
1275 g_source_set_priority (GSource *source,
1279 GMainContext *context;
1281 g_return_if_fail (source != NULL);
1283 context = source->context;
1286 LOCK_CONTEXT (context);
1288 source->priority = priority;
1292 /* Remove the source from the context's source and then
1293 * add it back so it is sorted in the correct plcae
1295 g_source_list_remove (source, source->context);
1296 g_source_list_add (source, source->context);
1298 if (!SOURCE_BLOCKED (source))
1300 tmp_list = source->poll_fds;
1303 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1304 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1306 tmp_list = tmp_list->next;
1310 UNLOCK_CONTEXT (source->context);
1315 * g_source_get_priority:
1316 * @source: a #GSource
1318 * Gets the priority of a source.
1320 * Return value: the priority of the source
1323 g_source_get_priority (GSource *source)
1325 g_return_val_if_fail (source != NULL, 0);
1327 return source->priority;
1331 * g_source_set_can_recurse:
1332 * @source: a #GSource
1333 * @can_recurse: whether recursion is allowed for this source
1335 * Sets whether a source can be called recursively. If @can_recurse is
1336 * %TRUE, then while the source is being dispatched then this source
1337 * will be processed normally. Otherwise, all processing of this
1338 * source is blocked until the dispatch function returns.
1341 g_source_set_can_recurse (GSource *source,
1342 gboolean can_recurse)
1344 GMainContext *context;
1346 g_return_if_fail (source != NULL);
1348 context = source->context;
1351 LOCK_CONTEXT (context);
1354 source->flags |= G_SOURCE_CAN_RECURSE;
1356 source->flags &= ~G_SOURCE_CAN_RECURSE;
1359 UNLOCK_CONTEXT (context);
1363 * g_source_get_can_recurse:
1364 * @source: a #GSource
1366 * Checks whether a source is allowed to be called recursively.
1367 * see g_source_set_can_recurse().
1369 * Return value: whether recursion is allowed.
1372 g_source_get_can_recurse (GSource *source)
1374 g_return_val_if_fail (source != NULL, FALSE);
1376 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1381 * g_source_set_name:
1382 * @source: a #GSource
1383 * @name: debug name for the source
1385 * Sets a name for the source, used in debugging and profiling.
1386 * The name defaults to #NULL.
1388 * The source name should describe in a human-readable way
1389 * what the source does. For example, "X11 event queue"
1390 * or "GTK+ repaint idle handler" or whatever it is.
1392 * It is permitted to call this function multiple times, but is not
1393 * recommended due to the potential performance impact. For example,
1394 * one could change the name in the "check" function of a #GSourceFuncs
1395 * to include details like the event type in the source name.
1400 g_source_set_name (GSource *source,
1403 g_return_if_fail (source != NULL);
1405 /* setting back to NULL is allowed, just because it's
1406 * weird if get_name can return NULL but you can't
1410 g_free (source->name);
1411 source->name = g_strdup (name);
1415 * g_source_get_name:
1416 * @source: a #GSource
1418 * Gets a name for the source, used in debugging and profiling.
1419 * The name may be #NULL if it has never been set with
1420 * g_source_set_name().
1422 * Return value: the name of the source
1425 G_CONST_RETURN char*
1426 g_source_get_name (GSource *source)
1428 g_return_val_if_fail (source != NULL, NULL);
1430 return source->name;
1434 * g_source_set_name_by_id:
1435 * @tag: a #GSource ID
1436 * @name: debug name for the source
1438 * Sets the name of a source using its ID.
1440 * This is a convenience utility to set source names from the return
1441 * value of g_idle_add(), g_timeout_add(), etc.
1446 g_source_set_name_by_id (guint tag,
1451 g_return_if_fail (tag > 0);
1453 source = g_main_context_find_source_by_id (NULL, tag);
1457 g_source_set_name (source, name);
1463 * @source: a #GSource
1465 * Increases the reference count on a source by one.
1467 * Return value: @source
1470 g_source_ref (GSource *source)
1472 GMainContext *context;
1474 g_return_val_if_fail (source != NULL, NULL);
1476 context = source->context;
1479 LOCK_CONTEXT (context);
1481 source->ref_count++;
1484 UNLOCK_CONTEXT (context);
1489 /* g_source_unref() but possible to call within context lock
1492 g_source_unref_internal (GSource *source,
1493 GMainContext *context,
1496 gpointer old_cb_data = NULL;
1497 GSourceCallbackFuncs *old_cb_funcs = NULL;
1499 g_return_if_fail (source != NULL);
1501 if (!have_lock && context)
1502 LOCK_CONTEXT (context);
1504 source->ref_count--;
1505 if (source->ref_count == 0)
1507 old_cb_data = source->callback_data;
1508 old_cb_funcs = source->callback_funcs;
1510 source->callback_data = NULL;
1511 source->callback_funcs = NULL;
1513 if (context && !SOURCE_DESTROYED (source))
1515 g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1516 source->ref_count++;
1519 g_source_list_remove (source, context);
1521 if (source->source_funcs->finalize)
1522 source->source_funcs->finalize (source);
1524 g_free (source->name);
1525 source->name = NULL;
1527 g_slist_free (source->poll_fds);
1528 source->poll_fds = NULL;
1532 if (!have_lock && context)
1533 UNLOCK_CONTEXT (context);
1538 UNLOCK_CONTEXT (context);
1540 old_cb_funcs->unref (old_cb_data);
1543 LOCK_CONTEXT (context);
1549 * @source: a #GSource
1551 * Decreases the reference count of a source by one. If the
1552 * resulting reference count is zero the source and associated
1553 * memory will be destroyed.
1556 g_source_unref (GSource *source)
1558 g_return_if_fail (source != NULL);
1560 g_source_unref_internal (source, source->context, FALSE);
1564 * g_main_context_find_source_by_id:
1565 * @context: a #GMainContext (if %NULL, the default context will be used)
1566 * @source_id: the source ID, as returned by g_source_get_id().
1568 * Finds a #GSource given a pair of context and ID.
1570 * Return value: the #GSource if found, otherwise, %NULL
1573 g_main_context_find_source_by_id (GMainContext *context,
1578 g_return_val_if_fail (source_id > 0, NULL);
1580 if (context == NULL)
1581 context = g_main_context_default ();
1583 LOCK_CONTEXT (context);
1585 source = context->source_list;
1588 if (!SOURCE_DESTROYED (source) &&
1589 source->source_id == source_id)
1591 source = source->next;
1594 UNLOCK_CONTEXT (context);
1600 * g_main_context_find_source_by_funcs_user_data:
1601 * @context: a #GMainContext (if %NULL, the default context will be used).
1602 * @funcs: the @source_funcs passed to g_source_new().
1603 * @user_data: the user data from the callback.
1605 * Finds a source with the given source functions and user data. If
1606 * multiple sources exist with the same source function and user data,
1607 * the first one found will be returned.
1609 * Return value: the source, if one was found, otherwise %NULL
1612 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1613 GSourceFuncs *funcs,
1618 g_return_val_if_fail (funcs != NULL, NULL);
1620 if (context == NULL)
1621 context = g_main_context_default ();
1623 LOCK_CONTEXT (context);
1625 source = context->source_list;
1628 if (!SOURCE_DESTROYED (source) &&
1629 source->source_funcs == funcs &&
1630 source->callback_funcs)
1632 GSourceFunc callback;
1633 gpointer callback_data;
1635 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1637 if (callback_data == user_data)
1640 source = source->next;
1643 UNLOCK_CONTEXT (context);
1649 * g_main_context_find_source_by_user_data:
1650 * @context: a #GMainContext
1651 * @user_data: the user_data for the callback.
1653 * Finds a source with the given user data for the callback. If
1654 * multiple sources exist with the same user data, the first
1655 * one found will be returned.
1657 * Return value: the source, if one was found, otherwise %NULL
1660 g_main_context_find_source_by_user_data (GMainContext *context,
1665 if (context == NULL)
1666 context = g_main_context_default ();
1668 LOCK_CONTEXT (context);
1670 source = context->source_list;
1673 if (!SOURCE_DESTROYED (source) &&
1674 source->callback_funcs)
1676 GSourceFunc callback;
1677 gpointer callback_data = NULL;
1679 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1681 if (callback_data == user_data)
1684 source = source->next;
1687 UNLOCK_CONTEXT (context);
1694 * @tag: the ID of the source to remove.
1696 * Removes the source with the given id from the default main context.
1698 * a #GSource is given by g_source_get_id(), or will be returned by the
1699 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1700 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1701 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1703 * See also g_source_destroy(). You must use g_source_destroy() for sources
1704 * added to a non-default main context.
1706 * Return value: %TRUE if the source was found and removed.
1709 g_source_remove (guint tag)
1713 g_return_val_if_fail (tag > 0, FALSE);
1715 source = g_main_context_find_source_by_id (NULL, tag);
1717 g_source_destroy (source);
1719 return source != NULL;
1723 * g_source_remove_by_user_data:
1724 * @user_data: the user_data for the callback.
1726 * Removes a source from the default main loop context given the user
1727 * data for the callback. If multiple sources exist with the same user
1728 * data, only one will be destroyed.
1730 * Return value: %TRUE if a source was found and removed.
1733 g_source_remove_by_user_data (gpointer user_data)
1737 source = g_main_context_find_source_by_user_data (NULL, user_data);
1740 g_source_destroy (source);
1748 * g_source_remove_by_funcs_user_data:
1749 * @funcs: The @source_funcs passed to g_source_new()
1750 * @user_data: the user data for the callback
1752 * Removes a source from the default main loop context given the
1753 * source functions and user data. If multiple sources exist with the
1754 * same source functions and user data, only one will be destroyed.
1756 * Return value: %TRUE if a source was found and removed.
1759 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1764 g_return_val_if_fail (funcs != NULL, FALSE);
1766 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1769 g_source_destroy (source);
1777 * g_get_current_time:
1778 * @result: #GTimeVal structure in which to store current time.
1780 * Equivalent to the UNIX gettimeofday() function, but portable.
1783 g_get_current_time (GTimeVal *result)
1788 g_return_if_fail (result != NULL);
1790 /*this is required on alpha, there the timeval structs are int's
1791 not longs and a cast only would fail horribly*/
1792 gettimeofday (&r, NULL);
1793 result->tv_sec = r.tv_sec;
1794 result->tv_usec = r.tv_usec;
1799 g_return_if_fail (result != NULL);
1801 GetSystemTimeAsFileTime (&ft);
1802 memmove (&time64, &ft, sizeof (FILETIME));
1804 /* Convert from 100s of nanoseconds since 1601-01-01
1805 * to Unix epoch. Yes, this is Y2038 unsafe.
1807 time64 -= G_GINT64_CONSTANT (116444736000000000);
1810 result->tv_sec = time64 / 1000000;
1811 result->tv_usec = time64 % 1000000;
1816 g_main_dispatch_free (gpointer dispatch)
1818 g_slice_free (GMainDispatch, dispatch);
1821 /* Running the main loop */
1823 static GMainDispatch *
1826 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
1827 GMainDispatch *dispatch = g_static_private_get (&depth_private);
1830 dispatch = g_slice_new0 (GMainDispatch);
1831 g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
1840 * Returns the depth of the stack of calls to
1841 * g_main_context_dispatch() on any #GMainContext in the current thread.
1842 * That is, when called from the toplevel, it gives 0. When
1843 * called from within a callback from g_main_context_iteration()
1844 * (or g_main_loop_run(), etc.) it returns 1. When called from within
1845 * a callback to a recursive call to g_main_context_iterate(),
1846 * it returns 2. And so forth.
1848 * This function is useful in a situation like the following:
1849 * Imagine an extremely simple "garbage collected" system.
1852 * static GList *free_list;
1855 * allocate_memory (gsize size)
1857 * gpointer result = g_malloc (size);
1858 * free_list = g_list_prepend (free_list, result);
1863 * free_allocated_memory (void)
1866 * for (l = free_list; l; l = l->next);
1868 * g_list_free (free_list);
1876 * g_main_context_iteration (NULL, TRUE);
1877 * free_allocated_memory();
1881 * This works from an application, however, if you want to do the same
1882 * thing from a library, it gets more difficult, since you no longer
1883 * control the main loop. You might think you can simply use an idle
1884 * function to make the call to free_allocated_memory(), but that
1885 * doesn't work, since the idle function could be called from a
1886 * recursive callback. This can be fixed by using g_main_depth()
1890 * allocate_memory (gsize size)
1892 * FreeListBlock *block = g_new (FreeListBlock, 1);
1893 * block->mem = g_malloc (size);
1894 * block->depth = g_main_depth ();
1895 * free_list = g_list_prepend (free_list, block);
1896 * return block->mem;
1900 * free_allocated_memory (void)
1904 * int depth = g_main_depth ();
1905 * for (l = free_list; l; );
1907 * GList *next = l->next;
1908 * FreeListBlock *block = l->data;
1909 * if (block->depth > depth)
1911 * g_free (block->mem);
1913 * free_list = g_list_delete_link (free_list, l);
1921 * There is a temptation to use g_main_depth() to solve
1922 * problems with reentrancy. For instance, while waiting for data
1923 * to be received from the network in response to a menu item,
1924 * the menu item might be selected again. It might seem that
1925 * one could make the menu item's callback return immediately
1926 * and do nothing if g_main_depth() returns a value greater than 1.
1927 * However, this should be avoided since the user then sees selecting
1928 * the menu item do nothing. Furthermore, you'll find yourself adding
1929 * these checks all over your code, since there are doubtless many,
1930 * many things that the user could do. Instead, you can use the
1931 * following techniques:
1936 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
1937 * the user from interacting with elements while the main
1938 * loop is recursing.
1943 * Avoid main loop recursion in situations where you can't handle
1944 * arbitrary callbacks. Instead, structure your code so that you
1945 * simply return to the main loop and then get called again when
1946 * there is more work to do.
1951 * Return value: The main loop recursion level in the current thread
1956 GMainDispatch *dispatch = get_dispatch ();
1957 return dispatch->depth;
1961 * g_main_current_source:
1963 * Returns the currently firing source for this thread.
1965 * Return value: The currently firing source or %NULL.
1970 g_main_current_source (void)
1972 GMainDispatch *dispatch = get_dispatch ();
1973 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
1977 * g_source_is_destroyed:
1978 * @source: a #GSource
1980 * Returns whether @source has been destroyed.
1982 * This is important when you operate upon your objects
1983 * from within idle handlers, but may have freed the object
1984 * before the dispatch of your idle handler.
1988 * idle_callback (gpointer data)
1990 * SomeWidget *self = data;
1992 * GDK_THREADS_ENTER (<!-- -->);
1993 * /<!-- -->* do stuff with self *<!-- -->/
1994 * self->idle_id = 0;
1995 * GDK_THREADS_LEAVE (<!-- -->);
2001 * some_widget_do_stuff_later (SomeWidget *self)
2003 * self->idle_id = g_idle_add (idle_callback, self);
2007 * some_widget_finalize (GObject *object)
2009 * SomeWidget *self = SOME_WIDGET (object);
2011 * if (self->idle_id)
2012 * g_source_remove (self->idle_id);
2014 * G_OBJECT_CLASS (parent_class)->finalize (object);
2018 * This will fail in a multi-threaded application if the
2019 * widget is destroyed before the idle handler fires due
2020 * to the use after free in the callback. A solution, to
2021 * this particular problem, is to check to if the source
2022 * has already been destroy within the callback.
2026 * idle_callback (gpointer data)
2028 * SomeWidget *self = data;
2030 * GDK_THREADS_ENTER ();
2031 * if (!g_source_is_destroyed (g_main_current_source ()))
2033 * /<!-- -->* do stuff with self *<!-- -->/
2035 * GDK_THREADS_LEAVE ();
2041 * Return value: %TRUE if the source has been destroyed
2046 g_source_is_destroyed (GSource *source)
2048 return SOURCE_DESTROYED (source);
2051 /* Temporarily remove all this source's file descriptors from the
2052 * poll(), so that if data comes available for one of the file descriptors
2053 * we don't continually spin in the poll()
2055 /* HOLDS: source->context's lock */
2057 block_source (GSource *source)
2061 g_return_if_fail (!SOURCE_BLOCKED (source));
2063 tmp_list = source->poll_fds;
2066 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2067 tmp_list = tmp_list->next;
2071 /* HOLDS: source->context's lock */
2073 unblock_source (GSource *source)
2077 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
2078 g_return_if_fail (!SOURCE_DESTROYED (source));
2080 tmp_list = source->poll_fds;
2083 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2084 tmp_list = tmp_list->next;
2088 /* HOLDS: context's lock */
2090 g_main_dispatch (GMainContext *context)
2092 GMainDispatch *current = get_dispatch ();
2095 for (i = 0; i < context->pending_dispatches->len; i++)
2097 GSource *source = context->pending_dispatches->pdata[i];
2099 context->pending_dispatches->pdata[i] = NULL;
2102 source->flags &= ~G_SOURCE_READY;
2104 if (!SOURCE_DESTROYED (source))
2106 gboolean was_in_call;
2107 gpointer user_data = NULL;
2108 GSourceFunc callback = NULL;
2109 GSourceCallbackFuncs *cb_funcs;
2111 gboolean need_destroy;
2113 gboolean (*dispatch) (GSource *,
2116 GSList current_source_link;
2118 dispatch = source->source_funcs->dispatch;
2119 cb_funcs = source->callback_funcs;
2120 cb_data = source->callback_data;
2123 cb_funcs->ref (cb_data);
2125 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2126 block_source (source);
2128 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2129 source->flags |= G_HOOK_FLAG_IN_CALL;
2132 cb_funcs->get (cb_data, source, &callback, &user_data);
2134 UNLOCK_CONTEXT (context);
2137 /* The on-stack allocation of the GSList is unconventional, but
2138 * we know that the lifetime of the link is bounded to this
2139 * function as the link is kept in a thread specific list and
2140 * not manipulated outside of this function and its descendants.
2141 * Avoiding the overhead of a g_slist_alloc() is useful as many
2142 * applications do little more than dispatch events.
2144 * This is a performance hack - do not revert to g_slist_prepend()!
2146 current_source_link.data = source;
2147 current_source_link.next = current->dispatching_sources;
2148 current->dispatching_sources = ¤t_source_link;
2149 need_destroy = ! dispatch (source,
2152 g_assert (current->dispatching_sources == ¤t_source_link);
2153 current->dispatching_sources = current_source_link.next;
2157 cb_funcs->unref (cb_data);
2159 LOCK_CONTEXT (context);
2162 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2164 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2165 !SOURCE_DESTROYED (source))
2166 unblock_source (source);
2168 /* Note: this depends on the fact that we can't switch
2169 * sources from one main context to another
2171 if (need_destroy && !SOURCE_DESTROYED (source))
2173 g_assert (source->context == context);
2174 g_source_destroy_internal (source, context, TRUE);
2178 SOURCE_UNREF (source, context);
2181 g_ptr_array_set_size (context->pending_dispatches, 0);
2184 /* Holds context's lock */
2185 static inline GSource *
2186 next_valid_source (GMainContext *context,
2189 GSource *new_source = source ? source->next : context->source_list;
2193 if (!SOURCE_DESTROYED (new_source))
2195 new_source->ref_count++;
2199 new_source = new_source->next;
2203 SOURCE_UNREF (source, context);
2209 * g_main_context_acquire:
2210 * @context: a #GMainContext
2212 * Tries to become the owner of the specified context.
2213 * If some other thread is the owner of the context,
2214 * returns %FALSE immediately. Ownership is properly
2215 * recursive: the owner can require ownership again
2216 * and will release ownership when g_main_context_release()
2217 * is called as many times as g_main_context_acquire().
2219 * You must be the owner of a context before you
2220 * can call g_main_context_prepare(), g_main_context_query(),
2221 * g_main_context_check(), g_main_context_dispatch().
2223 * Return value: %TRUE if the operation succeeded, and
2224 * this thread is now the owner of @context.
2227 g_main_context_acquire (GMainContext *context)
2229 #ifdef G_THREADS_ENABLED
2230 gboolean result = FALSE;
2231 GThread *self = G_THREAD_SELF;
2233 if (context == NULL)
2234 context = g_main_context_default ();
2236 LOCK_CONTEXT (context);
2238 if (!context->owner)
2240 context->owner = self;
2241 g_assert (context->owner_count == 0);
2244 if (context->owner == self)
2246 context->owner_count++;
2250 UNLOCK_CONTEXT (context);
2253 #else /* !G_THREADS_ENABLED */
2255 #endif /* G_THREADS_ENABLED */
2259 * g_main_context_release:
2260 * @context: a #GMainContext
2262 * Releases ownership of a context previously acquired by this thread
2263 * with g_main_context_acquire(). If the context was acquired multiple
2264 * times, the ownership will be released only when g_main_context_release()
2265 * is called as many times as it was acquired.
2268 g_main_context_release (GMainContext *context)
2270 #ifdef G_THREADS_ENABLED
2271 if (context == NULL)
2272 context = g_main_context_default ();
2274 LOCK_CONTEXT (context);
2276 context->owner_count--;
2277 if (context->owner_count == 0)
2279 context->owner = NULL;
2281 if (context->waiters)
2283 GMainWaiter *waiter = context->waiters->data;
2284 gboolean loop_internal_waiter =
2285 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
2286 context->waiters = g_slist_delete_link (context->waiters,
2288 if (!loop_internal_waiter)
2289 g_mutex_lock (waiter->mutex);
2291 g_cond_signal (waiter->cond);
2293 if (!loop_internal_waiter)
2294 g_mutex_unlock (waiter->mutex);
2298 UNLOCK_CONTEXT (context);
2299 #endif /* G_THREADS_ENABLED */
2303 * g_main_context_wait:
2304 * @context: a #GMainContext
2305 * @cond: a condition variable
2306 * @mutex: a mutex, currently held
2308 * Tries to become the owner of the specified context,
2309 * as with g_main_context_acquire(). But if another thread
2310 * is the owner, atomically drop @mutex and wait on @cond until
2311 * that owner releases ownership or until @cond is signaled, then
2312 * try again (once) to become the owner.
2314 * Return value: %TRUE if the operation succeeded, and
2315 * this thread is now the owner of @context.
2318 g_main_context_wait (GMainContext *context,
2322 #ifdef G_THREADS_ENABLED
2323 gboolean result = FALSE;
2324 GThread *self = G_THREAD_SELF;
2325 gboolean loop_internal_waiter;
2327 if (context == NULL)
2328 context = g_main_context_default ();
2330 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2332 if (!loop_internal_waiter)
2333 LOCK_CONTEXT (context);
2335 if (context->owner && context->owner != self)
2340 waiter.mutex = mutex;
2342 context->waiters = g_slist_append (context->waiters, &waiter);
2344 if (!loop_internal_waiter)
2345 UNLOCK_CONTEXT (context);
2346 g_cond_wait (cond, mutex);
2347 if (!loop_internal_waiter)
2348 LOCK_CONTEXT (context);
2350 context->waiters = g_slist_remove (context->waiters, &waiter);
2353 if (!context->owner)
2355 context->owner = self;
2356 g_assert (context->owner_count == 0);
2359 if (context->owner == self)
2361 context->owner_count++;
2365 if (!loop_internal_waiter)
2366 UNLOCK_CONTEXT (context);
2369 #else /* !G_THREADS_ENABLED */
2371 #endif /* G_THREADS_ENABLED */
2375 * g_main_context_prepare:
2376 * @context: a #GMainContext
2377 * @priority: location to store priority of highest priority
2378 * source already ready.
2380 * Prepares to poll sources within a main loop. The resulting information
2381 * for polling is determined by calling g_main_context_query ().
2383 * Return value: %TRUE if some source is ready to be dispatched
2387 g_main_context_prepare (GMainContext *context,
2392 gint current_priority = G_MAXINT;
2395 if (context == NULL)
2396 context = g_main_context_default ();
2398 LOCK_CONTEXT (context);
2400 context->time_is_current = FALSE;
2402 if (context->in_check_or_prepare)
2404 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2405 "prepare() member.");
2406 UNLOCK_CONTEXT (context);
2410 #ifdef G_THREADS_ENABLED
2411 if (context->poll_waiting)
2413 g_warning("g_main_context_prepare(): main loop already active in another thread");
2414 UNLOCK_CONTEXT (context);
2418 context->poll_waiting = TRUE;
2419 #endif /* G_THREADS_ENABLED */
2422 /* If recursing, finish up current dispatch, before starting over */
2423 if (context->pending_dispatches)
2426 g_main_dispatch (context, ¤t_time);
2428 UNLOCK_CONTEXT (context);
2433 /* If recursing, clear list of pending dispatches */
2435 for (i = 0; i < context->pending_dispatches->len; i++)
2437 if (context->pending_dispatches->pdata[i])
2438 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2440 g_ptr_array_set_size (context->pending_dispatches, 0);
2442 /* Prepare all sources */
2444 context->timeout = -1;
2446 source = next_valid_source (context, NULL);
2449 gint source_timeout = -1;
2451 if ((n_ready > 0) && (source->priority > current_priority))
2453 SOURCE_UNREF (source, context);
2456 if (SOURCE_BLOCKED (source))
2459 if (!(source->flags & G_SOURCE_READY))
2462 gboolean (*prepare) (GSource *source,
2465 prepare = source->source_funcs->prepare;
2466 context->in_check_or_prepare++;
2467 UNLOCK_CONTEXT (context);
2469 result = (*prepare) (source, &source_timeout);
2471 LOCK_CONTEXT (context);
2472 context->in_check_or_prepare--;
2475 source->flags |= G_SOURCE_READY;
2478 if (source->flags & G_SOURCE_READY)
2481 current_priority = source->priority;
2482 context->timeout = 0;
2485 if (source_timeout >= 0)
2487 if (context->timeout < 0)
2488 context->timeout = source_timeout;
2490 context->timeout = MIN (context->timeout, source_timeout);
2494 source = next_valid_source (context, source);
2497 UNLOCK_CONTEXT (context);
2500 *priority = current_priority;
2502 return (n_ready > 0);
2506 * g_main_context_query:
2507 * @context: a #GMainContext
2508 * @max_priority: maximum priority source to check
2509 * @timeout_: location to store timeout to be used in polling
2510 * @fds: location to store #GPollFD records that need to be polled.
2511 * @n_fds: length of @fds.
2513 * Determines information necessary to poll this main loop.
2515 * Return value: the number of records actually stored in @fds,
2516 * or, if more than @n_fds records need to be stored, the number
2517 * of records that need to be stored.
2520 g_main_context_query (GMainContext *context,
2529 LOCK_CONTEXT (context);
2531 pollrec = context->poll_records;
2533 while (pollrec && max_priority >= pollrec->priority)
2535 /* We need to include entries with fd->events == 0 in the array because
2536 * otherwise if the application changes fd->events behind our back and
2537 * makes it non-zero, we'll be out of sync when we check the fds[] array.
2538 * (Changing fd->events after adding an FD wasn't an anticipated use of
2539 * this API, but it occurs in practice.) */
2542 fds[n_poll].fd = pollrec->fd->fd;
2543 /* In direct contradiction to the Unix98 spec, IRIX runs into
2544 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2545 * flags in the events field of the pollfd while it should
2546 * just ignoring them. So we mask them out here.
2548 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2549 fds[n_poll].revents = 0;
2552 pollrec = pollrec->next;
2556 #ifdef G_THREADS_ENABLED
2557 context->poll_changed = FALSE;
2562 *timeout = context->timeout;
2564 context->time_is_current = FALSE;
2567 UNLOCK_CONTEXT (context);
2573 * g_main_context_check:
2574 * @context: a #GMainContext
2575 * @max_priority: the maximum numerical priority of sources to check
2576 * @fds: array of #GPollFD's that was passed to the last call to
2577 * g_main_context_query()
2578 * @n_fds: return value of g_main_context_query()
2580 * Passes the results of polling back to the main loop.
2582 * Return value: %TRUE if some sources are ready to be dispatched.
2585 g_main_context_check (GMainContext *context,
2595 LOCK_CONTEXT (context);
2597 if (context->in_check_or_prepare)
2599 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2600 "prepare() member.");
2601 UNLOCK_CONTEXT (context);
2605 #ifdef G_THREADS_ENABLED
2606 if (!context->poll_waiting)
2610 read (context->wake_up_pipe[0], &a, 1);
2614 context->poll_waiting = FALSE;
2616 /* If the set of poll file descriptors changed, bail out
2617 * and let the main loop rerun
2619 if (context->poll_changed)
2621 UNLOCK_CONTEXT (context);
2624 #endif /* G_THREADS_ENABLED */
2626 pollrec = context->poll_records;
2630 if (pollrec->fd->events)
2631 pollrec->fd->revents = fds[i].revents;
2633 pollrec = pollrec->next;
2637 source = next_valid_source (context, NULL);
2640 if ((n_ready > 0) && (source->priority > max_priority))
2642 SOURCE_UNREF (source, context);
2645 if (SOURCE_BLOCKED (source))
2648 if (!(source->flags & G_SOURCE_READY))
2651 gboolean (*check) (GSource *source);
2653 check = source->source_funcs->check;
2655 context->in_check_or_prepare++;
2656 UNLOCK_CONTEXT (context);
2658 result = (*check) (source);
2660 LOCK_CONTEXT (context);
2661 context->in_check_or_prepare--;
2664 source->flags |= G_SOURCE_READY;
2667 if (source->flags & G_SOURCE_READY)
2669 source->ref_count++;
2670 g_ptr_array_add (context->pending_dispatches, source);
2674 /* never dispatch sources with less priority than the first
2675 * one we choose to dispatch
2677 max_priority = source->priority;
2681 source = next_valid_source (context, source);
2684 UNLOCK_CONTEXT (context);
2690 * g_main_context_dispatch:
2691 * @context: a #GMainContext
2693 * Dispatches all pending sources.
2696 g_main_context_dispatch (GMainContext *context)
2698 LOCK_CONTEXT (context);
2700 if (context->pending_dispatches->len > 0)
2702 g_main_dispatch (context);
2705 UNLOCK_CONTEXT (context);
2708 /* HOLDS context lock */
2710 g_main_context_iterate (GMainContext *context,
2717 gboolean some_ready;
2718 gint nfds, allocated_nfds;
2719 GPollFD *fds = NULL;
2721 UNLOCK_CONTEXT (context);
2723 #ifdef G_THREADS_ENABLED
2724 if (!g_main_context_acquire (context))
2726 gboolean got_ownership;
2728 LOCK_CONTEXT (context);
2730 g_return_val_if_fail (g_thread_supported (), FALSE);
2736 context->cond = g_cond_new ();
2738 got_ownership = g_main_context_wait (context,
2740 g_static_mutex_get_mutex (&context->mutex));
2746 LOCK_CONTEXT (context);
2747 #endif /* G_THREADS_ENABLED */
2749 if (!context->cached_poll_array)
2751 context->cached_poll_array_size = context->n_poll_records;
2752 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2755 allocated_nfds = context->cached_poll_array_size;
2756 fds = context->cached_poll_array;
2758 UNLOCK_CONTEXT (context);
2760 g_main_context_prepare (context, &max_priority);
2762 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
2763 allocated_nfds)) > allocated_nfds)
2765 LOCK_CONTEXT (context);
2767 context->cached_poll_array_size = allocated_nfds = nfds;
2768 context->cached_poll_array = fds = g_new (GPollFD, nfds);
2769 UNLOCK_CONTEXT (context);
2775 g_main_context_poll (context, timeout, max_priority, fds, nfds);
2777 some_ready = g_main_context_check (context, max_priority, fds, nfds);
2780 g_main_context_dispatch (context);
2782 #ifdef G_THREADS_ENABLED
2783 g_main_context_release (context);
2784 #endif /* G_THREADS_ENABLED */
2786 LOCK_CONTEXT (context);
2792 * g_main_context_pending:
2793 * @context: a #GMainContext (if %NULL, the default context will be used)
2795 * Checks if any sources have pending events for the given context.
2797 * Return value: %TRUE if events are pending.
2800 g_main_context_pending (GMainContext *context)
2805 context = g_main_context_default();
2807 LOCK_CONTEXT (context);
2808 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
2809 UNLOCK_CONTEXT (context);
2815 * g_main_context_iteration:
2816 * @context: a #GMainContext (if %NULL, the default context will be used)
2817 * @may_block: whether the call may block.
2819 * Runs a single iteration for the given main loop. This involves
2820 * checking to see if any event sources are ready to be processed,
2821 * then if no events sources are ready and @may_block is %TRUE, waiting
2822 * for a source to become ready, then dispatching the highest priority
2823 * events sources that are ready. Otherwise, if @may_block is %FALSE
2824 * sources are not waited to become ready, only those highest priority
2825 * events sources will be dispatched (if any), that are ready at this
2826 * given moment without further waiting.
2828 * Note that even when @may_block is %TRUE, it is still possible for
2829 * g_main_context_iteration() to return %FALSE, since the the wait may
2830 * be interrupted for other reasons than an event source becoming ready.
2832 * Return value: %TRUE if events were dispatched.
2835 g_main_context_iteration (GMainContext *context, gboolean may_block)
2840 context = g_main_context_default();
2842 LOCK_CONTEXT (context);
2843 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
2844 UNLOCK_CONTEXT (context);
2851 * @context: a #GMainContext (if %NULL, the default context will be used).
2852 * @is_running: set to %TRUE to indicate that the loop is running. This
2853 * is not very important since calling g_main_loop_run() will set this to
2856 * Creates a new #GMainLoop structure.
2858 * Return value: a new #GMainLoop.
2861 g_main_loop_new (GMainContext *context,
2862 gboolean is_running)
2867 context = g_main_context_default();
2869 g_main_context_ref (context);
2871 loop = g_new0 (GMainLoop, 1);
2872 loop->context = context;
2873 loop->is_running = is_running != FALSE;
2874 loop->ref_count = 1;
2881 * @loop: a #GMainLoop
2883 * Increases the reference count on a #GMainLoop object by one.
2885 * Return value: @loop
2888 g_main_loop_ref (GMainLoop *loop)
2890 g_return_val_if_fail (loop != NULL, NULL);
2891 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2893 g_atomic_int_inc (&loop->ref_count);
2899 * g_main_loop_unref:
2900 * @loop: a #GMainLoop
2902 * Decreases the reference count on a #GMainLoop object by one. If
2903 * the result is zero, free the loop and free all associated memory.
2906 g_main_loop_unref (GMainLoop *loop)
2908 g_return_if_fail (loop != NULL);
2909 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2911 if (!g_atomic_int_dec_and_test (&loop->ref_count))
2914 g_main_context_unref (loop->context);
2920 * @loop: a #GMainLoop
2922 * Runs a main loop until g_main_loop_quit() is called on the loop.
2923 * If this is called for the thread of the loop's #GMainContext,
2924 * it will process events from the loop, otherwise it will
2928 g_main_loop_run (GMainLoop *loop)
2930 GThread *self = G_THREAD_SELF;
2932 g_return_if_fail (loop != NULL);
2933 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2935 #ifdef G_THREADS_ENABLED
2936 if (!g_main_context_acquire (loop->context))
2938 gboolean got_ownership = FALSE;
2940 /* Another thread owns this context */
2941 if (!g_thread_supported ())
2943 g_warning ("g_main_loop_run() was called from second thread but "
2944 "g_thread_init() was never called.");
2948 LOCK_CONTEXT (loop->context);
2950 g_atomic_int_inc (&loop->ref_count);
2952 if (!loop->is_running)
2953 loop->is_running = TRUE;
2955 if (!loop->context->cond)
2956 loop->context->cond = g_cond_new ();
2958 while (loop->is_running && !got_ownership)
2959 got_ownership = g_main_context_wait (loop->context,
2960 loop->context->cond,
2961 g_static_mutex_get_mutex (&loop->context->mutex));
2963 if (!loop->is_running)
2965 UNLOCK_CONTEXT (loop->context);
2967 g_main_context_release (loop->context);
2968 g_main_loop_unref (loop);
2972 g_assert (got_ownership);
2975 LOCK_CONTEXT (loop->context);
2976 #endif /* G_THREADS_ENABLED */
2978 if (loop->context->in_check_or_prepare)
2980 g_warning ("g_main_loop_run(): called recursively from within a source's "
2981 "check() or prepare() member, iteration not possible.");
2985 g_atomic_int_inc (&loop->ref_count);
2986 loop->is_running = TRUE;
2987 while (loop->is_running)
2988 g_main_context_iterate (loop->context, TRUE, TRUE, self);
2990 UNLOCK_CONTEXT (loop->context);
2992 #ifdef G_THREADS_ENABLED
2993 g_main_context_release (loop->context);
2994 #endif /* G_THREADS_ENABLED */
2996 g_main_loop_unref (loop);
3001 * @loop: a #GMainLoop
3003 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3004 * for the loop will return.
3006 * Note that sources that have already been dispatched when
3007 * g_main_loop_quit() is called will still be executed.
3010 g_main_loop_quit (GMainLoop *loop)
3012 g_return_if_fail (loop != NULL);
3013 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3015 LOCK_CONTEXT (loop->context);
3016 loop->is_running = FALSE;
3017 g_main_context_wakeup_unlocked (loop->context);
3019 #ifdef G_THREADS_ENABLED
3020 if (loop->context->cond)
3021 g_cond_broadcast (loop->context->cond);
3022 #endif /* G_THREADS_ENABLED */
3024 UNLOCK_CONTEXT (loop->context);
3028 * g_main_loop_is_running:
3029 * @loop: a #GMainLoop.
3031 * Checks to see if the main loop is currently being run via g_main_loop_run().
3033 * Return value: %TRUE if the mainloop is currently being run.
3036 g_main_loop_is_running (GMainLoop *loop)
3038 g_return_val_if_fail (loop != NULL, FALSE);
3039 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3041 return loop->is_running;
3045 * g_main_loop_get_context:
3046 * @loop: a #GMainLoop.
3048 * Returns the #GMainContext of @loop.
3050 * Return value: the #GMainContext of @loop
3053 g_main_loop_get_context (GMainLoop *loop)
3055 g_return_val_if_fail (loop != NULL, NULL);
3056 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3058 return loop->context;
3061 /* HOLDS: context's lock */
3063 g_main_context_poll (GMainContext *context,
3069 #ifdef G_MAIN_POLL_DEBUG
3075 GPollFunc poll_func;
3077 if (n_fds || timeout != 0)
3079 #ifdef G_MAIN_POLL_DEBUG
3080 if (_g_main_poll_debug)
3082 g_print ("polling context=%p n=%d timeout=%d\n",
3083 context, n_fds, timeout);
3084 poll_timer = g_timer_new ();
3088 LOCK_CONTEXT (context);
3090 poll_func = context->poll_func;
3092 UNLOCK_CONTEXT (context);
3093 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3096 g_warning ("poll(2) failed due to: %s.",
3097 g_strerror (errno));
3099 /* If g_poll () returns -1, it has already called g_warning() */
3103 #ifdef G_MAIN_POLL_DEBUG
3104 if (_g_main_poll_debug)
3106 LOCK_CONTEXT (context);
3108 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3111 g_timer_elapsed (poll_timer, NULL));
3112 g_timer_destroy (poll_timer);
3113 pollrec = context->poll_records;
3115 while (pollrec != NULL)
3120 if (fds[i].fd == pollrec->fd->fd &&
3121 pollrec->fd->events &&
3124 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3125 if (fds[i].revents & G_IO_IN)
3127 if (fds[i].revents & G_IO_OUT)
3129 if (fds[i].revents & G_IO_PRI)
3131 if (fds[i].revents & G_IO_ERR)
3133 if (fds[i].revents & G_IO_HUP)
3135 if (fds[i].revents & G_IO_NVAL)
3141 pollrec = pollrec->next;
3145 UNLOCK_CONTEXT (context);
3148 } /* if (n_fds || timeout != 0) */
3152 * g_main_context_add_poll:
3153 * @context: a #GMainContext (or %NULL for the default context)
3154 * @fd: a #GPollFD structure holding information about a file
3155 * descriptor to watch.
3156 * @priority: the priority for this file descriptor which should be
3157 * the same as the priority used for g_source_attach() to ensure that the
3158 * file descriptor is polled whenever the results may be needed.
3160 * Adds a file descriptor to the set of file descriptors polled for
3161 * this context. This will very seldomly be used directly. Instead
3162 * a typical event source will use g_source_add_poll() instead.
3165 g_main_context_add_poll (GMainContext *context,
3170 context = g_main_context_default ();
3172 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3173 g_return_if_fail (fd);
3175 LOCK_CONTEXT (context);
3176 g_main_context_add_poll_unlocked (context, priority, fd);
3177 UNLOCK_CONTEXT (context);
3180 /* HOLDS: main_loop_lock */
3182 g_main_context_add_poll_unlocked (GMainContext *context,
3186 GPollRec *lastrec, *pollrec;
3187 GPollRec *newrec = g_slice_new (GPollRec);
3189 /* This file descriptor may be checked before we ever poll */
3192 newrec->priority = priority;
3195 pollrec = context->poll_records;
3196 while (pollrec && priority >= pollrec->priority)
3199 pollrec = pollrec->next;
3203 lastrec->next = newrec;
3205 context->poll_records = newrec;
3207 newrec->next = pollrec;
3209 context->n_poll_records++;
3211 #ifdef G_THREADS_ENABLED
3212 context->poll_changed = TRUE;
3214 /* Now wake up the main loop if it is waiting in the poll() */
3215 g_main_context_wakeup_unlocked (context);
3220 * g_main_context_remove_poll:
3221 * @context:a #GMainContext
3222 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3224 * Removes file descriptor from the set of file descriptors to be
3225 * polled for a particular context.
3228 g_main_context_remove_poll (GMainContext *context,
3232 context = g_main_context_default ();
3234 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3235 g_return_if_fail (fd);
3237 LOCK_CONTEXT (context);
3238 g_main_context_remove_poll_unlocked (context, fd);
3239 UNLOCK_CONTEXT (context);
3243 g_main_context_remove_poll_unlocked (GMainContext *context,
3246 GPollRec *pollrec, *lastrec;
3249 pollrec = context->poll_records;
3253 if (pollrec->fd == fd)
3255 if (lastrec != NULL)
3256 lastrec->next = pollrec->next;
3258 context->poll_records = pollrec->next;
3260 g_slice_free (GPollRec, pollrec);
3262 context->n_poll_records--;
3266 pollrec = pollrec->next;
3269 #ifdef G_THREADS_ENABLED
3270 context->poll_changed = TRUE;
3272 /* Now wake up the main loop if it is waiting in the poll() */
3273 g_main_context_wakeup_unlocked (context);
3278 * g_source_get_current_time:
3279 * @source: a #GSource
3280 * @timeval: #GTimeVal structure in which to store current time.
3282 * Gets the "current time" to be used when checking
3283 * this source. The advantage of calling this function over
3284 * calling g_get_current_time() directly is that when
3285 * checking multiple sources, GLib can cache a single value
3286 * instead of having to repeatedly get the system time.
3289 g_source_get_current_time (GSource *source,
3292 GMainContext *context;
3294 g_return_if_fail (source->context != NULL);
3296 context = source->context;
3298 LOCK_CONTEXT (context);
3300 if (!context->time_is_current)
3302 g_get_current_time (&context->current_time);
3303 context->time_is_current = TRUE;
3306 *timeval = context->current_time;
3308 UNLOCK_CONTEXT (context);
3312 * g_main_context_set_poll_func:
3313 * @context: a #GMainContext
3314 * @func: the function to call to poll all file descriptors
3316 * Sets the function to use to handle polling of file descriptors. It
3317 * will be used instead of the poll() system call
3318 * (or GLib's replacement function, which is used where
3319 * poll() isn't available).
3321 * This function could possibly be used to integrate the GLib event
3322 * loop with an external event loop.
3325 g_main_context_set_poll_func (GMainContext *context,
3329 context = g_main_context_default ();
3331 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3333 LOCK_CONTEXT (context);
3336 context->poll_func = func;
3338 context->poll_func = g_poll;
3340 UNLOCK_CONTEXT (context);
3344 * g_main_context_get_poll_func:
3345 * @context: a #GMainContext
3347 * Gets the poll function set by g_main_context_set_poll_func().
3349 * Return value: the poll function
3352 g_main_context_get_poll_func (GMainContext *context)
3357 context = g_main_context_default ();
3359 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3361 LOCK_CONTEXT (context);
3362 result = context->poll_func;
3363 UNLOCK_CONTEXT (context);
3368 /* HOLDS: context's lock */
3369 /* Wake the main loop up from a poll() */
3371 g_main_context_wakeup_unlocked (GMainContext *context)
3373 #ifdef G_THREADS_ENABLED
3374 if (g_thread_supported() && context->poll_waiting)
3376 context->poll_waiting = FALSE;
3378 write (context->wake_up_pipe[1], "A", 1);
3380 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
3387 * g_main_context_wakeup:
3388 * @context: a #GMainContext
3390 * If @context is currently waiting in a poll(), interrupt
3391 * the poll(), and continue the iteration process.
3394 g_main_context_wakeup (GMainContext *context)
3397 context = g_main_context_default ();
3399 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3401 LOCK_CONTEXT (context);
3402 g_main_context_wakeup_unlocked (context);
3403 UNLOCK_CONTEXT (context);
3407 * g_main_context_is_owner:
3408 * @context: a #GMainContext
3410 * Determines whether this thread holds the (recursive)
3411 * ownership of this #GMaincontext. This is useful to
3412 * know before waiting on another thread that may be
3413 * blocking to get ownership of @context.
3415 * Returns: %TRUE if current thread is owner of @context.
3420 g_main_context_is_owner (GMainContext *context)
3425 context = g_main_context_default ();
3427 #ifdef G_THREADS_ENABLED
3428 LOCK_CONTEXT (context);
3429 is_owner = context->owner == G_THREAD_SELF;
3430 UNLOCK_CONTEXT (context);
3441 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3442 GTimeVal *current_time)
3444 guint seconds = timeout_source->interval / 1000;
3445 guint msecs = timeout_source->interval - seconds * 1000;
3447 timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
3448 timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
3449 if (timeout_source->expiration.tv_usec >= 1000000)
3451 timeout_source->expiration.tv_usec -= 1000000;
3452 timeout_source->expiration.tv_sec++;
3454 if (timer_perturb==-1)
3457 * we want a per machine/session unique 'random' value; try the dbus
3458 * address first, that has a UUID in it. If there is no dbus, use the
3459 * hostname for hashing.
3461 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3462 if (!session_bus_address)
3463 session_bus_address = g_getenv ("HOSTNAME");
3464 if (session_bus_address)
3465 timer_perturb = ABS ((gint) g_str_hash (session_bus_address));
3469 if (timeout_source->granularity)
3472 gint gran; /* in usecs */
3475 gran = timeout_source->granularity * 1000;
3476 perturb = timer_perturb % gran;
3478 * We want to give each machine a per machine pertubation;
3479 * shift time back first, and forward later after the rounding
3482 timeout_source->expiration.tv_usec -= perturb;
3483 if (timeout_source->expiration.tv_usec < 0)
3485 timeout_source->expiration.tv_usec += 1000000;
3486 timeout_source->expiration.tv_sec--;
3489 remainder = timeout_source->expiration.tv_usec % gran;
3490 if (remainder >= gran/4) /* round up */
3491 timeout_source->expiration.tv_usec += gran;
3492 timeout_source->expiration.tv_usec -= remainder;
3494 timeout_source->expiration.tv_usec += perturb;
3496 /* the rounding may have overflown tv_usec */
3497 while (timeout_source->expiration.tv_usec > 1000000)
3499 timeout_source->expiration.tv_usec -= 1000000;
3500 timeout_source->expiration.tv_sec++;
3506 g_timeout_prepare (GSource *source,
3511 GTimeVal current_time;
3513 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3515 g_source_get_current_time (source, ¤t_time);
3517 sec = timeout_source->expiration.tv_sec - current_time.tv_sec;
3518 msec = (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000;
3520 /* We do the following in a rather convoluted fashion to deal with
3521 * the fact that we don't have an integral type big enough to hold
3522 * the difference of two timevals in millseconds.
3524 if (sec < 0 || (sec == 0 && msec < 0))
3528 glong interval_sec = timeout_source->interval / 1000;
3529 glong interval_msec = timeout_source->interval % 1000;
3537 if (sec > interval_sec ||
3538 (sec == interval_sec && msec > interval_msec))
3540 /* The system time has been set backwards, so we
3541 * reset the expiration time to now + timeout_source->interval;
3542 * this at least avoids hanging for long periods of time.
3544 g_timeout_set_expiration (timeout_source, ¤t_time);
3545 msec = MIN (G_MAXINT, timeout_source->interval);
3549 msec = MIN (G_MAXINT, (guint)msec + 1000 * (guint)sec);
3553 *timeout = (gint)msec;
3559 g_timeout_check (GSource *source)
3561 GTimeVal current_time;
3562 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3564 g_source_get_current_time (source, ¤t_time);
3566 return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
3567 ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
3568 (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
3572 g_timeout_dispatch (GSource *source,
3573 GSourceFunc callback,
3576 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3580 g_warning ("Timeout source dispatched without callback\n"
3581 "You must call g_source_set_callback().");
3585 if (callback (user_data))
3587 GTimeVal current_time;
3589 g_source_get_current_time (source, ¤t_time);
3590 g_timeout_set_expiration (timeout_source, ¤t_time);
3599 * g_timeout_source_new:
3600 * @interval: the timeout interval in milliseconds.
3602 * Creates a new timeout source.
3604 * The source will not initially be associated with any #GMainContext
3605 * and must be added to one with g_source_attach() before it will be
3608 * Return value: the newly-created timeout source
3611 g_timeout_source_new (guint interval)
3613 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3614 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3615 GTimeVal current_time;
3617 timeout_source->interval = interval;
3619 g_get_current_time (¤t_time);
3620 g_timeout_set_expiration (timeout_source, ¤t_time);
3626 * g_timeout_source_new_seconds:
3627 * @interval: the timeout interval in seconds
3629 * Creates a new timeout source.
3631 * The source will not initially be associated with any #GMainContext
3632 * and must be added to one with g_source_attach() before it will be
3635 * The scheduling granularity/accuracy of this timeout source will be
3638 * Return value: the newly-created timeout source
3643 g_timeout_source_new_seconds (guint interval)
3645 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3646 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3647 GTimeVal current_time;
3649 timeout_source->interval = 1000*interval;
3650 timeout_source->granularity = 1000;
3652 g_get_current_time (¤t_time);
3653 g_timeout_set_expiration (timeout_source, ¤t_time);
3660 * g_timeout_add_full:
3661 * @priority: the priority of the timeout source. Typically this will be in
3662 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3663 * @interval: the time between calls to the function, in milliseconds
3664 * (1/1000ths of a second)
3665 * @function: function to call
3666 * @data: data to pass to @function
3667 * @notify: function to call when the timeout is removed, or %NULL
3669 * Sets a function to be called at regular intervals, with the given
3670 * priority. The function is called repeatedly until it returns
3671 * %FALSE, at which point the timeout is automatically destroyed and
3672 * the function will not be called again. The @notify function is
3673 * called when the timeout is destroyed. The first call to the
3674 * function will be at the end of the first @interval.
3676 * Note that timeout functions may be delayed, due to the processing of other
3677 * event sources. Thus they should not be relied on for precise timing.
3678 * After each call to the timeout function, the time of the next
3679 * timeout is recalculated based on the current time and the given interval
3680 * (it does not try to 'catch up' time lost in delays).
3682 * This internally creates a main loop source using g_timeout_source_new()
3683 * and attaches it to the main loop context using g_source_attach(). You can
3684 * do these steps manually if you need greater control.
3686 * Return value: the ID (greater than 0) of the event source.
3689 g_timeout_add_full (gint priority,
3691 GSourceFunc function,
3693 GDestroyNotify notify)
3698 g_return_val_if_fail (function != NULL, 0);
3700 source = g_timeout_source_new (interval);
3702 if (priority != G_PRIORITY_DEFAULT)
3703 g_source_set_priority (source, priority);
3705 g_source_set_callback (source, function, data, notify);
3706 id = g_source_attach (source, NULL);
3707 g_source_unref (source);
3714 * @interval: the time between calls to the function, in milliseconds
3715 * (1/1000ths of a second)
3716 * @function: function to call
3717 * @data: data to pass to @function
3719 * Sets a function to be called at regular intervals, with the default
3720 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
3721 * until it returns %FALSE, at which point the timeout is automatically
3722 * destroyed and the function will not be called again. The first call
3723 * to the function will be at the end of the first @interval.
3725 * Note that timeout functions may be delayed, due to the processing of other
3726 * event sources. Thus they should not be relied on for precise timing.
3727 * After each call to the timeout function, the time of the next
3728 * timeout is recalculated based on the current time and the given interval
3729 * (it does not try to 'catch up' time lost in delays).
3731 * If you want to have a timer in the "seconds" range and do not care
3732 * about the exact time of the first call of the timer, use the
3733 * g_timeout_add_seconds() function; this function allows for more
3734 * optimizations and more efficient system power usage.
3736 * This internally creates a main loop source using g_timeout_source_new()
3737 * and attaches it to the main loop context using g_source_attach(). You can
3738 * do these steps manually if you need greater control.
3740 * Return value: the ID (greater than 0) of the event source.
3743 g_timeout_add (guint32 interval,
3744 GSourceFunc function,
3747 return g_timeout_add_full (G_PRIORITY_DEFAULT,
3748 interval, function, data, NULL);
3752 * g_timeout_add_seconds_full:
3753 * @priority: the priority of the timeout source. Typically this will be in
3754 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3755 * @interval: the time between calls to the function, in seconds
3756 * @function: function to call
3757 * @data: data to pass to @function
3758 * @notify: function to call when the timeout is removed, or %NULL
3760 * Sets a function to be called at regular intervals, with @priority.
3761 * The function is called repeatedly until it returns %FALSE, at which
3762 * point the timeout is automatically destroyed and the function will
3763 * not be called again.
3765 * Unlike g_timeout_add(), this function operates at whole second granularity.
3766 * The initial starting point of the timer is determined by the implementation
3767 * and the implementation is expected to group multiple timers together so that
3768 * they fire all at the same time.
3769 * To allow this grouping, the @interval to the first timer is rounded
3770 * and can deviate up to one second from the specified interval.
3771 * Subsequent timer iterations will generally run at the specified interval.
3773 * Note that timeout functions may be delayed, due to the processing of other
3774 * event sources. Thus they should not be relied on for precise timing.
3775 * After each call to the timeout function, the time of the next
3776 * timeout is recalculated based on the current time and the given @interval
3778 * If you want timing more precise than whole seconds, use g_timeout_add()
3781 * The grouping of timers to fire at the same time results in a more power
3782 * and CPU efficient behavior so if your timer is in multiples of seconds
3783 * and you don't require the first timer exactly one second from now, the
3784 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
3786 * This internally creates a main loop source using
3787 * g_timeout_source_new_seconds() and attaches it to the main loop context
3788 * using g_source_attach(). You can do these steps manually if you need
3791 * Return value: the ID (greater than 0) of the event source.
3796 g_timeout_add_seconds_full (gint priority,
3798 GSourceFunc function,
3800 GDestroyNotify notify)
3805 g_return_val_if_fail (function != NULL, 0);
3807 source = g_timeout_source_new_seconds (interval);
3809 if (priority != G_PRIORITY_DEFAULT)
3810 g_source_set_priority (source, priority);
3812 g_source_set_callback (source, function, data, notify);
3813 id = g_source_attach (source, NULL);
3814 g_source_unref (source);
3820 * g_timeout_add_seconds:
3821 * @interval: the time between calls to the function, in seconds
3822 * @function: function to call
3823 * @data: data to pass to @function
3825 * Sets a function to be called at regular intervals with the default
3826 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
3827 * it returns %FALSE, at which point the timeout is automatically destroyed
3828 * and the function will not be called again.
3830 * This internally creates a main loop source using
3831 * g_timeout_source_new_seconds() and attaches it to the main loop context
3832 * using g_source_attach(). You can do these steps manually if you need
3833 * greater control. Also see g_timout_add_seconds_full().
3835 * Return value: the ID (greater than 0) of the event source.
3840 g_timeout_add_seconds (guint interval,
3841 GSourceFunc function,
3844 g_return_val_if_fail (function != NULL, 0);
3846 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
3849 /* Child watch functions */
3854 g_child_watch_prepare (GSource *source,
3863 g_child_watch_check (GSource *source)
3865 GChildWatchSource *child_watch_source;
3866 gboolean child_exited;
3868 child_watch_source = (GChildWatchSource *) source;
3870 child_exited = child_watch_source->poll.revents & G_IO_IN;
3877 * Note: We do _not_ check for the special value of STILL_ACTIVE
3878 * since we know that the process has exited and doing so runs into
3879 * problems if the child process "happens to return STILL_ACTIVE(259)"
3880 * as Microsoft's Platform SDK puts it.
3882 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
3884 gchar *emsg = g_win32_error_message (GetLastError ());
3885 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
3888 child_watch_source->child_status = -1;
3891 child_watch_source->child_status = child_status;
3894 return child_exited;
3897 #else /* G_OS_WIN32 */
3900 check_for_child_exited (GSource *source)
3902 GChildWatchSource *child_watch_source;
3905 /* protect against another SIGCHLD in the middle of this call */
3906 count = child_watch_count;
3908 child_watch_source = (GChildWatchSource *) source;
3910 if (child_watch_source->child_exited)
3913 if (child_watch_source->count < count)
3917 if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
3919 child_watch_source->child_status = child_status;
3920 child_watch_source->child_exited = TRUE;
3922 child_watch_source->count = count;
3925 return child_watch_source->child_exited;
3929 g_child_watch_prepare (GSource *source,
3934 return check_for_child_exited (source);
3939 g_child_watch_check (GSource *source)
3941 return check_for_child_exited (source);
3944 #endif /* G_OS_WIN32 */
3947 g_child_watch_dispatch (GSource *source,
3948 GSourceFunc callback,
3951 GChildWatchSource *child_watch_source;
3952 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
3954 child_watch_source = (GChildWatchSource *) source;
3958 g_warning ("Child watch source dispatched without callback\n"
3959 "You must call g_source_set_callback().");
3963 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
3965 /* We never keep a child watch source around as the child is gone */
3972 g_child_watch_signal_handler (int signum)
3974 child_watch_count ++;
3976 if (child_watch_init_state == CHILD_WATCH_INITIALIZED_THREADED)
3978 write (child_watch_wake_up_pipe[1], "B", 1);
3982 /* We count on the signal interrupting the poll in the same thread.
3988 g_child_watch_source_init_single (void)
3990 struct sigaction action;
3992 g_assert (! g_thread_supported());
3993 g_assert (child_watch_init_state == CHILD_WATCH_UNINITIALIZED);
3995 child_watch_init_state = CHILD_WATCH_INITIALIZED_SINGLE;
3997 action.sa_handler = g_child_watch_signal_handler;
3998 sigemptyset (&action.sa_mask);
3999 action.sa_flags = SA_NOCLDSTOP;
4000 sigaction (SIGCHLD, &action, NULL);
4003 G_GNUC_NORETURN static gpointer
4004 child_watch_helper_thread (gpointer data)
4011 read (child_watch_wake_up_pipe[0], b, 20);
4013 /* We were woken up. Wake up all other contexts in all other threads */
4014 G_LOCK (main_context_list);
4015 for (list = main_context_list; list; list = list->next)
4017 GMainContext *context;
4019 context = list->data;
4020 if (g_atomic_int_get (&context->ref_count) > 0)
4021 /* Due to racing conditions we can find ref_count == 0, in
4022 * that case, however, the context is still not destroyed
4023 * and no poll can be active, otherwise the ref_count
4025 g_main_context_wakeup (context);
4027 G_UNLOCK (main_context_list);
4032 g_child_watch_source_init_multi_threaded (void)
4034 GError *error = NULL;
4035 struct sigaction action;
4037 g_assert (g_thread_supported());
4039 if (pipe (child_watch_wake_up_pipe) < 0)
4040 g_error ("Cannot create wake up pipe: %s\n", g_strerror (errno));
4041 fcntl (child_watch_wake_up_pipe[1], F_SETFL, O_NONBLOCK | fcntl (child_watch_wake_up_pipe[1], F_GETFL));
4043 /* We create a helper thread that polls on the wakeup pipe indefinitely */
4044 /* FIXME: Think this through for races */
4045 if (g_thread_create (child_watch_helper_thread, NULL, FALSE, &error) == NULL)
4046 g_error ("Cannot create a thread to monitor child exit status: %s\n", error->message);
4047 child_watch_init_state = CHILD_WATCH_INITIALIZED_THREADED;
4049 action.sa_handler = g_child_watch_signal_handler;
4050 sigemptyset (&action.sa_mask);
4051 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4052 sigaction (SIGCHLD, &action, NULL);
4056 g_child_watch_source_init_promote_single_to_threaded (void)
4058 g_child_watch_source_init_multi_threaded ();
4062 g_child_watch_source_init (void)
4064 if (g_thread_supported())
4066 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
4067 g_child_watch_source_init_multi_threaded ();
4068 else if (child_watch_init_state == CHILD_WATCH_INITIALIZED_SINGLE)
4069 g_child_watch_source_init_promote_single_to_threaded ();
4073 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
4074 g_child_watch_source_init_single ();
4078 #endif /* !G_OS_WIN32 */
4081 * g_child_watch_source_new:
4082 * @pid: process to watch. On POSIX the pid of a child process. On
4083 * Windows a handle for a process (which doesn't have to be a child).
4085 * Creates a new child_watch source.
4087 * The source will not initially be associated with any #GMainContext
4088 * and must be added to one with g_source_attach() before it will be
4091 * Note that child watch sources can only be used in conjunction with
4092 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4095 * Note that on platforms where #GPid must be explicitly closed
4096 * (see g_spawn_close_pid()) @pid must not be closed while the
4097 * source is still active. Typically, you will want to call
4098 * g_spawn_close_pid() in the callback function for the source.
4100 * Note further that using g_child_watch_source_new() is not
4101 * compatible with calling <literal>waitpid(-1)</literal> in
4102 * the application. Calling waitpid() for individual pids will
4105 * Return value: the newly-created child watch source
4110 g_child_watch_source_new (GPid pid)
4112 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4113 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4116 child_watch_source->poll.fd = (gintptr) pid;
4117 child_watch_source->poll.events = G_IO_IN;
4119 g_source_add_poll (source, &child_watch_source->poll);
4120 #else /* G_OS_WIN32 */
4121 g_child_watch_source_init ();
4122 #endif /* G_OS_WIN32 */
4124 child_watch_source->pid = pid;
4130 * g_child_watch_add_full:
4131 * @priority: the priority of the idle source. Typically this will be in the
4132 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4133 * @pid: process to watch. On POSIX the pid of a child process. On
4134 * Windows a handle for a process (which doesn't have to be a child).
4135 * @function: function to call
4136 * @data: data to pass to @function
4137 * @notify: function to call when the idle is removed, or %NULL
4139 * Sets a function to be called when the child indicated by @pid
4140 * exits, at the priority @priority.
4142 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4143 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4144 * the spawn function for the child watching to work.
4146 * Note that on platforms where #GPid must be explicitly closed
4147 * (see g_spawn_close_pid()) @pid must not be closed while the
4148 * source is still active. Typically, you will want to call
4149 * g_spawn_close_pid() in the callback function for the source.
4151 * GLib supports only a single callback per process id.
4153 * This internally creates a main loop source using
4154 * g_child_watch_source_new() and attaches it to the main loop context
4155 * using g_source_attach(). You can do these steps manually if you
4156 * need greater control.
4158 * Return value: the ID (greater than 0) of the event source.
4163 g_child_watch_add_full (gint priority,
4165 GChildWatchFunc function,
4167 GDestroyNotify notify)
4172 g_return_val_if_fail (function != NULL, 0);
4174 source = g_child_watch_source_new (pid);
4176 if (priority != G_PRIORITY_DEFAULT)
4177 g_source_set_priority (source, priority);
4179 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4180 id = g_source_attach (source, NULL);
4181 g_source_unref (source);
4187 * g_child_watch_add:
4188 * @pid: process id to watch. On POSIX the pid of a child process. On
4189 * Windows a handle for a process (which doesn't have to be a child).
4190 * @function: function to call
4191 * @data: data to pass to @function
4193 * Sets a function to be called when the child indicated by @pid
4194 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4196 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4197 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4198 * the spawn function for the child watching to work.
4200 * Note that on platforms where #GPid must be explicitly closed
4201 * (see g_spawn_close_pid()) @pid must not be closed while the
4202 * source is still active. Typically, you will want to call
4203 * g_spawn_close_pid() in the callback function for the source.
4205 * GLib supports only a single callback per process id.
4207 * This internally creates a main loop source using
4208 * g_child_watch_source_new() and attaches it to the main loop context
4209 * using g_source_attach(). You can do these steps manually if you
4210 * need greater control.
4212 * Return value: the ID (greater than 0) of the event source.
4217 g_child_watch_add (GPid pid,
4218 GChildWatchFunc function,
4221 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4225 /* Idle functions */
4228 g_idle_prepare (GSource *source,
4237 g_idle_check (GSource *source)
4243 g_idle_dispatch (GSource *source,
4244 GSourceFunc callback,
4249 g_warning ("Idle source dispatched without callback\n"
4250 "You must call g_source_set_callback().");
4254 return callback (user_data);
4258 * g_idle_source_new:
4260 * Creates a new idle source.
4262 * The source will not initially be associated with any #GMainContext
4263 * and must be added to one with g_source_attach() before it will be
4264 * executed. Note that the default priority for idle sources is
4265 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4266 * have a default priority of %G_PRIORITY_DEFAULT.
4268 * Return value: the newly-created idle source
4271 g_idle_source_new (void)
4275 source = g_source_new (&g_idle_funcs, sizeof (GSource));
4276 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4283 * @priority: the priority of the idle source. Typically this will be in the
4284 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4285 * @function: function to call
4286 * @data: data to pass to @function
4287 * @notify: function to call when the idle is removed, or %NULL
4289 * Adds a function to be called whenever there are no higher priority
4290 * events pending. If the function returns %FALSE it is automatically
4291 * removed from the list of event sources and will not be called again.
4293 * This internally creates a main loop source using g_idle_source_new()
4294 * and attaches it to the main loop context using g_source_attach().
4295 * You can do these steps manually if you need greater control.
4297 * Return value: the ID (greater than 0) of the event source.
4300 g_idle_add_full (gint priority,
4301 GSourceFunc function,
4303 GDestroyNotify notify)
4308 g_return_val_if_fail (function != NULL, 0);
4310 source = g_idle_source_new ();
4312 if (priority != G_PRIORITY_DEFAULT_IDLE)
4313 g_source_set_priority (source, priority);
4315 g_source_set_callback (source, function, data, notify);
4316 id = g_source_attach (source, NULL);
4317 g_source_unref (source);
4324 * @function: function to call
4325 * @data: data to pass to @function.
4327 * Adds a function to be called whenever there are no higher priority
4328 * events pending to the default main loop. The function is given the
4329 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4330 * returns %FALSE it is automatically removed from the list of event
4331 * sources and will not be called again.
4333 * This internally creates a main loop source using g_idle_source_new()
4334 * and attaches it to the main loop context using g_source_attach().
4335 * You can do these steps manually if you need greater control.
4337 * Return value: the ID (greater than 0) of the event source.
4340 g_idle_add (GSourceFunc function,
4343 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4347 * g_idle_remove_by_data:
4348 * @data: the data for the idle source's callback.
4350 * Removes the idle function with the given data.
4352 * Return value: %TRUE if an idle source was found and removed.
4355 g_idle_remove_by_data (gpointer data)
4357 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4361 * g_main_context_invoke:
4362 * @context: a #GMainContext, or %NULL
4363 * @function: function to call
4364 * @data: data to pass to @function
4366 * Invokes a function in such a way that @context is owned during the
4367 * invocation of @function.
4369 * If @context is %NULL then the global default main context — as
4370 * returned by g_main_context_default() — is used.
4372 * If @context is owned by the current thread, @function is called
4373 * directly. Otherwise, if @context is the thread-default main context
4374 * of the current thread and g_main_context_acquire() succeeds, then
4375 * @function is called and g_main_context_release() is called
4378 * In any other case, an idle source is created to call @function and
4379 * that source is attached to @context (presumably to be run in another
4380 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
4381 * priority. If you want a different priority, use
4382 * g_main_context_invoke_full().
4384 * Note that, as with normal idle functions, @function should probably
4385 * return %FALSE. If it returns %TRUE, it will be continuously run in a
4386 * loop (and may prevent this call from returning).
4391 g_main_context_invoke (GMainContext *context,
4392 GSourceFunc function,
4395 g_main_context_invoke_full (context,
4397 function, data, NULL);
4401 * g_main_context_invoke_full:
4402 * @context: a #GMainContext, or %NULL
4403 * @priority: the priority at which to run @function
4404 * @function: function to call
4405 * @data: data to pass to @function
4406 * @notify: a function to call when @data is no longer in use, or %NULL.
4408 * Invokes a function in such a way that @context is owned during the
4409 * invocation of @function.
4411 * This function is the same as g_main_context_invoke() except that it
4412 * lets you specify the priority incase @function ends up being
4413 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
4415 * @notify should not assume that it is called from any particular
4416 * thread or with any particular context acquired.
4421 g_main_context_invoke_full (GMainContext *context,
4423 GSourceFunc function,
4425 GDestroyNotify notify)
4427 g_return_if_fail (function != NULL);
4430 context = g_main_context_default ();
4432 if (g_main_context_is_owner (context))
4434 while (function (data));
4441 GMainContext *thread_default;
4443 thread_default = g_main_context_get_thread_default ();
4445 if (!thread_default)
4446 thread_default = g_main_context_default ();
4448 if (thread_default == context && g_main_context_acquire (context))
4450 while (function (data));
4452 g_main_context_release (context);
4461 source = g_idle_source_new ();
4462 g_source_set_priority (source, priority);
4463 g_source_set_callback (source, function, data, notify);
4464 g_source_attach (source, context);
4465 g_source_unref (source);