1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * gmain.c: Main loop abstraction, timeouts, and idle functions
5 * Copyright 1998 Owen Taylor
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the
19 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 * Boston, MA 02111-1307, USA.
24 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
25 * file for a list of people on the GLib Team. See the ChangeLog
26 * files for a list of changes. These files are distributed with
27 * GLib at ftp://ftp.gtk.org/pub/gtk/.
35 /* for pipe2; need to define it first to avoid
36 * other headers pulling in unistd.h
38 /* The meaning of_GNU_SOURCE that is intended here is present only on
39 * Linux; avoid the possibility that some misguided header in MinGW
40 * looks at it. Ideally we should define _GNU_SOURCE only on platforms
41 * where we know what it means and that is what we want here
42 * (i.e. Linux with glibc). After all, there might be some other POSIX
43 * platform even where _GNU_SOURCE is used for some unrelated change
44 * in semantics that isn't wanted. Sigh.
50 #include "glibconfig.h"
52 /* Uncomment the next line (and the corresponding line in gpoll.c) to
53 * enable debugging printouts if the environment variable
54 * G_MAIN_POLL_DEBUG is set to some value.
56 /* #define G_MAIN_POLL_DEBUG */
59 /* Always enable debugging printout on Windows, as it is more often
62 #define G_MAIN_POLL_DEBUG
66 #include <sys/types.h>
69 #ifdef HAVE_SYS_TIME_H
71 #endif /* HAVE_SYS_TIME_H */
74 #endif /* HAVE_UNISTD_H */
80 #endif /* G_OS_WIN32 */
83 #include <sys/socket.h>
85 #endif /* G_OS_BEOS */
95 #include "giochannel.h"
99 #include "gstrfuncs.h"
100 #include "gtestutils.h"
101 #include "gthreadprivate.h"
107 #ifdef G_MAIN_POLL_DEBUG
113 * @title: The Main Event Loop
114 * @short_description: manages all available sources of events
116 * The main event loop manages all the available sources of events for
117 * GLib and GTK+ applications. These events can come from any number of
118 * different types of sources such as file descriptors (plain files,
119 * pipes or sockets) and timeouts. New types of event sources can also
120 * be added using g_source_attach().
122 * To allow multiple independent sets of sources to be handled in
123 * different threads, each source is associated with a #GMainContext.
124 * A GMainContext can only be running in a single thread, but
125 * sources can be added to it and removed from it from other threads.
127 * Each event source is assigned a priority. The default priority,
128 * #G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
129 * Values greater than 0 denote lower priorities. Events from high priority
130 * sources are always processed before events from lower priority sources.
132 * Idle functions can also be added, and assigned a priority. These will
133 * be run whenever no events with a higher priority are ready to be processed.
135 * The #GMainLoop data type represents a main event loop. A GMainLoop is
136 * created with g_main_loop_new(). After adding the initial event sources,
137 * g_main_loop_run() is called. This continuously checks for new events from
138 * each of the event sources and dispatches them. Finally, the processing of
139 * an event from one of the sources leads to a call to g_main_loop_quit() to
140 * exit the main loop, and g_main_loop_run() returns.
142 * It is possible to create new instances of #GMainLoop recursively.
143 * This is often used in GTK+ applications when showing modal dialog
144 * boxes. Note that event sources are associated with a particular
145 * #GMainContext, and will be checked and dispatched for all main
146 * loops associated with that GMainContext.
148 * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
149 * gtk_main_quit() and gtk_events_pending().
151 * <refsect2><title>Creating new source types</title>
152 * <para>One of the unusual features of the #GMainLoop functionality
153 * is that new types of event source can be created and used in
154 * addition to the builtin type of event source. A new event source
155 * type is used for handling GDK events. A new source type is created
156 * by <firstterm>deriving</firstterm> from the #GSource structure.
157 * The derived type of source is represented by a structure that has
158 * the #GSource structure as a first element, and other elements specific
159 * to the new source type. To create an instance of the new source type,
160 * call g_source_new() passing in the size of the derived structure and
161 * a table of functions. These #GSourceFuncs determine the behavior of
162 * the new source type.</para>
163 * <para>New source types basically interact with the main context
164 * in two ways. Their prepare function in #GSourceFuncs can set a timeout
165 * to determine the maximum amount of time that the main loop will sleep
166 * before checking the source again. In addition, or as well, the source
167 * can add file descriptors to the set that the main context checks using
168 * g_source_add_poll().</para>
170 * <refsect2><title>Customizing the main loop iteration</title>
171 * <para>Single iterations of a #GMainContext can be run with
172 * g_main_context_iteration(). In some cases, more detailed control
173 * of exactly how the details of the main loop work is desired, for
174 * instance, when integrating the #GMainLoop with an external main loop.
175 * In such cases, you can call the component functions of
176 * g_main_context_iteration() directly. These functions are
177 * g_main_context_prepare(), g_main_context_query(),
178 * g_main_context_check() and g_main_context_dispatch().</para>
179 * <para>The operation of these functions can best be seen in terms
180 * of a state diagram, as shown in <xref linkend="mainloop-states"/>.</para>
181 * <figure id="mainloop-states"><title>States of a Main Context</title>
182 * <graphic fileref="mainloop-states.gif" format="GIF"></graphic>
189 typedef struct _GTimeoutSource GTimeoutSource;
190 typedef struct _GChildWatchSource GChildWatchSource;
191 typedef struct _GPollRec GPollRec;
192 typedef struct _GSourceCallback GSourceCallback;
196 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
197 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
200 #ifdef G_THREADS_ENABLED
201 typedef struct _GMainWaiter GMainWaiter;
210 typedef struct _GMainDispatch GMainDispatch;
212 struct _GMainDispatch
215 GSList *dispatching_sources; /* stack of current sources */
218 #ifdef G_MAIN_POLL_DEBUG
219 gboolean _g_main_poll_debug = FALSE;
224 #ifdef G_THREADS_ENABLED
225 /* The following lock is used for both the list of sources
226 * and the list of poll records
237 GPtrArray *pending_dispatches;
238 gint timeout; /* Timeout for current iteration */
241 GSource *source_list;
242 gint in_check_or_prepare;
244 GPollRec *poll_records;
245 guint n_poll_records;
246 GPollFD *cached_poll_array;
247 guint cached_poll_array_size;
249 #ifdef G_THREADS_ENABLED
251 /* this pipe is used to wake up the main loop when a source is added.
253 gint wake_up_pipe[2];
254 #else /* G_OS_WIN32 */
255 HANDLE wake_up_semaphore;
256 #endif /* G_OS_WIN32 */
259 gboolean poll_waiting;
261 /* Flag indicating whether the set of fd's changed during a poll */
262 gboolean poll_changed;
263 #endif /* G_THREADS_ENABLED */
267 GTimeVal current_time;
268 gboolean time_is_current;
271 struct _GSourceCallback
276 GDestroyNotify notify;
281 GMainContext *context;
286 struct _GTimeoutSource
294 struct _GChildWatchSource
301 #else /* G_OS_WIN32 */
303 gboolean child_exited;
304 #endif /* G_OS_WIN32 */
314 #ifdef G_THREADS_ENABLED
315 #define LOCK_CONTEXT(context) g_static_mutex_lock (&context->mutex)
316 #define UNLOCK_CONTEXT(context) g_static_mutex_unlock (&context->mutex)
317 #define G_THREAD_SELF g_thread_self ()
319 #define LOCK_CONTEXT(context) (void)0
320 #define UNLOCK_CONTEXT(context) (void)0
321 #define G_THREAD_SELF NULL
324 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
325 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
326 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
328 #define SOURCE_UNREF(source, context) \
330 if ((source)->ref_count > 1) \
331 (source)->ref_count--; \
333 g_source_unref_internal ((source), (context), TRUE); \
337 /* Forward declarations */
339 static void g_source_unref_internal (GSource *source,
340 GMainContext *context,
342 static void g_source_destroy_internal (GSource *source,
343 GMainContext *context,
345 static void g_main_context_poll (GMainContext *context,
350 static void g_main_context_add_poll_unlocked (GMainContext *context,
353 static void g_main_context_remove_poll_unlocked (GMainContext *context,
355 static void g_main_context_wakeup_unlocked (GMainContext *context);
357 static gboolean g_timeout_prepare (GSource *source,
359 static gboolean g_timeout_check (GSource *source);
360 static gboolean g_timeout_dispatch (GSource *source,
361 GSourceFunc callback,
363 static gboolean g_child_watch_prepare (GSource *source,
365 static gboolean g_child_watch_check (GSource *source);
366 static gboolean g_child_watch_dispatch (GSource *source,
367 GSourceFunc callback,
369 static gboolean g_idle_prepare (GSource *source,
371 static gboolean g_idle_check (GSource *source);
372 static gboolean g_idle_dispatch (GSource *source,
373 GSourceFunc callback,
376 G_LOCK_DEFINE_STATIC (main_loop);
377 static GMainContext *default_main_context;
378 static GSList *main_contexts_without_pipe = NULL;
381 /* Child status monitoring code */
383 CHILD_WATCH_UNINITIALIZED,
384 CHILD_WATCH_INITIALIZED_SINGLE,
385 CHILD_WATCH_INITIALIZED_THREADED
387 static gint child_watch_init_state = CHILD_WATCH_UNINITIALIZED;
388 static gint child_watch_count = 1;
389 static gint child_watch_wake_up_pipe[2] = {0, 0};
390 #endif /* !G_OS_WIN32 */
391 G_LOCK_DEFINE_STATIC (main_context_list);
392 static GSList *main_context_list = NULL;
394 static gint timer_perturb = -1;
396 GSourceFuncs g_timeout_funcs =
404 GSourceFuncs g_child_watch_funcs =
406 g_child_watch_prepare,
408 g_child_watch_dispatch,
412 GSourceFuncs g_idle_funcs =
421 * g_main_context_ref:
422 * @context: a #GMainContext
424 * Increases the reference count on a #GMainContext object by one.
426 * Returns: the @context that was passed in (since 2.6)
429 g_main_context_ref (GMainContext *context)
431 g_return_val_if_fail (context != NULL, NULL);
432 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
434 g_atomic_int_inc (&context->ref_count);
440 poll_rec_list_free (GMainContext *context,
443 g_slice_free_chain (GPollRec, list, next);
447 * g_main_context_unref:
448 * @context: a #GMainContext
450 * Decreases the reference count on a #GMainContext object by one. If
451 * the result is zero, free the context and free all associated memory.
454 g_main_context_unref (GMainContext *context)
457 g_return_if_fail (context != NULL);
458 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
460 if (!g_atomic_int_dec_and_test (&context->ref_count))
463 G_LOCK (main_context_list);
464 main_context_list = g_slist_remove (main_context_list, context);
465 G_UNLOCK (main_context_list);
467 source = context->source_list;
470 GSource *next = source->next;
471 g_source_destroy_internal (source, context, FALSE);
475 #ifdef G_THREADS_ENABLED
476 g_static_mutex_free (&context->mutex);
479 g_ptr_array_free (context->pending_dispatches, TRUE);
480 g_free (context->cached_poll_array);
482 poll_rec_list_free (context, context->poll_records);
484 #ifdef G_THREADS_ENABLED
485 if (g_thread_supported())
488 close (context->wake_up_pipe[0]);
489 close (context->wake_up_pipe[1]);
491 CloseHandle (context->wake_up_semaphore);
495 main_contexts_without_pipe = g_slist_remove (main_contexts_without_pipe,
498 if (context->cond != NULL)
499 g_cond_free (context->cond);
505 #ifdef G_THREADS_ENABLED
507 g_main_context_init_pipe (GMainContext *context)
510 if (context->wake_up_pipe[0] != -1)
514 /* if this fails, we fall through and try pipe */
515 pipe2 (context->wake_up_pipe, O_CLOEXEC);
517 if (context->wake_up_pipe[0] == -1)
519 if (pipe (context->wake_up_pipe) < 0)
520 g_error ("Cannot create pipe main loop wake-up: %s\n",
523 fcntl (context->wake_up_pipe[0], F_SETFD, FD_CLOEXEC);
524 fcntl (context->wake_up_pipe[1], F_SETFD, FD_CLOEXEC);
527 context->wake_up_rec.fd = context->wake_up_pipe[0];
528 context->wake_up_rec.events = G_IO_IN;
530 if (context->wake_up_semaphore != NULL)
532 context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
533 if (context->wake_up_semaphore == NULL)
534 g_error ("Cannot create wake-up semaphore: %s",
535 g_win32_error_message (GetLastError ()));
536 context->wake_up_rec.fd = (gintptr) context->wake_up_semaphore;
537 context->wake_up_rec.events = G_IO_IN;
539 if (_g_main_poll_debug)
540 g_print ("wake-up semaphore: %p\n", context->wake_up_semaphore);
542 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
546 _g_main_thread_init (void)
548 GSList *curr = main_contexts_without_pipe;
551 g_main_context_init_pipe ((GMainContext *)curr->data);
554 g_slist_free (main_contexts_without_pipe);
555 main_contexts_without_pipe = NULL;
557 #endif /* G_THREADS_ENABLED */
560 * g_main_context_new:
562 * Creates a new #GMainContext structure.
564 * Return value: the new #GMainContext
567 g_main_context_new (void)
569 GMainContext *context = g_new0 (GMainContext, 1);
571 #ifdef G_MAIN_POLL_DEBUG
573 static gboolean beenhere = FALSE;
577 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
578 _g_main_poll_debug = TRUE;
584 #ifdef G_THREADS_ENABLED
585 g_static_mutex_init (&context->mutex);
587 context->owner = NULL;
588 context->waiters = NULL;
591 context->wake_up_pipe[0] = -1;
592 context->wake_up_pipe[1] = -1;
594 context->wake_up_semaphore = NULL;
598 context->ref_count = 1;
600 context->next_id = 1;
602 context->source_list = NULL;
604 context->poll_func = g_poll;
606 context->cached_poll_array = NULL;
607 context->cached_poll_array_size = 0;
609 context->pending_dispatches = g_ptr_array_new ();
611 context->time_is_current = FALSE;
613 #ifdef G_THREADS_ENABLED
614 if (g_thread_supported ())
615 g_main_context_init_pipe (context);
617 main_contexts_without_pipe = g_slist_prepend (main_contexts_without_pipe,
621 G_LOCK (main_context_list);
622 main_context_list = g_slist_append (main_context_list, context);
624 #ifdef G_MAIN_POLL_DEBUG
625 if (_g_main_poll_debug)
626 g_print ("created context=%p\n", context);
629 G_UNLOCK (main_context_list);
635 * g_main_context_default:
637 * Returns the global default main context. This is the main context
638 * used for main loop functions when a main loop is not explicitly
639 * specified, and corresponds to the "main" main loop. See also
640 * g_main_context_get_thread_default().
642 * Return value: the global default main context.
645 g_main_context_default (void)
651 if (!default_main_context)
653 default_main_context = g_main_context_new ();
654 #ifdef G_MAIN_POLL_DEBUG
655 if (_g_main_poll_debug)
656 g_print ("default context=%p\n", default_main_context);
660 G_UNLOCK (main_loop);
662 return default_main_context;
665 static GStaticPrivate thread_context_stack = G_STATIC_PRIVATE_INIT;
668 free_context_stack (gpointer data)
670 GQueue *stack = data;
671 GMainContext *context;
673 while (!g_queue_is_empty (stack))
675 context = g_queue_pop_head (stack);
676 g_main_context_release (context);
678 g_main_context_unref (context);
680 g_queue_free (stack);
684 * g_main_context_push_thread_default:
685 * @context: a #GMainContext, or %NULL for the global default context
687 * Acquires @context and sets it as the thread-default context for the
688 * current thread. This will cause certain asynchronous operations
689 * (such as most <link linkend="gio">gio</link>-based I/O) which are
690 * started in this thread to run under @context and deliver their
691 * results to its main loop, rather than running under the global
692 * default context in the main thread. Note that calling this function
693 * changes the context returned by
694 * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
695 * one returned by g_main_context_default(), so it does not affect the
696 * context used by functions like g_idle_add().
698 * Normally you would call this function shortly after creating a new
699 * thread, passing it a #GMainContext which will be run by a
700 * #GMainLoop in that thread, to set a new default context for all
701 * async operations in that thread. (In this case, you don't need to
702 * ever call g_main_context_pop_thread_default().) In some cases
703 * however, you may want to schedule a single operation in a
704 * non-default context, or temporarily use a non-default context in
705 * the main thread. In that case, you can wrap the call to the
706 * asynchronous operation inside a
707 * g_main_context_push_thread_default() /
708 * g_main_context_pop_thread_default() pair, but it is up to you to
709 * ensure that no other asynchronous operations accidentally get
710 * started while the non-default context is active.
712 * Beware that libraries that predate this function may not correctly
713 * handle being used from a thread with a thread-default context. Eg,
714 * see g_file_supports_thread_contexts().
719 g_main_context_push_thread_default (GMainContext *context)
722 gboolean acquired_context;
724 acquired_context = g_main_context_acquire (context);
725 g_return_if_fail (acquired_context);
727 if (context == g_main_context_default ())
730 g_main_context_ref (context);
732 stack = g_static_private_get (&thread_context_stack);
735 stack = g_queue_new ();
736 g_static_private_set (&thread_context_stack, stack,
740 g_queue_push_head (stack, context);
744 * g_main_context_pop_thread_default:
745 * @context: a #GMainContext object, or %NULL
747 * Pops @context off the thread-default context stack (verifying that
748 * it was on the top of the stack).
753 g_main_context_pop_thread_default (GMainContext *context)
757 if (context == g_main_context_default ())
760 stack = g_static_private_get (&thread_context_stack);
762 g_return_if_fail (stack != NULL);
763 g_return_if_fail (g_queue_peek_head (stack) == context);
765 g_queue_pop_head (stack);
767 g_main_context_release (context);
769 g_main_context_unref (context);
773 * g_main_context_get_thread_default:
775 * Gets the thread-default #GMainContext for this thread. Asynchronous
776 * operations that want to be able to be run in contexts other than
777 * the default one should call this method to get a #GMainContext to
778 * add their #GSource<!-- -->s to. (Note that even in single-threaded
779 * programs applications may sometimes want to temporarily push a
780 * non-default context, so it is not safe to assume that this will
781 * always return %NULL if threads are not initialized.)
783 * Returns: the thread-default #GMainContext, or %NULL if the
784 * thread-default context is the global default context.
789 g_main_context_get_thread_default (void)
793 stack = g_static_private_get (&thread_context_stack);
795 return g_queue_peek_head (stack);
800 /* Hooks for adding to the main loop */
804 * @source_funcs: structure containing functions that implement
805 * the sources behavior.
806 * @struct_size: size of the #GSource structure to create.
808 * Creates a new #GSource structure. The size is specified to
809 * allow creating structures derived from #GSource that contain
810 * additional data. The size passed in must be at least
811 * <literal>sizeof (GSource)</literal>.
813 * The source will not initially be associated with any #GMainContext
814 * and must be added to one with g_source_attach() before it will be
817 * Return value: the newly-created #GSource.
820 g_source_new (GSourceFuncs *source_funcs,
825 g_return_val_if_fail (source_funcs != NULL, NULL);
826 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
828 source = (GSource*) g_malloc0 (struct_size);
830 source->source_funcs = source_funcs;
831 source->ref_count = 1;
833 source->priority = G_PRIORITY_DEFAULT;
835 source->flags = G_HOOK_FLAG_ACTIVE;
837 /* NULL/0 initialization for all other fields */
842 /* Holds context's lock
845 g_source_list_add (GSource *source,
846 GMainContext *context)
848 GSource *tmp_source, *last_source;
851 tmp_source = context->source_list;
852 while (tmp_source && tmp_source->priority <= source->priority)
854 last_source = tmp_source;
855 tmp_source = tmp_source->next;
858 source->next = tmp_source;
860 tmp_source->prev = source;
862 source->prev = last_source;
864 last_source->next = source;
866 context->source_list = source;
869 /* Holds context's lock
872 g_source_list_remove (GSource *source,
873 GMainContext *context)
876 source->prev->next = source->next;
878 context->source_list = source->next;
881 source->next->prev = source->prev;
889 * @source: a #GSource
890 * @context: a #GMainContext (if %NULL, the default context will be used)
892 * Adds a #GSource to a @context so that it will be executed within
893 * that context. Remove it by calling g_source_destroy().
895 * Return value: the ID (greater than 0) for the source within the
899 g_source_attach (GSource *source,
900 GMainContext *context)
905 g_return_val_if_fail (source->context == NULL, 0);
906 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
909 context = g_main_context_default ();
911 LOCK_CONTEXT (context);
913 source->context = context;
914 result = source->source_id = context->next_id++;
917 g_source_list_add (source, context);
919 tmp_list = source->poll_fds;
922 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
923 tmp_list = tmp_list->next;
926 #ifdef G_THREADS_ENABLED
927 /* Now wake up the main loop if it is waiting in the poll() */
928 g_main_context_wakeup_unlocked (context);
931 UNLOCK_CONTEXT (context);
937 g_source_destroy_internal (GSource *source,
938 GMainContext *context,
942 LOCK_CONTEXT (context);
944 if (!SOURCE_DESTROYED (source))
947 gpointer old_cb_data;
948 GSourceCallbackFuncs *old_cb_funcs;
950 source->flags &= ~G_HOOK_FLAG_ACTIVE;
952 old_cb_data = source->callback_data;
953 old_cb_funcs = source->callback_funcs;
955 source->callback_data = NULL;
956 source->callback_funcs = NULL;
960 UNLOCK_CONTEXT (context);
961 old_cb_funcs->unref (old_cb_data);
962 LOCK_CONTEXT (context);
965 if (!SOURCE_BLOCKED (source))
967 tmp_list = source->poll_fds;
970 g_main_context_remove_poll_unlocked (context, tmp_list->data);
971 tmp_list = tmp_list->next;
975 g_source_unref_internal (source, context, TRUE);
979 UNLOCK_CONTEXT (context);
984 * @source: a #GSource
986 * Removes a source from its #GMainContext, if any, and mark it as
987 * destroyed. The source cannot be subsequently added to another
991 g_source_destroy (GSource *source)
993 GMainContext *context;
995 g_return_if_fail (source != NULL);
997 context = source->context;
1000 g_source_destroy_internal (source, context, FALSE);
1002 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1007 * @source: a #GSource
1009 * Returns the numeric ID for a particular source. The ID of a source
1010 * is a positive integer which is unique within a particular main loop
1011 * context. The reverse
1012 * mapping from ID to source is done by g_main_context_find_source_by_id().
1014 * Return value: the ID (greater than 0) for the source
1017 g_source_get_id (GSource *source)
1021 g_return_val_if_fail (source != NULL, 0);
1022 g_return_val_if_fail (source->context != NULL, 0);
1024 LOCK_CONTEXT (source->context);
1025 result = source->source_id;
1026 UNLOCK_CONTEXT (source->context);
1032 * g_source_get_context:
1033 * @source: a #GSource
1035 * Gets the #GMainContext with which the source is associated.
1036 * Calling this function on a destroyed source is an error.
1038 * Return value: the #GMainContext with which the source is associated,
1039 * or %NULL if the context has not yet been added
1043 g_source_get_context (GSource *source)
1045 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1047 return source->context;
1051 * g_source_add_poll:
1052 * @source:a #GSource
1053 * @fd: a #GPollFD structure holding information about a file
1054 * descriptor to watch.
1056 * Adds a file descriptor to the set of file descriptors polled for
1057 * this source. This is usually combined with g_source_new() to add an
1058 * event source. The event source's check function will typically test
1059 * the @revents field in the #GPollFD struct and return %TRUE if events need
1063 g_source_add_poll (GSource *source,
1066 GMainContext *context;
1068 g_return_if_fail (source != NULL);
1069 g_return_if_fail (fd != NULL);
1070 g_return_if_fail (!SOURCE_DESTROYED (source));
1072 context = source->context;
1075 LOCK_CONTEXT (context);
1077 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1081 if (!SOURCE_BLOCKED (source))
1082 g_main_context_add_poll_unlocked (context, source->priority, fd);
1083 UNLOCK_CONTEXT (context);
1088 * g_source_remove_poll:
1089 * @source:a #GSource
1090 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1092 * Removes a file descriptor from the set of file descriptors polled for
1096 g_source_remove_poll (GSource *source,
1099 GMainContext *context;
1101 g_return_if_fail (source != NULL);
1102 g_return_if_fail (fd != NULL);
1103 g_return_if_fail (!SOURCE_DESTROYED (source));
1105 context = source->context;
1108 LOCK_CONTEXT (context);
1110 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1114 if (!SOURCE_BLOCKED (source))
1115 g_main_context_remove_poll_unlocked (context, fd);
1116 UNLOCK_CONTEXT (context);
1121 * g_source_set_callback_indirect:
1122 * @source: the source
1123 * @callback_data: pointer to callback data "object"
1124 * @callback_funcs: functions for reference counting @callback_data
1125 * and getting the callback and data
1127 * Sets the callback function storing the data as a refcounted callback
1128 * "object". This is used internally. Note that calling
1129 * g_source_set_callback_indirect() assumes
1130 * an initial reference count on @callback_data, and thus
1131 * @callback_funcs->unref will eventually be called once more
1132 * than @callback_funcs->ref.
1135 g_source_set_callback_indirect (GSource *source,
1136 gpointer callback_data,
1137 GSourceCallbackFuncs *callback_funcs)
1139 GMainContext *context;
1140 gpointer old_cb_data;
1141 GSourceCallbackFuncs *old_cb_funcs;
1143 g_return_if_fail (source != NULL);
1144 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1146 context = source->context;
1149 LOCK_CONTEXT (context);
1151 old_cb_data = source->callback_data;
1152 old_cb_funcs = source->callback_funcs;
1154 source->callback_data = callback_data;
1155 source->callback_funcs = callback_funcs;
1158 UNLOCK_CONTEXT (context);
1161 old_cb_funcs->unref (old_cb_data);
1165 g_source_callback_ref (gpointer cb_data)
1167 GSourceCallback *callback = cb_data;
1169 callback->ref_count++;
1174 g_source_callback_unref (gpointer cb_data)
1176 GSourceCallback *callback = cb_data;
1178 callback->ref_count--;
1179 if (callback->ref_count == 0)
1181 if (callback->notify)
1182 callback->notify (callback->data);
1188 g_source_callback_get (gpointer cb_data,
1193 GSourceCallback *callback = cb_data;
1195 *func = callback->func;
1196 *data = callback->data;
1199 static GSourceCallbackFuncs g_source_callback_funcs = {
1200 g_source_callback_ref,
1201 g_source_callback_unref,
1202 g_source_callback_get,
1206 * g_source_set_callback:
1207 * @source: the source
1208 * @func: a callback function
1209 * @data: the data to pass to callback function
1210 * @notify: a function to call when @data is no longer in use, or %NULL.
1212 * Sets the callback function for a source. The callback for a source is
1213 * called from the source's dispatch function.
1215 * The exact type of @func depends on the type of source; ie. you
1216 * should not count on @func being called with @data as its first
1219 * Typically, you won't use this function. Instead use functions specific
1220 * to the type of source you are using.
1223 g_source_set_callback (GSource *source,
1226 GDestroyNotify notify)
1228 GSourceCallback *new_callback;
1230 g_return_if_fail (source != NULL);
1232 new_callback = g_new (GSourceCallback, 1);
1234 new_callback->ref_count = 1;
1235 new_callback->func = func;
1236 new_callback->data = data;
1237 new_callback->notify = notify;
1239 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1244 * g_source_set_funcs:
1245 * @source: a #GSource
1246 * @funcs: the new #GSourceFuncs
1248 * Sets the source functions (can be used to override
1249 * default implementations) of an unattached source.
1254 g_source_set_funcs (GSource *source,
1255 GSourceFuncs *funcs)
1257 g_return_if_fail (source != NULL);
1258 g_return_if_fail (source->context == NULL);
1259 g_return_if_fail (source->ref_count > 0);
1260 g_return_if_fail (funcs != NULL);
1262 source->source_funcs = funcs;
1266 * g_source_set_priority:
1267 * @source: a #GSource
1268 * @priority: the new priority.
1270 * Sets the priority of a source. While the main loop is being
1271 * run, a source will be dispatched if it is ready to be dispatched and no sources
1272 * at a higher (numerically smaller) priority are ready to be dispatched.
1275 g_source_set_priority (GSource *source,
1279 GMainContext *context;
1281 g_return_if_fail (source != NULL);
1283 context = source->context;
1286 LOCK_CONTEXT (context);
1288 source->priority = priority;
1292 /* Remove the source from the context's source and then
1293 * add it back so it is sorted in the correct plcae
1295 g_source_list_remove (source, source->context);
1296 g_source_list_add (source, source->context);
1298 if (!SOURCE_BLOCKED (source))
1300 tmp_list = source->poll_fds;
1303 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1304 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1306 tmp_list = tmp_list->next;
1310 UNLOCK_CONTEXT (source->context);
1315 * g_source_get_priority:
1316 * @source: a #GSource
1318 * Gets the priority of a source.
1320 * Return value: the priority of the source
1323 g_source_get_priority (GSource *source)
1325 g_return_val_if_fail (source != NULL, 0);
1327 return source->priority;
1331 * g_source_set_can_recurse:
1332 * @source: a #GSource
1333 * @can_recurse: whether recursion is allowed for this source
1335 * Sets whether a source can be called recursively. If @can_recurse is
1336 * %TRUE, then while the source is being dispatched then this source
1337 * will be processed normally. Otherwise, all processing of this
1338 * source is blocked until the dispatch function returns.
1341 g_source_set_can_recurse (GSource *source,
1342 gboolean can_recurse)
1344 GMainContext *context;
1346 g_return_if_fail (source != NULL);
1348 context = source->context;
1351 LOCK_CONTEXT (context);
1354 source->flags |= G_SOURCE_CAN_RECURSE;
1356 source->flags &= ~G_SOURCE_CAN_RECURSE;
1359 UNLOCK_CONTEXT (context);
1363 * g_source_get_can_recurse:
1364 * @source: a #GSource
1366 * Checks whether a source is allowed to be called recursively.
1367 * see g_source_set_can_recurse().
1369 * Return value: whether recursion is allowed.
1372 g_source_get_can_recurse (GSource *source)
1374 g_return_val_if_fail (source != NULL, FALSE);
1376 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1381 * g_source_set_name:
1382 * @source: a #GSource
1383 * @name: debug name for the source
1385 * Sets a name for the source, used in debugging and profiling.
1386 * The name defaults to #NULL.
1388 * The source name should describe in a human-readable way
1389 * what the source does. For example, "X11 event queue"
1390 * or "GTK+ repaint idle handler" or whatever it is.
1392 * It is permitted to call this function multiple times, but is not
1393 * recommended due to the potential performance impact. For example,
1394 * one could change the name in the "check" function of a #GSourceFuncs
1395 * to include details like the event type in the source name.
1400 g_source_set_name (GSource *source,
1403 g_return_if_fail (source != NULL);
1405 /* setting back to NULL is allowed, just because it's
1406 * weird if get_name can return NULL but you can't
1410 g_free (source->name);
1411 source->name = g_strdup (name);
1415 * g_source_get_name:
1416 * @source: a #GSource
1418 * Gets a name for the source, used in debugging and profiling.
1419 * The name may be #NULL if it has never been set with
1420 * g_source_set_name().
1422 * Return value: the name of the source
1425 G_CONST_RETURN char*
1426 g_source_get_name (GSource *source)
1428 g_return_val_if_fail (source != NULL, NULL);
1430 return source->name;
1434 * g_source_set_name_by_id:
1435 * @tag: a #GSource ID
1436 * @name: debug name for the source
1438 * Sets the name of a source using its ID.
1440 * This is a convenience utility to set source names from the return
1441 * value of g_idle_add(), g_timeout_add(), etc.
1446 g_source_set_name_by_id (guint tag,
1451 g_return_if_fail (tag > 0);
1453 source = g_main_context_find_source_by_id (NULL, tag);
1457 g_source_set_name (source, name);
1463 * @source: a #GSource
1465 * Increases the reference count on a source by one.
1467 * Return value: @source
1470 g_source_ref (GSource *source)
1472 GMainContext *context;
1474 g_return_val_if_fail (source != NULL, NULL);
1476 context = source->context;
1479 LOCK_CONTEXT (context);
1481 source->ref_count++;
1484 UNLOCK_CONTEXT (context);
1489 /* g_source_unref() but possible to call within context lock
1492 g_source_unref_internal (GSource *source,
1493 GMainContext *context,
1496 gpointer old_cb_data = NULL;
1497 GSourceCallbackFuncs *old_cb_funcs = NULL;
1499 g_return_if_fail (source != NULL);
1501 if (!have_lock && context)
1502 LOCK_CONTEXT (context);
1504 source->ref_count--;
1505 if (source->ref_count == 0)
1507 old_cb_data = source->callback_data;
1508 old_cb_funcs = source->callback_funcs;
1510 source->callback_data = NULL;
1511 source->callback_funcs = NULL;
1513 if (context && !SOURCE_DESTROYED (source))
1515 g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1516 source->ref_count++;
1519 g_source_list_remove (source, context);
1521 if (source->source_funcs->finalize)
1522 source->source_funcs->finalize (source);
1524 g_free (source->name);
1525 source->name = NULL;
1527 g_slist_free (source->poll_fds);
1528 source->poll_fds = NULL;
1532 if (!have_lock && context)
1533 UNLOCK_CONTEXT (context);
1538 UNLOCK_CONTEXT (context);
1540 old_cb_funcs->unref (old_cb_data);
1543 LOCK_CONTEXT (context);
1549 * @source: a #GSource
1551 * Decreases the reference count of a source by one. If the
1552 * resulting reference count is zero the source and associated
1553 * memory will be destroyed.
1556 g_source_unref (GSource *source)
1558 g_return_if_fail (source != NULL);
1560 g_source_unref_internal (source, source->context, FALSE);
1564 * g_main_context_find_source_by_id:
1565 * @context: a #GMainContext (if %NULL, the default context will be used)
1566 * @source_id: the source ID, as returned by g_source_get_id().
1568 * Finds a #GSource given a pair of context and ID.
1570 * Return value: the #GSource if found, otherwise, %NULL
1573 g_main_context_find_source_by_id (GMainContext *context,
1578 g_return_val_if_fail (source_id > 0, NULL);
1580 if (context == NULL)
1581 context = g_main_context_default ();
1583 LOCK_CONTEXT (context);
1585 source = context->source_list;
1588 if (!SOURCE_DESTROYED (source) &&
1589 source->source_id == source_id)
1591 source = source->next;
1594 UNLOCK_CONTEXT (context);
1600 * g_main_context_find_source_by_funcs_user_data:
1601 * @context: a #GMainContext (if %NULL, the default context will be used).
1602 * @funcs: the @source_funcs passed to g_source_new().
1603 * @user_data: the user data from the callback.
1605 * Finds a source with the given source functions and user data. If
1606 * multiple sources exist with the same source function and user data,
1607 * the first one found will be returned.
1609 * Return value: the source, if one was found, otherwise %NULL
1612 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1613 GSourceFuncs *funcs,
1618 g_return_val_if_fail (funcs != NULL, NULL);
1620 if (context == NULL)
1621 context = g_main_context_default ();
1623 LOCK_CONTEXT (context);
1625 source = context->source_list;
1628 if (!SOURCE_DESTROYED (source) &&
1629 source->source_funcs == funcs &&
1630 source->callback_funcs)
1632 GSourceFunc callback;
1633 gpointer callback_data;
1635 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1637 if (callback_data == user_data)
1640 source = source->next;
1643 UNLOCK_CONTEXT (context);
1649 * g_main_context_find_source_by_user_data:
1650 * @context: a #GMainContext
1651 * @user_data: the user_data for the callback.
1653 * Finds a source with the given user data for the callback. If
1654 * multiple sources exist with the same user data, the first
1655 * one found will be returned.
1657 * Return value: the source, if one was found, otherwise %NULL
1660 g_main_context_find_source_by_user_data (GMainContext *context,
1665 if (context == NULL)
1666 context = g_main_context_default ();
1668 LOCK_CONTEXT (context);
1670 source = context->source_list;
1673 if (!SOURCE_DESTROYED (source) &&
1674 source->callback_funcs)
1676 GSourceFunc callback;
1677 gpointer callback_data = NULL;
1679 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1681 if (callback_data == user_data)
1684 source = source->next;
1687 UNLOCK_CONTEXT (context);
1694 * @tag: the ID of the source to remove.
1696 * Removes the source with the given id from the default main context.
1698 * a #GSource is given by g_source_get_id(), or will be returned by the
1699 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1700 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1701 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1703 * See also g_source_destroy(). You must use g_source_destroy() for sources
1704 * added to a non-default main context.
1706 * Return value: %TRUE if the source was found and removed.
1709 g_source_remove (guint tag)
1713 g_return_val_if_fail (tag > 0, FALSE);
1715 source = g_main_context_find_source_by_id (NULL, tag);
1717 g_source_destroy (source);
1719 return source != NULL;
1723 * g_source_remove_by_user_data:
1724 * @user_data: the user_data for the callback.
1726 * Removes a source from the default main loop context given the user
1727 * data for the callback. If multiple sources exist with the same user
1728 * data, only one will be destroyed.
1730 * Return value: %TRUE if a source was found and removed.
1733 g_source_remove_by_user_data (gpointer user_data)
1737 source = g_main_context_find_source_by_user_data (NULL, user_data);
1740 g_source_destroy (source);
1748 * g_source_remove_by_funcs_user_data:
1749 * @funcs: The @source_funcs passed to g_source_new()
1750 * @user_data: the user data for the callback
1752 * Removes a source from the default main loop context given the
1753 * source functions and user data. If multiple sources exist with the
1754 * same source functions and user data, only one will be destroyed.
1756 * Return value: %TRUE if a source was found and removed.
1759 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1764 g_return_val_if_fail (funcs != NULL, FALSE);
1766 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1769 g_source_destroy (source);
1777 * g_get_current_time:
1778 * @result: #GTimeVal structure in which to store current time.
1780 * Equivalent to the UNIX gettimeofday() function, but portable.
1783 g_get_current_time (GTimeVal *result)
1788 g_return_if_fail (result != NULL);
1790 /*this is required on alpha, there the timeval structs are int's
1791 not longs and a cast only would fail horribly*/
1792 gettimeofday (&r, NULL);
1793 result->tv_sec = r.tv_sec;
1794 result->tv_usec = r.tv_usec;
1799 g_return_if_fail (result != NULL);
1801 GetSystemTimeAsFileTime (&ft);
1802 memmove (&time64, &ft, sizeof (FILETIME));
1804 /* Convert from 100s of nanoseconds since 1601-01-01
1805 * to Unix epoch. Yes, this is Y2038 unsafe.
1807 time64 -= G_GINT64_CONSTANT (116444736000000000);
1810 result->tv_sec = time64 / 1000000;
1811 result->tv_usec = time64 % 1000000;
1818 * Represents a precise time, with seconds and nanoseconds. This is
1819 * similar to POSIX <structname>struct timespec</structname>.
1825 g_main_dispatch_free (gpointer dispatch)
1827 g_slice_free (GMainDispatch, dispatch);
1830 /* Running the main loop */
1832 static GMainDispatch *
1835 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
1836 GMainDispatch *dispatch = g_static_private_get (&depth_private);
1839 dispatch = g_slice_new0 (GMainDispatch);
1840 g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
1849 * Returns the depth of the stack of calls to
1850 * g_main_context_dispatch() on any #GMainContext in the current thread.
1851 * That is, when called from the toplevel, it gives 0. When
1852 * called from within a callback from g_main_context_iteration()
1853 * (or g_main_loop_run(), etc.) it returns 1. When called from within
1854 * a callback to a recursive call to g_main_context_iterate(),
1855 * it returns 2. And so forth.
1857 * This function is useful in a situation like the following:
1858 * Imagine an extremely simple "garbage collected" system.
1861 * static GList *free_list;
1864 * allocate_memory (gsize size)
1866 * gpointer result = g_malloc (size);
1867 * free_list = g_list_prepend (free_list, result);
1872 * free_allocated_memory (void)
1875 * for (l = free_list; l; l = l->next);
1877 * g_list_free (free_list);
1885 * g_main_context_iteration (NULL, TRUE);
1886 * free_allocated_memory();
1890 * This works from an application, however, if you want to do the same
1891 * thing from a library, it gets more difficult, since you no longer
1892 * control the main loop. You might think you can simply use an idle
1893 * function to make the call to free_allocated_memory(), but that
1894 * doesn't work, since the idle function could be called from a
1895 * recursive callback. This can be fixed by using g_main_depth()
1899 * allocate_memory (gsize size)
1901 * FreeListBlock *block = g_new (FreeListBlock, 1);
1902 * block->mem = g_malloc (size);
1903 * block->depth = g_main_depth ();
1904 * free_list = g_list_prepend (free_list, block);
1905 * return block->mem;
1909 * free_allocated_memory (void)
1913 * int depth = g_main_depth ();
1914 * for (l = free_list; l; );
1916 * GList *next = l->next;
1917 * FreeListBlock *block = l->data;
1918 * if (block->depth > depth)
1920 * g_free (block->mem);
1922 * free_list = g_list_delete_link (free_list, l);
1930 * There is a temptation to use g_main_depth() to solve
1931 * problems with reentrancy. For instance, while waiting for data
1932 * to be received from the network in response to a menu item,
1933 * the menu item might be selected again. It might seem that
1934 * one could make the menu item's callback return immediately
1935 * and do nothing if g_main_depth() returns a value greater than 1.
1936 * However, this should be avoided since the user then sees selecting
1937 * the menu item do nothing. Furthermore, you'll find yourself adding
1938 * these checks all over your code, since there are doubtless many,
1939 * many things that the user could do. Instead, you can use the
1940 * following techniques:
1945 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
1946 * the user from interacting with elements while the main
1947 * loop is recursing.
1952 * Avoid main loop recursion in situations where you can't handle
1953 * arbitrary callbacks. Instead, structure your code so that you
1954 * simply return to the main loop and then get called again when
1955 * there is more work to do.
1960 * Return value: The main loop recursion level in the current thread
1965 GMainDispatch *dispatch = get_dispatch ();
1966 return dispatch->depth;
1970 * g_main_current_source:
1972 * Returns the currently firing source for this thread.
1974 * Return value: The currently firing source or %NULL.
1979 g_main_current_source (void)
1981 GMainDispatch *dispatch = get_dispatch ();
1982 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
1986 * g_source_is_destroyed:
1987 * @source: a #GSource
1989 * Returns whether @source has been destroyed.
1991 * This is important when you operate upon your objects
1992 * from within idle handlers, but may have freed the object
1993 * before the dispatch of your idle handler.
1997 * idle_callback (gpointer data)
1999 * SomeWidget *self = data;
2001 * GDK_THREADS_ENTER (<!-- -->);
2002 * /<!-- -->* do stuff with self *<!-- -->/
2003 * self->idle_id = 0;
2004 * GDK_THREADS_LEAVE (<!-- -->);
2010 * some_widget_do_stuff_later (SomeWidget *self)
2012 * self->idle_id = g_idle_add (idle_callback, self);
2016 * some_widget_finalize (GObject *object)
2018 * SomeWidget *self = SOME_WIDGET (object);
2020 * if (self->idle_id)
2021 * g_source_remove (self->idle_id);
2023 * G_OBJECT_CLASS (parent_class)->finalize (object);
2027 * This will fail in a multi-threaded application if the
2028 * widget is destroyed before the idle handler fires due
2029 * to the use after free in the callback. A solution, to
2030 * this particular problem, is to check to if the source
2031 * has already been destroy within the callback.
2035 * idle_callback (gpointer data)
2037 * SomeWidget *self = data;
2039 * GDK_THREADS_ENTER ();
2040 * if (!g_source_is_destroyed (g_main_current_source ()))
2042 * /<!-- -->* do stuff with self *<!-- -->/
2044 * GDK_THREADS_LEAVE ();
2050 * Return value: %TRUE if the source has been destroyed
2055 g_source_is_destroyed (GSource *source)
2057 return SOURCE_DESTROYED (source);
2060 /* Temporarily remove all this source's file descriptors from the
2061 * poll(), so that if data comes available for one of the file descriptors
2062 * we don't continually spin in the poll()
2064 /* HOLDS: source->context's lock */
2066 block_source (GSource *source)
2070 g_return_if_fail (!SOURCE_BLOCKED (source));
2072 tmp_list = source->poll_fds;
2075 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2076 tmp_list = tmp_list->next;
2080 /* HOLDS: source->context's lock */
2082 unblock_source (GSource *source)
2086 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
2087 g_return_if_fail (!SOURCE_DESTROYED (source));
2089 tmp_list = source->poll_fds;
2092 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2093 tmp_list = tmp_list->next;
2097 /* HOLDS: context's lock */
2099 g_main_dispatch (GMainContext *context)
2101 GMainDispatch *current = get_dispatch ();
2104 for (i = 0; i < context->pending_dispatches->len; i++)
2106 GSource *source = context->pending_dispatches->pdata[i];
2108 context->pending_dispatches->pdata[i] = NULL;
2111 source->flags &= ~G_SOURCE_READY;
2113 if (!SOURCE_DESTROYED (source))
2115 gboolean was_in_call;
2116 gpointer user_data = NULL;
2117 GSourceFunc callback = NULL;
2118 GSourceCallbackFuncs *cb_funcs;
2120 gboolean need_destroy;
2122 gboolean (*dispatch) (GSource *,
2125 GSList current_source_link;
2127 dispatch = source->source_funcs->dispatch;
2128 cb_funcs = source->callback_funcs;
2129 cb_data = source->callback_data;
2132 cb_funcs->ref (cb_data);
2134 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2135 block_source (source);
2137 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2138 source->flags |= G_HOOK_FLAG_IN_CALL;
2141 cb_funcs->get (cb_data, source, &callback, &user_data);
2143 UNLOCK_CONTEXT (context);
2146 /* The on-stack allocation of the GSList is unconventional, but
2147 * we know that the lifetime of the link is bounded to this
2148 * function as the link is kept in a thread specific list and
2149 * not manipulated outside of this function and its descendants.
2150 * Avoiding the overhead of a g_slist_alloc() is useful as many
2151 * applications do little more than dispatch events.
2153 * This is a performance hack - do not revert to g_slist_prepend()!
2155 current_source_link.data = source;
2156 current_source_link.next = current->dispatching_sources;
2157 current->dispatching_sources = ¤t_source_link;
2158 need_destroy = ! dispatch (source,
2161 g_assert (current->dispatching_sources == ¤t_source_link);
2162 current->dispatching_sources = current_source_link.next;
2166 cb_funcs->unref (cb_data);
2168 LOCK_CONTEXT (context);
2171 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2173 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2174 !SOURCE_DESTROYED (source))
2175 unblock_source (source);
2177 /* Note: this depends on the fact that we can't switch
2178 * sources from one main context to another
2180 if (need_destroy && !SOURCE_DESTROYED (source))
2182 g_assert (source->context == context);
2183 g_source_destroy_internal (source, context, TRUE);
2187 SOURCE_UNREF (source, context);
2190 g_ptr_array_set_size (context->pending_dispatches, 0);
2193 /* Holds context's lock */
2194 static inline GSource *
2195 next_valid_source (GMainContext *context,
2198 GSource *new_source = source ? source->next : context->source_list;
2202 if (!SOURCE_DESTROYED (new_source))
2204 new_source->ref_count++;
2208 new_source = new_source->next;
2212 SOURCE_UNREF (source, context);
2218 * g_main_context_acquire:
2219 * @context: a #GMainContext
2221 * Tries to become the owner of the specified context.
2222 * If some other thread is the owner of the context,
2223 * returns %FALSE immediately. Ownership is properly
2224 * recursive: the owner can require ownership again
2225 * and will release ownership when g_main_context_release()
2226 * is called as many times as g_main_context_acquire().
2228 * You must be the owner of a context before you
2229 * can call g_main_context_prepare(), g_main_context_query(),
2230 * g_main_context_check(), g_main_context_dispatch().
2232 * Return value: %TRUE if the operation succeeded, and
2233 * this thread is now the owner of @context.
2236 g_main_context_acquire (GMainContext *context)
2238 #ifdef G_THREADS_ENABLED
2239 gboolean result = FALSE;
2240 GThread *self = G_THREAD_SELF;
2242 if (context == NULL)
2243 context = g_main_context_default ();
2245 LOCK_CONTEXT (context);
2247 if (!context->owner)
2249 context->owner = self;
2250 g_assert (context->owner_count == 0);
2253 if (context->owner == self)
2255 context->owner_count++;
2259 UNLOCK_CONTEXT (context);
2262 #else /* !G_THREADS_ENABLED */
2264 #endif /* G_THREADS_ENABLED */
2268 * g_main_context_release:
2269 * @context: a #GMainContext
2271 * Releases ownership of a context previously acquired by this thread
2272 * with g_main_context_acquire(). If the context was acquired multiple
2273 * times, the ownership will be released only when g_main_context_release()
2274 * is called as many times as it was acquired.
2277 g_main_context_release (GMainContext *context)
2279 #ifdef G_THREADS_ENABLED
2280 if (context == NULL)
2281 context = g_main_context_default ();
2283 LOCK_CONTEXT (context);
2285 context->owner_count--;
2286 if (context->owner_count == 0)
2288 context->owner = NULL;
2290 if (context->waiters)
2292 GMainWaiter *waiter = context->waiters->data;
2293 gboolean loop_internal_waiter =
2294 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
2295 context->waiters = g_slist_delete_link (context->waiters,
2297 if (!loop_internal_waiter)
2298 g_mutex_lock (waiter->mutex);
2300 g_cond_signal (waiter->cond);
2302 if (!loop_internal_waiter)
2303 g_mutex_unlock (waiter->mutex);
2307 UNLOCK_CONTEXT (context);
2308 #endif /* G_THREADS_ENABLED */
2312 * g_main_context_wait:
2313 * @context: a #GMainContext
2314 * @cond: a condition variable
2315 * @mutex: a mutex, currently held
2317 * Tries to become the owner of the specified context,
2318 * as with g_main_context_acquire(). But if another thread
2319 * is the owner, atomically drop @mutex and wait on @cond until
2320 * that owner releases ownership or until @cond is signaled, then
2321 * try again (once) to become the owner.
2323 * Return value: %TRUE if the operation succeeded, and
2324 * this thread is now the owner of @context.
2327 g_main_context_wait (GMainContext *context,
2331 #ifdef G_THREADS_ENABLED
2332 gboolean result = FALSE;
2333 GThread *self = G_THREAD_SELF;
2334 gboolean loop_internal_waiter;
2336 if (context == NULL)
2337 context = g_main_context_default ();
2339 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2341 if (!loop_internal_waiter)
2342 LOCK_CONTEXT (context);
2344 if (context->owner && context->owner != self)
2349 waiter.mutex = mutex;
2351 context->waiters = g_slist_append (context->waiters, &waiter);
2353 if (!loop_internal_waiter)
2354 UNLOCK_CONTEXT (context);
2355 g_cond_wait (cond, mutex);
2356 if (!loop_internal_waiter)
2357 LOCK_CONTEXT (context);
2359 context->waiters = g_slist_remove (context->waiters, &waiter);
2362 if (!context->owner)
2364 context->owner = self;
2365 g_assert (context->owner_count == 0);
2368 if (context->owner == self)
2370 context->owner_count++;
2374 if (!loop_internal_waiter)
2375 UNLOCK_CONTEXT (context);
2378 #else /* !G_THREADS_ENABLED */
2380 #endif /* G_THREADS_ENABLED */
2384 * g_main_context_prepare:
2385 * @context: a #GMainContext
2386 * @priority: location to store priority of highest priority
2387 * source already ready.
2389 * Prepares to poll sources within a main loop. The resulting information
2390 * for polling is determined by calling g_main_context_query ().
2392 * Return value: %TRUE if some source is ready to be dispatched
2396 g_main_context_prepare (GMainContext *context,
2401 gint current_priority = G_MAXINT;
2404 if (context == NULL)
2405 context = g_main_context_default ();
2407 LOCK_CONTEXT (context);
2409 context->time_is_current = FALSE;
2411 if (context->in_check_or_prepare)
2413 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2414 "prepare() member.");
2415 UNLOCK_CONTEXT (context);
2419 #ifdef G_THREADS_ENABLED
2420 if (context->poll_waiting)
2422 g_warning("g_main_context_prepare(): main loop already active in another thread");
2423 UNLOCK_CONTEXT (context);
2427 context->poll_waiting = TRUE;
2428 #endif /* G_THREADS_ENABLED */
2431 /* If recursing, finish up current dispatch, before starting over */
2432 if (context->pending_dispatches)
2435 g_main_dispatch (context, ¤t_time);
2437 UNLOCK_CONTEXT (context);
2442 /* If recursing, clear list of pending dispatches */
2444 for (i = 0; i < context->pending_dispatches->len; i++)
2446 if (context->pending_dispatches->pdata[i])
2447 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2449 g_ptr_array_set_size (context->pending_dispatches, 0);
2451 /* Prepare all sources */
2453 context->timeout = -1;
2455 source = next_valid_source (context, NULL);
2458 gint source_timeout = -1;
2460 if ((n_ready > 0) && (source->priority > current_priority))
2462 SOURCE_UNREF (source, context);
2465 if (SOURCE_BLOCKED (source))
2468 if (!(source->flags & G_SOURCE_READY))
2471 gboolean (*prepare) (GSource *source,
2474 prepare = source->source_funcs->prepare;
2475 context->in_check_or_prepare++;
2476 UNLOCK_CONTEXT (context);
2478 result = (*prepare) (source, &source_timeout);
2480 LOCK_CONTEXT (context);
2481 context->in_check_or_prepare--;
2484 source->flags |= G_SOURCE_READY;
2487 if (source->flags & G_SOURCE_READY)
2490 current_priority = source->priority;
2491 context->timeout = 0;
2494 if (source_timeout >= 0)
2496 if (context->timeout < 0)
2497 context->timeout = source_timeout;
2499 context->timeout = MIN (context->timeout, source_timeout);
2503 source = next_valid_source (context, source);
2506 UNLOCK_CONTEXT (context);
2509 *priority = current_priority;
2511 return (n_ready > 0);
2515 * g_main_context_query:
2516 * @context: a #GMainContext
2517 * @max_priority: maximum priority source to check
2518 * @timeout_: location to store timeout to be used in polling
2519 * @fds: location to store #GPollFD records that need to be polled.
2520 * @n_fds: length of @fds.
2522 * Determines information necessary to poll this main loop.
2524 * Return value: the number of records actually stored in @fds,
2525 * or, if more than @n_fds records need to be stored, the number
2526 * of records that need to be stored.
2529 g_main_context_query (GMainContext *context,
2538 LOCK_CONTEXT (context);
2540 pollrec = context->poll_records;
2542 while (pollrec && max_priority >= pollrec->priority)
2544 /* We need to include entries with fd->events == 0 in the array because
2545 * otherwise if the application changes fd->events behind our back and
2546 * makes it non-zero, we'll be out of sync when we check the fds[] array.
2547 * (Changing fd->events after adding an FD wasn't an anticipated use of
2548 * this API, but it occurs in practice.) */
2551 fds[n_poll].fd = pollrec->fd->fd;
2552 /* In direct contradiction to the Unix98 spec, IRIX runs into
2553 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2554 * flags in the events field of the pollfd while it should
2555 * just ignoring them. So we mask them out here.
2557 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2558 fds[n_poll].revents = 0;
2561 pollrec = pollrec->next;
2565 #ifdef G_THREADS_ENABLED
2566 context->poll_changed = FALSE;
2571 *timeout = context->timeout;
2573 context->time_is_current = FALSE;
2576 UNLOCK_CONTEXT (context);
2582 * g_main_context_check:
2583 * @context: a #GMainContext
2584 * @max_priority: the maximum numerical priority of sources to check
2585 * @fds: array of #GPollFD's that was passed to the last call to
2586 * g_main_context_query()
2587 * @n_fds: return value of g_main_context_query()
2589 * Passes the results of polling back to the main loop.
2591 * Return value: %TRUE if some sources are ready to be dispatched.
2594 g_main_context_check (GMainContext *context,
2604 LOCK_CONTEXT (context);
2606 if (context->in_check_or_prepare)
2608 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2609 "prepare() member.");
2610 UNLOCK_CONTEXT (context);
2614 #ifdef G_THREADS_ENABLED
2615 if (!context->poll_waiting)
2619 read (context->wake_up_pipe[0], &a, 1);
2623 context->poll_waiting = FALSE;
2625 /* If the set of poll file descriptors changed, bail out
2626 * and let the main loop rerun
2628 if (context->poll_changed)
2630 UNLOCK_CONTEXT (context);
2633 #endif /* G_THREADS_ENABLED */
2635 pollrec = context->poll_records;
2639 if (pollrec->fd->events)
2640 pollrec->fd->revents = fds[i].revents;
2642 pollrec = pollrec->next;
2646 source = next_valid_source (context, NULL);
2649 if ((n_ready > 0) && (source->priority > max_priority))
2651 SOURCE_UNREF (source, context);
2654 if (SOURCE_BLOCKED (source))
2657 if (!(source->flags & G_SOURCE_READY))
2660 gboolean (*check) (GSource *source);
2662 check = source->source_funcs->check;
2664 context->in_check_or_prepare++;
2665 UNLOCK_CONTEXT (context);
2667 result = (*check) (source);
2669 LOCK_CONTEXT (context);
2670 context->in_check_or_prepare--;
2673 source->flags |= G_SOURCE_READY;
2676 if (source->flags & G_SOURCE_READY)
2678 source->ref_count++;
2679 g_ptr_array_add (context->pending_dispatches, source);
2683 /* never dispatch sources with less priority than the first
2684 * one we choose to dispatch
2686 max_priority = source->priority;
2690 source = next_valid_source (context, source);
2693 UNLOCK_CONTEXT (context);
2699 * g_main_context_dispatch:
2700 * @context: a #GMainContext
2702 * Dispatches all pending sources.
2705 g_main_context_dispatch (GMainContext *context)
2707 LOCK_CONTEXT (context);
2709 if (context->pending_dispatches->len > 0)
2711 g_main_dispatch (context);
2714 UNLOCK_CONTEXT (context);
2717 /* HOLDS context lock */
2719 g_main_context_iterate (GMainContext *context,
2726 gboolean some_ready;
2727 gint nfds, allocated_nfds;
2728 GPollFD *fds = NULL;
2730 UNLOCK_CONTEXT (context);
2732 #ifdef G_THREADS_ENABLED
2733 if (!g_main_context_acquire (context))
2735 gboolean got_ownership;
2737 LOCK_CONTEXT (context);
2739 g_return_val_if_fail (g_thread_supported (), FALSE);
2745 context->cond = g_cond_new ();
2747 got_ownership = g_main_context_wait (context,
2749 g_static_mutex_get_mutex (&context->mutex));
2755 LOCK_CONTEXT (context);
2756 #endif /* G_THREADS_ENABLED */
2758 if (!context->cached_poll_array)
2760 context->cached_poll_array_size = context->n_poll_records;
2761 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2764 allocated_nfds = context->cached_poll_array_size;
2765 fds = context->cached_poll_array;
2767 UNLOCK_CONTEXT (context);
2769 g_main_context_prepare (context, &max_priority);
2771 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
2772 allocated_nfds)) > allocated_nfds)
2774 LOCK_CONTEXT (context);
2776 context->cached_poll_array_size = allocated_nfds = nfds;
2777 context->cached_poll_array = fds = g_new (GPollFD, nfds);
2778 UNLOCK_CONTEXT (context);
2784 g_main_context_poll (context, timeout, max_priority, fds, nfds);
2786 some_ready = g_main_context_check (context, max_priority, fds, nfds);
2789 g_main_context_dispatch (context);
2791 #ifdef G_THREADS_ENABLED
2792 g_main_context_release (context);
2793 #endif /* G_THREADS_ENABLED */
2795 LOCK_CONTEXT (context);
2801 * g_main_context_pending:
2802 * @context: a #GMainContext (if %NULL, the default context will be used)
2804 * Checks if any sources have pending events for the given context.
2806 * Return value: %TRUE if events are pending.
2809 g_main_context_pending (GMainContext *context)
2814 context = g_main_context_default();
2816 LOCK_CONTEXT (context);
2817 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
2818 UNLOCK_CONTEXT (context);
2824 * g_main_context_iteration:
2825 * @context: a #GMainContext (if %NULL, the default context will be used)
2826 * @may_block: whether the call may block.
2828 * Runs a single iteration for the given main loop. This involves
2829 * checking to see if any event sources are ready to be processed,
2830 * then if no events sources are ready and @may_block is %TRUE, waiting
2831 * for a source to become ready, then dispatching the highest priority
2832 * events sources that are ready. Otherwise, if @may_block is %FALSE
2833 * sources are not waited to become ready, only those highest priority
2834 * events sources will be dispatched (if any), that are ready at this
2835 * given moment without further waiting.
2837 * Note that even when @may_block is %TRUE, it is still possible for
2838 * g_main_context_iteration() to return %FALSE, since the the wait may
2839 * be interrupted for other reasons than an event source becoming ready.
2841 * Return value: %TRUE if events were dispatched.
2844 g_main_context_iteration (GMainContext *context, gboolean may_block)
2849 context = g_main_context_default();
2851 LOCK_CONTEXT (context);
2852 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
2853 UNLOCK_CONTEXT (context);
2860 * @context: a #GMainContext (if %NULL, the default context will be used).
2861 * @is_running: set to %TRUE to indicate that the loop is running. This
2862 * is not very important since calling g_main_loop_run() will set this to
2865 * Creates a new #GMainLoop structure.
2867 * Return value: a new #GMainLoop.
2870 g_main_loop_new (GMainContext *context,
2871 gboolean is_running)
2876 context = g_main_context_default();
2878 g_main_context_ref (context);
2880 loop = g_new0 (GMainLoop, 1);
2881 loop->context = context;
2882 loop->is_running = is_running != FALSE;
2883 loop->ref_count = 1;
2890 * @loop: a #GMainLoop
2892 * Increases the reference count on a #GMainLoop object by one.
2894 * Return value: @loop
2897 g_main_loop_ref (GMainLoop *loop)
2899 g_return_val_if_fail (loop != NULL, NULL);
2900 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2902 g_atomic_int_inc (&loop->ref_count);
2908 * g_main_loop_unref:
2909 * @loop: a #GMainLoop
2911 * Decreases the reference count on a #GMainLoop object by one. If
2912 * the result is zero, free the loop and free all associated memory.
2915 g_main_loop_unref (GMainLoop *loop)
2917 g_return_if_fail (loop != NULL);
2918 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2920 if (!g_atomic_int_dec_and_test (&loop->ref_count))
2923 g_main_context_unref (loop->context);
2929 * @loop: a #GMainLoop
2931 * Runs a main loop until g_main_loop_quit() is called on the loop.
2932 * If this is called for the thread of the loop's #GMainContext,
2933 * it will process events from the loop, otherwise it will
2937 g_main_loop_run (GMainLoop *loop)
2939 GThread *self = G_THREAD_SELF;
2941 g_return_if_fail (loop != NULL);
2942 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2944 #ifdef G_THREADS_ENABLED
2945 if (!g_main_context_acquire (loop->context))
2947 gboolean got_ownership = FALSE;
2949 /* Another thread owns this context */
2950 if (!g_thread_supported ())
2952 g_warning ("g_main_loop_run() was called from second thread but "
2953 "g_thread_init() was never called.");
2957 LOCK_CONTEXT (loop->context);
2959 g_atomic_int_inc (&loop->ref_count);
2961 if (!loop->is_running)
2962 loop->is_running = TRUE;
2964 if (!loop->context->cond)
2965 loop->context->cond = g_cond_new ();
2967 while (loop->is_running && !got_ownership)
2968 got_ownership = g_main_context_wait (loop->context,
2969 loop->context->cond,
2970 g_static_mutex_get_mutex (&loop->context->mutex));
2972 if (!loop->is_running)
2974 UNLOCK_CONTEXT (loop->context);
2976 g_main_context_release (loop->context);
2977 g_main_loop_unref (loop);
2981 g_assert (got_ownership);
2984 LOCK_CONTEXT (loop->context);
2985 #endif /* G_THREADS_ENABLED */
2987 if (loop->context->in_check_or_prepare)
2989 g_warning ("g_main_loop_run(): called recursively from within a source's "
2990 "check() or prepare() member, iteration not possible.");
2994 g_atomic_int_inc (&loop->ref_count);
2995 loop->is_running = TRUE;
2996 while (loop->is_running)
2997 g_main_context_iterate (loop->context, TRUE, TRUE, self);
2999 UNLOCK_CONTEXT (loop->context);
3001 #ifdef G_THREADS_ENABLED
3002 g_main_context_release (loop->context);
3003 #endif /* G_THREADS_ENABLED */
3005 g_main_loop_unref (loop);
3010 * @loop: a #GMainLoop
3012 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3013 * for the loop will return.
3015 * Note that sources that have already been dispatched when
3016 * g_main_loop_quit() is called will still be executed.
3019 g_main_loop_quit (GMainLoop *loop)
3021 g_return_if_fail (loop != NULL);
3022 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3024 LOCK_CONTEXT (loop->context);
3025 loop->is_running = FALSE;
3026 g_main_context_wakeup_unlocked (loop->context);
3028 #ifdef G_THREADS_ENABLED
3029 if (loop->context->cond)
3030 g_cond_broadcast (loop->context->cond);
3031 #endif /* G_THREADS_ENABLED */
3033 UNLOCK_CONTEXT (loop->context);
3037 * g_main_loop_is_running:
3038 * @loop: a #GMainLoop.
3040 * Checks to see if the main loop is currently being run via g_main_loop_run().
3042 * Return value: %TRUE if the mainloop is currently being run.
3045 g_main_loop_is_running (GMainLoop *loop)
3047 g_return_val_if_fail (loop != NULL, FALSE);
3048 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3050 return loop->is_running;
3054 * g_main_loop_get_context:
3055 * @loop: a #GMainLoop.
3057 * Returns the #GMainContext of @loop.
3059 * Return value: the #GMainContext of @loop
3062 g_main_loop_get_context (GMainLoop *loop)
3064 g_return_val_if_fail (loop != NULL, NULL);
3065 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3067 return loop->context;
3070 /* HOLDS: context's lock */
3072 g_main_context_poll (GMainContext *context,
3078 #ifdef G_MAIN_POLL_DEBUG
3084 GPollFunc poll_func;
3086 if (n_fds || timeout != 0)
3088 #ifdef G_MAIN_POLL_DEBUG
3089 if (_g_main_poll_debug)
3091 g_print ("polling context=%p n=%d timeout=%d\n",
3092 context, n_fds, timeout);
3093 poll_timer = g_timer_new ();
3097 LOCK_CONTEXT (context);
3099 poll_func = context->poll_func;
3101 UNLOCK_CONTEXT (context);
3102 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3105 g_warning ("poll(2) failed due to: %s.",
3106 g_strerror (errno));
3108 /* If g_poll () returns -1, it has already called g_warning() */
3112 #ifdef G_MAIN_POLL_DEBUG
3113 if (_g_main_poll_debug)
3115 LOCK_CONTEXT (context);
3117 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3120 g_timer_elapsed (poll_timer, NULL));
3121 g_timer_destroy (poll_timer);
3122 pollrec = context->poll_records;
3124 while (pollrec != NULL)
3129 if (fds[i].fd == pollrec->fd->fd &&
3130 pollrec->fd->events &&
3133 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3134 if (fds[i].revents & G_IO_IN)
3136 if (fds[i].revents & G_IO_OUT)
3138 if (fds[i].revents & G_IO_PRI)
3140 if (fds[i].revents & G_IO_ERR)
3142 if (fds[i].revents & G_IO_HUP)
3144 if (fds[i].revents & G_IO_NVAL)
3150 pollrec = pollrec->next;
3154 UNLOCK_CONTEXT (context);
3157 } /* if (n_fds || timeout != 0) */
3161 * g_main_context_add_poll:
3162 * @context: a #GMainContext (or %NULL for the default context)
3163 * @fd: a #GPollFD structure holding information about a file
3164 * descriptor to watch.
3165 * @priority: the priority for this file descriptor which should be
3166 * the same as the priority used for g_source_attach() to ensure that the
3167 * file descriptor is polled whenever the results may be needed.
3169 * Adds a file descriptor to the set of file descriptors polled for
3170 * this context. This will very seldomly be used directly. Instead
3171 * a typical event source will use g_source_add_poll() instead.
3174 g_main_context_add_poll (GMainContext *context,
3179 context = g_main_context_default ();
3181 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3182 g_return_if_fail (fd);
3184 LOCK_CONTEXT (context);
3185 g_main_context_add_poll_unlocked (context, priority, fd);
3186 UNLOCK_CONTEXT (context);
3189 /* HOLDS: main_loop_lock */
3191 g_main_context_add_poll_unlocked (GMainContext *context,
3195 GPollRec *lastrec, *pollrec;
3196 GPollRec *newrec = g_slice_new (GPollRec);
3198 /* This file descriptor may be checked before we ever poll */
3201 newrec->priority = priority;
3204 pollrec = context->poll_records;
3205 while (pollrec && priority >= pollrec->priority)
3208 pollrec = pollrec->next;
3212 lastrec->next = newrec;
3214 context->poll_records = newrec;
3216 newrec->next = pollrec;
3218 context->n_poll_records++;
3220 #ifdef G_THREADS_ENABLED
3221 context->poll_changed = TRUE;
3223 /* Now wake up the main loop if it is waiting in the poll() */
3224 g_main_context_wakeup_unlocked (context);
3229 * g_main_context_remove_poll:
3230 * @context:a #GMainContext
3231 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3233 * Removes file descriptor from the set of file descriptors to be
3234 * polled for a particular context.
3237 g_main_context_remove_poll (GMainContext *context,
3241 context = g_main_context_default ();
3243 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3244 g_return_if_fail (fd);
3246 LOCK_CONTEXT (context);
3247 g_main_context_remove_poll_unlocked (context, fd);
3248 UNLOCK_CONTEXT (context);
3252 g_main_context_remove_poll_unlocked (GMainContext *context,
3255 GPollRec *pollrec, *lastrec;
3258 pollrec = context->poll_records;
3262 if (pollrec->fd == fd)
3264 if (lastrec != NULL)
3265 lastrec->next = pollrec->next;
3267 context->poll_records = pollrec->next;
3269 g_slice_free (GPollRec, pollrec);
3271 context->n_poll_records--;
3275 pollrec = pollrec->next;
3278 #ifdef G_THREADS_ENABLED
3279 context->poll_changed = TRUE;
3281 /* Now wake up the main loop if it is waiting in the poll() */
3282 g_main_context_wakeup_unlocked (context);
3287 * g_source_get_current_time:
3288 * @source: a #GSource
3289 * @timeval: #GTimeVal structure in which to store current time.
3291 * Gets the "current time" to be used when checking
3292 * this source. The advantage of calling this function over
3293 * calling g_get_current_time() directly is that when
3294 * checking multiple sources, GLib can cache a single value
3295 * instead of having to repeatedly get the system time.
3298 g_source_get_current_time (GSource *source,
3301 GMainContext *context;
3303 g_return_if_fail (source->context != NULL);
3305 context = source->context;
3307 LOCK_CONTEXT (context);
3309 if (!context->time_is_current)
3311 g_get_current_time (&context->current_time);
3312 context->time_is_current = TRUE;
3315 *timeval = context->current_time;
3317 UNLOCK_CONTEXT (context);
3321 * g_main_context_set_poll_func:
3322 * @context: a #GMainContext
3323 * @func: the function to call to poll all file descriptors
3325 * Sets the function to use to handle polling of file descriptors. It
3326 * will be used instead of the poll() system call
3327 * (or GLib's replacement function, which is used where
3328 * poll() isn't available).
3330 * This function could possibly be used to integrate the GLib event
3331 * loop with an external event loop.
3334 g_main_context_set_poll_func (GMainContext *context,
3338 context = g_main_context_default ();
3340 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3342 LOCK_CONTEXT (context);
3345 context->poll_func = func;
3347 context->poll_func = g_poll;
3349 UNLOCK_CONTEXT (context);
3353 * g_main_context_get_poll_func:
3354 * @context: a #GMainContext
3356 * Gets the poll function set by g_main_context_set_poll_func().
3358 * Return value: the poll function
3361 g_main_context_get_poll_func (GMainContext *context)
3366 context = g_main_context_default ();
3368 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3370 LOCK_CONTEXT (context);
3371 result = context->poll_func;
3372 UNLOCK_CONTEXT (context);
3377 /* HOLDS: context's lock */
3378 /* Wake the main loop up from a poll() */
3380 g_main_context_wakeup_unlocked (GMainContext *context)
3382 #ifdef G_THREADS_ENABLED
3383 if (g_thread_supported() && context->poll_waiting)
3385 context->poll_waiting = FALSE;
3387 write (context->wake_up_pipe[1], "A", 1);
3389 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
3396 * g_main_context_wakeup:
3397 * @context: a #GMainContext
3399 * If @context is currently waiting in a poll(), interrupt
3400 * the poll(), and continue the iteration process.
3403 g_main_context_wakeup (GMainContext *context)
3406 context = g_main_context_default ();
3408 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3410 LOCK_CONTEXT (context);
3411 g_main_context_wakeup_unlocked (context);
3412 UNLOCK_CONTEXT (context);
3416 * g_main_context_is_owner:
3417 * @context: a #GMainContext
3419 * Determines whether this thread holds the (recursive)
3420 * ownership of this #GMaincontext. This is useful to
3421 * know before waiting on another thread that may be
3422 * blocking to get ownership of @context.
3424 * Returns: %TRUE if current thread is owner of @context.
3429 g_main_context_is_owner (GMainContext *context)
3434 context = g_main_context_default ();
3436 #ifdef G_THREADS_ENABLED
3437 LOCK_CONTEXT (context);
3438 is_owner = context->owner == G_THREAD_SELF;
3439 UNLOCK_CONTEXT (context);
3450 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3451 GTimeVal *current_time)
3453 guint seconds = timeout_source->interval / 1000;
3454 guint msecs = timeout_source->interval - seconds * 1000;
3456 timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
3457 timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
3458 if (timeout_source->expiration.tv_usec >= 1000000)
3460 timeout_source->expiration.tv_usec -= 1000000;
3461 timeout_source->expiration.tv_sec++;
3463 if (timer_perturb==-1)
3466 * we want a per machine/session unique 'random' value; try the dbus
3467 * address first, that has a UUID in it. If there is no dbus, use the
3468 * hostname for hashing.
3470 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3471 if (!session_bus_address)
3472 session_bus_address = g_getenv ("HOSTNAME");
3473 if (session_bus_address)
3474 timer_perturb = ABS ((gint) g_str_hash (session_bus_address));
3478 if (timeout_source->granularity)
3481 gint gran; /* in usecs */
3484 gran = timeout_source->granularity * 1000;
3485 perturb = timer_perturb % gran;
3487 * We want to give each machine a per machine pertubation;
3488 * shift time back first, and forward later after the rounding
3491 timeout_source->expiration.tv_usec -= perturb;
3492 if (timeout_source->expiration.tv_usec < 0)
3494 timeout_source->expiration.tv_usec += 1000000;
3495 timeout_source->expiration.tv_sec--;
3498 remainder = timeout_source->expiration.tv_usec % gran;
3499 if (remainder >= gran/4) /* round up */
3500 timeout_source->expiration.tv_usec += gran;
3501 timeout_source->expiration.tv_usec -= remainder;
3503 timeout_source->expiration.tv_usec += perturb;
3505 /* the rounding may have overflown tv_usec */
3506 while (timeout_source->expiration.tv_usec > 1000000)
3508 timeout_source->expiration.tv_usec -= 1000000;
3509 timeout_source->expiration.tv_sec++;
3515 g_timeout_prepare (GSource *source,
3520 GTimeVal current_time;
3522 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3524 g_source_get_current_time (source, ¤t_time);
3526 sec = timeout_source->expiration.tv_sec - current_time.tv_sec;
3527 msec = (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000;
3529 /* We do the following in a rather convoluted fashion to deal with
3530 * the fact that we don't have an integral type big enough to hold
3531 * the difference of two timevals in millseconds.
3533 if (sec < 0 || (sec == 0 && msec < 0))
3537 glong interval_sec = timeout_source->interval / 1000;
3538 glong interval_msec = timeout_source->interval % 1000;
3546 if (sec > interval_sec ||
3547 (sec == interval_sec && msec > interval_msec))
3549 /* The system time has been set backwards, so we
3550 * reset the expiration time to now + timeout_source->interval;
3551 * this at least avoids hanging for long periods of time.
3553 g_timeout_set_expiration (timeout_source, ¤t_time);
3554 msec = MIN (G_MAXINT, timeout_source->interval);
3558 msec = MIN (G_MAXINT, (guint)msec + 1000 * (guint)sec);
3562 *timeout = (gint)msec;
3568 g_timeout_check (GSource *source)
3570 GTimeVal current_time;
3571 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3573 g_source_get_current_time (source, ¤t_time);
3575 return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
3576 ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
3577 (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
3581 g_timeout_dispatch (GSource *source,
3582 GSourceFunc callback,
3585 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3589 g_warning ("Timeout source dispatched without callback\n"
3590 "You must call g_source_set_callback().");
3594 if (callback (user_data))
3596 GTimeVal current_time;
3598 g_source_get_current_time (source, ¤t_time);
3599 g_timeout_set_expiration (timeout_source, ¤t_time);
3608 * g_timeout_source_new:
3609 * @interval: the timeout interval in milliseconds.
3611 * Creates a new timeout source.
3613 * The source will not initially be associated with any #GMainContext
3614 * and must be added to one with g_source_attach() before it will be
3617 * Return value: the newly-created timeout source
3620 g_timeout_source_new (guint interval)
3622 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3623 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3624 GTimeVal current_time;
3626 timeout_source->interval = interval;
3628 g_get_current_time (¤t_time);
3629 g_timeout_set_expiration (timeout_source, ¤t_time);
3635 * g_timeout_source_new_seconds:
3636 * @interval: the timeout interval in seconds
3638 * Creates a new timeout source.
3640 * The source will not initially be associated with any #GMainContext
3641 * and must be added to one with g_source_attach() before it will be
3644 * The scheduling granularity/accuracy of this timeout source will be
3647 * Return value: the newly-created timeout source
3652 g_timeout_source_new_seconds (guint interval)
3654 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3655 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3656 GTimeVal current_time;
3658 timeout_source->interval = 1000*interval;
3659 timeout_source->granularity = 1000;
3661 g_get_current_time (¤t_time);
3662 g_timeout_set_expiration (timeout_source, ¤t_time);
3669 * g_timeout_add_full:
3670 * @priority: the priority of the timeout source. Typically this will be in
3671 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3672 * @interval: the time between calls to the function, in milliseconds
3673 * (1/1000ths of a second)
3674 * @function: function to call
3675 * @data: data to pass to @function
3676 * @notify: function to call when the timeout is removed, or %NULL
3678 * Sets a function to be called at regular intervals, with the given
3679 * priority. The function is called repeatedly until it returns
3680 * %FALSE, at which point the timeout is automatically destroyed and
3681 * the function will not be called again. The @notify function is
3682 * called when the timeout is destroyed. The first call to the
3683 * function will be at the end of the first @interval.
3685 * Note that timeout functions may be delayed, due to the processing of other
3686 * event sources. Thus they should not be relied on for precise timing.
3687 * After each call to the timeout function, the time of the next
3688 * timeout is recalculated based on the current time and the given interval
3689 * (it does not try to 'catch up' time lost in delays).
3691 * This internally creates a main loop source using g_timeout_source_new()
3692 * and attaches it to the main loop context using g_source_attach(). You can
3693 * do these steps manually if you need greater control.
3695 * Return value: the ID (greater than 0) of the event source.
3698 g_timeout_add_full (gint priority,
3700 GSourceFunc function,
3702 GDestroyNotify notify)
3707 g_return_val_if_fail (function != NULL, 0);
3709 source = g_timeout_source_new (interval);
3711 if (priority != G_PRIORITY_DEFAULT)
3712 g_source_set_priority (source, priority);
3714 g_source_set_callback (source, function, data, notify);
3715 id = g_source_attach (source, NULL);
3716 g_source_unref (source);
3723 * @interval: the time between calls to the function, in milliseconds
3724 * (1/1000ths of a second)
3725 * @function: function to call
3726 * @data: data to pass to @function
3728 * Sets a function to be called at regular intervals, with the default
3729 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
3730 * until it returns %FALSE, at which point the timeout is automatically
3731 * destroyed and the function will not be called again. The first call
3732 * to the function will be at the end of the first @interval.
3734 * Note that timeout functions may be delayed, due to the processing of other
3735 * event sources. Thus they should not be relied on for precise timing.
3736 * After each call to the timeout function, the time of the next
3737 * timeout is recalculated based on the current time and the given interval
3738 * (it does not try to 'catch up' time lost in delays).
3740 * If you want to have a timer in the "seconds" range and do not care
3741 * about the exact time of the first call of the timer, use the
3742 * g_timeout_add_seconds() function; this function allows for more
3743 * optimizations and more efficient system power usage.
3745 * This internally creates a main loop source using g_timeout_source_new()
3746 * and attaches it to the main loop context using g_source_attach(). You can
3747 * do these steps manually if you need greater control.
3749 * Return value: the ID (greater than 0) of the event source.
3752 g_timeout_add (guint32 interval,
3753 GSourceFunc function,
3756 return g_timeout_add_full (G_PRIORITY_DEFAULT,
3757 interval, function, data, NULL);
3761 * g_timeout_add_seconds_full:
3762 * @priority: the priority of the timeout source. Typically this will be in
3763 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3764 * @interval: the time between calls to the function, in seconds
3765 * @function: function to call
3766 * @data: data to pass to @function
3767 * @notify: function to call when the timeout is removed, or %NULL
3769 * Sets a function to be called at regular intervals, with @priority.
3770 * The function is called repeatedly until it returns %FALSE, at which
3771 * point the timeout is automatically destroyed and the function will
3772 * not be called again.
3774 * Unlike g_timeout_add(), this function operates at whole second granularity.
3775 * The initial starting point of the timer is determined by the implementation
3776 * and the implementation is expected to group multiple timers together so that
3777 * they fire all at the same time.
3778 * To allow this grouping, the @interval to the first timer is rounded
3779 * and can deviate up to one second from the specified interval.
3780 * Subsequent timer iterations will generally run at the specified interval.
3782 * Note that timeout functions may be delayed, due to the processing of other
3783 * event sources. Thus they should not be relied on for precise timing.
3784 * After each call to the timeout function, the time of the next
3785 * timeout is recalculated based on the current time and the given @interval
3787 * If you want timing more precise than whole seconds, use g_timeout_add()
3790 * The grouping of timers to fire at the same time results in a more power
3791 * and CPU efficient behavior so if your timer is in multiples of seconds
3792 * and you don't require the first timer exactly one second from now, the
3793 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
3795 * This internally creates a main loop source using
3796 * g_timeout_source_new_seconds() and attaches it to the main loop context
3797 * using g_source_attach(). You can do these steps manually if you need
3800 * Return value: the ID (greater than 0) of the event source.
3805 g_timeout_add_seconds_full (gint priority,
3807 GSourceFunc function,
3809 GDestroyNotify notify)
3814 g_return_val_if_fail (function != NULL, 0);
3816 source = g_timeout_source_new_seconds (interval);
3818 if (priority != G_PRIORITY_DEFAULT)
3819 g_source_set_priority (source, priority);
3821 g_source_set_callback (source, function, data, notify);
3822 id = g_source_attach (source, NULL);
3823 g_source_unref (source);
3829 * g_timeout_add_seconds:
3830 * @interval: the time between calls to the function, in seconds
3831 * @function: function to call
3832 * @data: data to pass to @function
3834 * Sets a function to be called at regular intervals with the default
3835 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
3836 * it returns %FALSE, at which point the timeout is automatically destroyed
3837 * and the function will not be called again.
3839 * This internally creates a main loop source using
3840 * g_timeout_source_new_seconds() and attaches it to the main loop context
3841 * using g_source_attach(). You can do these steps manually if you need
3842 * greater control. Also see g_timout_add_seconds_full().
3844 * Return value: the ID (greater than 0) of the event source.
3849 g_timeout_add_seconds (guint interval,
3850 GSourceFunc function,
3853 g_return_val_if_fail (function != NULL, 0);
3855 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
3858 /* Child watch functions */
3863 g_child_watch_prepare (GSource *source,
3872 g_child_watch_check (GSource *source)
3874 GChildWatchSource *child_watch_source;
3875 gboolean child_exited;
3877 child_watch_source = (GChildWatchSource *) source;
3879 child_exited = child_watch_source->poll.revents & G_IO_IN;
3886 * Note: We do _not_ check for the special value of STILL_ACTIVE
3887 * since we know that the process has exited and doing so runs into
3888 * problems if the child process "happens to return STILL_ACTIVE(259)"
3889 * as Microsoft's Platform SDK puts it.
3891 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
3893 gchar *emsg = g_win32_error_message (GetLastError ());
3894 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
3897 child_watch_source->child_status = -1;
3900 child_watch_source->child_status = child_status;
3903 return child_exited;
3906 #else /* G_OS_WIN32 */
3909 check_for_child_exited (GSource *source)
3911 GChildWatchSource *child_watch_source;
3914 /* protect against another SIGCHLD in the middle of this call */
3915 count = child_watch_count;
3917 child_watch_source = (GChildWatchSource *) source;
3919 if (child_watch_source->child_exited)
3922 if (child_watch_source->count < count)
3926 if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
3928 child_watch_source->child_status = child_status;
3929 child_watch_source->child_exited = TRUE;
3931 child_watch_source->count = count;
3934 return child_watch_source->child_exited;
3938 g_child_watch_prepare (GSource *source,
3943 return check_for_child_exited (source);
3948 g_child_watch_check (GSource *source)
3950 return check_for_child_exited (source);
3953 #endif /* G_OS_WIN32 */
3956 g_child_watch_dispatch (GSource *source,
3957 GSourceFunc callback,
3960 GChildWatchSource *child_watch_source;
3961 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
3963 child_watch_source = (GChildWatchSource *) source;
3967 g_warning ("Child watch source dispatched without callback\n"
3968 "You must call g_source_set_callback().");
3972 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
3974 /* We never keep a child watch source around as the child is gone */
3981 g_child_watch_signal_handler (int signum)
3983 child_watch_count ++;
3985 if (child_watch_init_state == CHILD_WATCH_INITIALIZED_THREADED)
3987 write (child_watch_wake_up_pipe[1], "B", 1);
3991 /* We count on the signal interrupting the poll in the same thread.
3997 g_child_watch_source_init_single (void)
3999 struct sigaction action;
4001 g_assert (! g_thread_supported());
4002 g_assert (child_watch_init_state == CHILD_WATCH_UNINITIALIZED);
4004 child_watch_init_state = CHILD_WATCH_INITIALIZED_SINGLE;
4006 action.sa_handler = g_child_watch_signal_handler;
4007 sigemptyset (&action.sa_mask);
4008 action.sa_flags = SA_NOCLDSTOP;
4009 sigaction (SIGCHLD, &action, NULL);
4012 G_GNUC_NORETURN static gpointer
4013 child_watch_helper_thread (gpointer data)
4020 read (child_watch_wake_up_pipe[0], b, 20);
4022 /* We were woken up. Wake up all other contexts in all other threads */
4023 G_LOCK (main_context_list);
4024 for (list = main_context_list; list; list = list->next)
4026 GMainContext *context;
4028 context = list->data;
4029 if (g_atomic_int_get (&context->ref_count) > 0)
4030 /* Due to racing conditions we can find ref_count == 0, in
4031 * that case, however, the context is still not destroyed
4032 * and no poll can be active, otherwise the ref_count
4034 g_main_context_wakeup (context);
4036 G_UNLOCK (main_context_list);
4041 g_child_watch_source_init_multi_threaded (void)
4043 GError *error = NULL;
4044 struct sigaction action;
4046 g_assert (g_thread_supported());
4048 if (pipe (child_watch_wake_up_pipe) < 0)
4049 g_error ("Cannot create wake up pipe: %s\n", g_strerror (errno));
4050 fcntl (child_watch_wake_up_pipe[1], F_SETFL, O_NONBLOCK | fcntl (child_watch_wake_up_pipe[1], F_GETFL));
4052 /* We create a helper thread that polls on the wakeup pipe indefinitely */
4053 /* FIXME: Think this through for races */
4054 if (g_thread_create (child_watch_helper_thread, NULL, FALSE, &error) == NULL)
4055 g_error ("Cannot create a thread to monitor child exit status: %s\n", error->message);
4056 child_watch_init_state = CHILD_WATCH_INITIALIZED_THREADED;
4058 action.sa_handler = g_child_watch_signal_handler;
4059 sigemptyset (&action.sa_mask);
4060 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4061 sigaction (SIGCHLD, &action, NULL);
4065 g_child_watch_source_init_promote_single_to_threaded (void)
4067 g_child_watch_source_init_multi_threaded ();
4071 g_child_watch_source_init (void)
4073 if (g_thread_supported())
4075 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
4076 g_child_watch_source_init_multi_threaded ();
4077 else if (child_watch_init_state == CHILD_WATCH_INITIALIZED_SINGLE)
4078 g_child_watch_source_init_promote_single_to_threaded ();
4082 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
4083 g_child_watch_source_init_single ();
4087 #endif /* !G_OS_WIN32 */
4090 * g_child_watch_source_new:
4091 * @pid: process to watch. On POSIX the pid of a child process. On
4092 * Windows a handle for a process (which doesn't have to be a child).
4094 * Creates a new child_watch source.
4096 * The source will not initially be associated with any #GMainContext
4097 * and must be added to one with g_source_attach() before it will be
4100 * Note that child watch sources can only be used in conjunction with
4101 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4104 * Note that on platforms where #GPid must be explicitly closed
4105 * (see g_spawn_close_pid()) @pid must not be closed while the
4106 * source is still active. Typically, you will want to call
4107 * g_spawn_close_pid() in the callback function for the source.
4109 * Note further that using g_child_watch_source_new() is not
4110 * compatible with calling <literal>waitpid(-1)</literal> in
4111 * the application. Calling waitpid() for individual pids will
4114 * Return value: the newly-created child watch source
4119 g_child_watch_source_new (GPid pid)
4121 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4122 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4125 child_watch_source->poll.fd = (gintptr) pid;
4126 child_watch_source->poll.events = G_IO_IN;
4128 g_source_add_poll (source, &child_watch_source->poll);
4129 #else /* G_OS_WIN32 */
4130 g_child_watch_source_init ();
4131 #endif /* G_OS_WIN32 */
4133 child_watch_source->pid = pid;
4139 * g_child_watch_add_full:
4140 * @priority: the priority of the idle source. Typically this will be in the
4141 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4142 * @pid: process to watch. On POSIX the pid of a child process. On
4143 * Windows a handle for a process (which doesn't have to be a child).
4144 * @function: function to call
4145 * @data: data to pass to @function
4146 * @notify: function to call when the idle is removed, or %NULL
4148 * Sets a function to be called when the child indicated by @pid
4149 * exits, at the priority @priority.
4151 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4152 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4153 * the spawn function for the child watching to work.
4155 * Note that on platforms where #GPid must be explicitly closed
4156 * (see g_spawn_close_pid()) @pid must not be closed while the
4157 * source is still active. Typically, you will want to call
4158 * g_spawn_close_pid() in the callback function for the source.
4160 * GLib supports only a single callback per process id.
4162 * This internally creates a main loop source using
4163 * g_child_watch_source_new() and attaches it to the main loop context
4164 * using g_source_attach(). You can do these steps manually if you
4165 * need greater control.
4167 * Return value: the ID (greater than 0) of the event source.
4172 g_child_watch_add_full (gint priority,
4174 GChildWatchFunc function,
4176 GDestroyNotify notify)
4181 g_return_val_if_fail (function != NULL, 0);
4183 source = g_child_watch_source_new (pid);
4185 if (priority != G_PRIORITY_DEFAULT)
4186 g_source_set_priority (source, priority);
4188 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4189 id = g_source_attach (source, NULL);
4190 g_source_unref (source);
4196 * g_child_watch_add:
4197 * @pid: process id to watch. On POSIX the pid of a child process. On
4198 * Windows a handle for a process (which doesn't have to be a child).
4199 * @function: function to call
4200 * @data: data to pass to @function
4202 * Sets a function to be called when the child indicated by @pid
4203 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4205 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4206 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4207 * the spawn function for the child watching to work.
4209 * Note that on platforms where #GPid must be explicitly closed
4210 * (see g_spawn_close_pid()) @pid must not be closed while the
4211 * source is still active. Typically, you will want to call
4212 * g_spawn_close_pid() in the callback function for the source.
4214 * GLib supports only a single callback per process id.
4216 * This internally creates a main loop source using
4217 * g_child_watch_source_new() and attaches it to the main loop context
4218 * using g_source_attach(). You can do these steps manually if you
4219 * need greater control.
4221 * Return value: the ID (greater than 0) of the event source.
4226 g_child_watch_add (GPid pid,
4227 GChildWatchFunc function,
4230 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4234 /* Idle functions */
4237 g_idle_prepare (GSource *source,
4246 g_idle_check (GSource *source)
4252 g_idle_dispatch (GSource *source,
4253 GSourceFunc callback,
4258 g_warning ("Idle source dispatched without callback\n"
4259 "You must call g_source_set_callback().");
4263 return callback (user_data);
4267 * g_idle_source_new:
4269 * Creates a new idle source.
4271 * The source will not initially be associated with any #GMainContext
4272 * and must be added to one with g_source_attach() before it will be
4273 * executed. Note that the default priority for idle sources is
4274 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4275 * have a default priority of %G_PRIORITY_DEFAULT.
4277 * Return value: the newly-created idle source
4280 g_idle_source_new (void)
4284 source = g_source_new (&g_idle_funcs, sizeof (GSource));
4285 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4292 * @priority: the priority of the idle source. Typically this will be in the
4293 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4294 * @function: function to call
4295 * @data: data to pass to @function
4296 * @notify: function to call when the idle is removed, or %NULL
4298 * Adds a function to be called whenever there are no higher priority
4299 * events pending. If the function returns %FALSE it is automatically
4300 * removed from the list of event sources and will not be called again.
4302 * This internally creates a main loop source using g_idle_source_new()
4303 * and attaches it to the main loop context using g_source_attach().
4304 * You can do these steps manually if you need greater control.
4306 * Return value: the ID (greater than 0) of the event source.
4309 g_idle_add_full (gint priority,
4310 GSourceFunc function,
4312 GDestroyNotify notify)
4317 g_return_val_if_fail (function != NULL, 0);
4319 source = g_idle_source_new ();
4321 if (priority != G_PRIORITY_DEFAULT_IDLE)
4322 g_source_set_priority (source, priority);
4324 g_source_set_callback (source, function, data, notify);
4325 id = g_source_attach (source, NULL);
4326 g_source_unref (source);
4333 * @function: function to call
4334 * @data: data to pass to @function.
4336 * Adds a function to be called whenever there are no higher priority
4337 * events pending to the default main loop. The function is given the
4338 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4339 * returns %FALSE it is automatically removed from the list of event
4340 * sources and will not be called again.
4342 * This internally creates a main loop source using g_idle_source_new()
4343 * and attaches it to the main loop context using g_source_attach().
4344 * You can do these steps manually if you need greater control.
4346 * Return value: the ID (greater than 0) of the event source.
4349 g_idle_add (GSourceFunc function,
4352 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4356 * g_idle_remove_by_data:
4357 * @data: the data for the idle source's callback.
4359 * Removes the idle function with the given data.
4361 * Return value: %TRUE if an idle source was found and removed.
4364 g_idle_remove_by_data (gpointer data)
4366 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4370 * g_main_context_invoke:
4371 * @context: a #GMainContext, or %NULL
4372 * @function: function to call
4373 * @data: data to pass to @function
4375 * Invokes a function in such a way that @context is owned during the
4376 * invocation of @function.
4378 * If @context is %NULL then the global default main context — as
4379 * returned by g_main_context_default() — is used.
4381 * If @context is owned by the current thread, @function is called
4382 * directly. Otherwise, if @context is the thread-default main context
4383 * of the current thread and g_main_context_acquire() succeeds, then
4384 * @function is called and g_main_context_release() is called
4387 * In any other case, an idle source is created to call @function and
4388 * that source is attached to @context (presumably to be run in another
4389 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
4390 * priority. If you want a different priority, use
4391 * g_main_context_invoke_full().
4393 * Note that, as with normal idle functions, @function should probably
4394 * return %FALSE. If it returns %TRUE, it will be continuously run in a
4395 * loop (and may prevent this call from returning).
4400 g_main_context_invoke (GMainContext *context,
4401 GSourceFunc function,
4404 g_main_context_invoke_full (context,
4406 function, data, NULL);
4410 * g_main_context_invoke_full:
4411 * @context: a #GMainContext, or %NULL
4412 * @priority: the priority at which to run @function
4413 * @function: function to call
4414 * @data: data to pass to @function
4415 * @notify: a function to call when @data is no longer in use, or %NULL.
4417 * Invokes a function in such a way that @context is owned during the
4418 * invocation of @function.
4420 * This function is the same as g_main_context_invoke() except that it
4421 * lets you specify the priority incase @function ends up being
4422 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
4424 * @notify should not assume that it is called from any particular
4425 * thread or with any particular context acquired.
4430 g_main_context_invoke_full (GMainContext *context,
4432 GSourceFunc function,
4434 GDestroyNotify notify)
4436 g_return_if_fail (function != NULL);
4439 context = g_main_context_default ();
4441 if (g_main_context_is_owner (context))
4443 while (function (data));
4450 GMainContext *thread_default;
4452 thread_default = g_main_context_get_thread_default ();
4454 if (!thread_default)
4455 thread_default = g_main_context_default ();
4457 if (thread_default == context && g_main_context_acquire (context))
4459 while (function (data));
4461 g_main_context_release (context);
4470 source = g_idle_source_new ();
4471 g_source_set_priority (source, priority);
4472 g_source_set_callback (source, function, data, notify);
4473 g_source_attach (source, context);
4474 g_source_unref (source);