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 #include "glibconfig.h"
37 /* Uncomment the next line (and the corresponding line in gpoll.c) to
38 * enable debugging printouts if the environment variable
39 * G_MAIN_POLL_DEBUG is set to some value.
41 /* #define G_MAIN_POLL_DEBUG */
44 /* Always enable debugging printout on Windows, as it is more often
47 #define G_MAIN_POLL_DEBUG
50 #define _GNU_SOURCE /* for pipe2 */
53 #include <sys/types.h>
56 #ifdef HAVE_SYS_TIME_H
58 #endif /* HAVE_SYS_TIME_H */
61 #endif /* HAVE_UNISTD_H */
67 #endif /* G_OS_WIN32 */
70 #include <sys/socket.h>
72 #endif /* G_OS_BEOS */
82 #include "giochannel.h"
86 #include "gstrfuncs.h"
87 #include "gtestutils.h"
88 #include "gthreadprivate.h"
92 * @title: The Main Event Loop
93 * @short_description: manages all available sources of events
95 * The main event loop manages all the available sources of events for
96 * GLib and GTK+ applications. These events can come from any number of
97 * different types of sources such as file descriptors (plain files,
98 * pipes or sockets) and timeouts. New types of event sources can also
99 * be added using g_source_attach().
101 * To allow multiple independent sets of sources to be handled in
102 * different threads, each source is associated with a #GMainContext.
103 * A GMainContext can only be running in a single thread, but
104 * sources can be added to it and removed from it from other threads.
106 * Each event source is assigned a priority. The default priority,
107 * #G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
108 * Values greater than 0 denote lower priorities. Events from high priority
109 * sources are always processed before events from lower priority sources.
111 * Idle functions can also be added, and assigned a priority. These will
112 * be run whenever no events with a higher priority are ready to be processed.
114 * The #GMainLoop data type represents a main event loop. A GMainLoop is
115 * created with g_main_loop_new(). After adding the initial event sources,
116 * g_main_loop_run() is called. This continuously checks for new events from
117 * each of the event sources and dispatches them. Finally, the processing of
118 * an event from one of the sources leads to a call to g_main_loop_quit() to
119 * exit the main loop, and g_main_loop_run() returns.
121 * It is possible to create new instances of #GMainLoop recursively.
122 * This is often used in GTK+ applications when showing modal dialog
123 * boxes. Note that event sources are associated with a particular
124 * #GMainContext, and will be checked and dispatched for all main
125 * loops associated with that GMainContext.
127 * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
128 * gtk_main_quit() and gtk_events_pending().
130 * <refsect2><title>Creating new source types</title>
131 * <para>One of the unusual features of the #GMainLoop functionality
132 * is that new types of event source can be created and used in
133 * addition to the builtin type of event source. A new event source
134 * type is used for handling GDK events. A new source type is created
135 * by <firstterm>deriving</firstterm> from the #GSource structure.
136 * The derived type of source is represented by a structure that has
137 * the #GSource structure as a first element, and other elements specific
138 * to the new source type. To create an instance of the new source type,
139 * call g_source_new() passing in the size of the derived structure and
140 * a table of functions. These #GSourceFuncs determine the behavior of
141 * the new source type.</para>
142 * <para>New source types basically interact with the main context
143 * in two ways. Their prepare function in #GSourceFuncs can set a timeout
144 * to determine the maximum amount of time that the main loop will sleep
145 * before checking the source again. In addition, or as well, the source
146 * can add file descriptors to the set that the main context checks using
147 * g_source_add_poll().</para>
149 * <refsect2><title>Customizing the main loop iteration</title>
150 * <para>Single iterations of a #GMainContext can be run with
151 * g_main_context_iteration(). In some cases, more detailed control
152 * of exactly how the details of the main loop work is desired, for
153 * instance, when integrating the #GMainLoop with an external main loop.
154 * In such cases, you can call the component functions of
155 * g_main_context_iteration() directly. These functions are
156 * g_main_context_prepare(), g_main_context_query(),
157 * g_main_context_check() and g_main_context_dispatch().</para>
158 * <para>The operation of these functions can best be seen in terms
159 * of a state diagram, as shown in <xref linkend="mainloop-states"/>.</para>
160 * <figure id="mainloop-states"><title>States of a Main Context</title>
161 * <graphic fileref="mainloop-states.gif" format="GIF"></graphic>
168 typedef struct _GTimeoutSource GTimeoutSource;
169 typedef struct _GChildWatchSource GChildWatchSource;
170 typedef struct _GPollRec GPollRec;
171 typedef struct _GSourceCallback GSourceCallback;
175 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
176 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
179 #ifdef G_THREADS_ENABLED
180 typedef struct _GMainWaiter GMainWaiter;
189 typedef struct _GMainDispatch GMainDispatch;
191 struct _GMainDispatch
194 GSList *dispatching_sources; /* stack of current sources */
197 #ifdef G_MAIN_POLL_DEBUG
198 gboolean _g_main_poll_debug = FALSE;
203 #ifdef G_THREADS_ENABLED
204 /* The following lock is used for both the list of sources
205 * and the list of poll records
216 GPtrArray *pending_dispatches;
217 gint timeout; /* Timeout for current iteration */
220 GSource *source_list;
221 gint in_check_or_prepare;
223 GPollRec *poll_records;
224 guint n_poll_records;
225 GPollFD *cached_poll_array;
226 guint cached_poll_array_size;
228 #ifdef G_THREADS_ENABLED
230 /* this pipe is used to wake up the main loop when a source is added.
232 gint wake_up_pipe[2];
233 #else /* G_OS_WIN32 */
234 HANDLE wake_up_semaphore;
235 #endif /* G_OS_WIN32 */
238 gboolean poll_waiting;
240 /* Flag indicating whether the set of fd's changed during a poll */
241 gboolean poll_changed;
242 #endif /* G_THREADS_ENABLED */
246 GTimeVal current_time;
247 gboolean time_is_current;
250 struct _GSourceCallback
255 GDestroyNotify notify;
260 GMainContext *context;
265 struct _GTimeoutSource
273 struct _GChildWatchSource
280 #else /* G_OS_WIN32 */
282 gboolean child_exited;
283 #endif /* G_OS_WIN32 */
293 #ifdef G_THREADS_ENABLED
294 #define LOCK_CONTEXT(context) g_static_mutex_lock (&context->mutex)
295 #define UNLOCK_CONTEXT(context) g_static_mutex_unlock (&context->mutex)
296 #define G_THREAD_SELF g_thread_self ()
298 #define LOCK_CONTEXT(context) (void)0
299 #define UNLOCK_CONTEXT(context) (void)0
300 #define G_THREAD_SELF NULL
303 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
304 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
305 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
307 #define SOURCE_UNREF(source, context) \
309 if ((source)->ref_count > 1) \
310 (source)->ref_count--; \
312 g_source_unref_internal ((source), (context), TRUE); \
316 /* Forward declarations */
318 static void g_source_unref_internal (GSource *source,
319 GMainContext *context,
321 static void g_source_destroy_internal (GSource *source,
322 GMainContext *context,
324 static void g_main_context_poll (GMainContext *context,
329 static void g_main_context_add_poll_unlocked (GMainContext *context,
332 static void g_main_context_remove_poll_unlocked (GMainContext *context,
334 static void g_main_context_wakeup_unlocked (GMainContext *context);
336 static gboolean g_timeout_prepare (GSource *source,
338 static gboolean g_timeout_check (GSource *source);
339 static gboolean g_timeout_dispatch (GSource *source,
340 GSourceFunc callback,
342 static gboolean g_child_watch_prepare (GSource *source,
344 static gboolean g_child_watch_check (GSource *source);
345 static gboolean g_child_watch_dispatch (GSource *source,
346 GSourceFunc callback,
348 static gboolean g_idle_prepare (GSource *source,
350 static gboolean g_idle_check (GSource *source);
351 static gboolean g_idle_dispatch (GSource *source,
352 GSourceFunc callback,
355 G_LOCK_DEFINE_STATIC (main_loop);
356 static GMainContext *default_main_context;
357 static GSList *main_contexts_without_pipe = NULL;
360 /* Child status monitoring code */
362 CHILD_WATCH_UNINITIALIZED,
363 CHILD_WATCH_INITIALIZED_SINGLE,
364 CHILD_WATCH_INITIALIZED_THREADED
366 static gint child_watch_init_state = CHILD_WATCH_UNINITIALIZED;
367 static gint child_watch_count = 1;
368 static gint child_watch_wake_up_pipe[2] = {0, 0};
369 #endif /* !G_OS_WIN32 */
370 G_LOCK_DEFINE_STATIC (main_context_list);
371 static GSList *main_context_list = NULL;
373 static gint timer_perturb = -1;
375 GSourceFuncs g_timeout_funcs =
383 GSourceFuncs g_child_watch_funcs =
385 g_child_watch_prepare,
387 g_child_watch_dispatch,
391 GSourceFuncs g_idle_funcs =
400 * g_main_context_ref:
401 * @context: a #GMainContext
403 * Increases the reference count on a #GMainContext object by one.
405 * Returns: the @context that was passed in (since 2.6)
408 g_main_context_ref (GMainContext *context)
410 g_return_val_if_fail (context != NULL, NULL);
411 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
413 g_atomic_int_inc (&context->ref_count);
419 poll_rec_list_free (GMainContext *context,
422 g_slice_free_chain (GPollRec, list, next);
426 * g_main_context_unref:
427 * @context: a #GMainContext
429 * Decreases the reference count on a #GMainContext object by one. If
430 * the result is zero, free the context and free all associated memory.
433 g_main_context_unref (GMainContext *context)
436 g_return_if_fail (context != NULL);
437 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
439 if (!g_atomic_int_dec_and_test (&context->ref_count))
442 G_LOCK (main_context_list);
443 main_context_list = g_slist_remove (main_context_list, context);
444 G_UNLOCK (main_context_list);
446 source = context->source_list;
449 GSource *next = source->next;
450 g_source_destroy_internal (source, context, FALSE);
454 #ifdef G_THREADS_ENABLED
455 g_static_mutex_free (&context->mutex);
458 g_ptr_array_free (context->pending_dispatches, TRUE);
459 g_free (context->cached_poll_array);
461 poll_rec_list_free (context, context->poll_records);
463 #ifdef G_THREADS_ENABLED
464 if (g_thread_supported())
467 close (context->wake_up_pipe[0]);
468 close (context->wake_up_pipe[1]);
470 CloseHandle (context->wake_up_semaphore);
474 main_contexts_without_pipe = g_slist_remove (main_contexts_without_pipe,
477 if (context->cond != NULL)
478 g_cond_free (context->cond);
484 #ifdef G_THREADS_ENABLED
486 g_main_context_init_pipe (GMainContext *context)
489 if (context->wake_up_pipe[0] != -1)
493 /* if this fails, we fall through and try pipe */
494 pipe2 (context->wake_up_pipe, O_CLOEXEC);
496 if (context->wake_up_pipe[0] == -1)
498 if (pipe (context->wake_up_pipe) < 0)
499 g_error ("Cannot create pipe main loop wake-up: %s\n",
502 fcntl (context->wake_up_pipe[0], F_SETFD, FD_CLOEXEC);
503 fcntl (context->wake_up_pipe[1], F_SETFD, FD_CLOEXEC);
506 context->wake_up_rec.fd = context->wake_up_pipe[0];
507 context->wake_up_rec.events = G_IO_IN;
509 if (context->wake_up_semaphore != NULL)
511 context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
512 if (context->wake_up_semaphore == NULL)
513 g_error ("Cannot create wake-up semaphore: %s",
514 g_win32_error_message (GetLastError ()));
515 context->wake_up_rec.fd = (gintptr) context->wake_up_semaphore;
516 context->wake_up_rec.events = G_IO_IN;
518 if (_g_main_poll_debug)
519 g_print ("wake-up semaphore: %p\n", context->wake_up_semaphore);
521 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
525 _g_main_thread_init (void)
527 GSList *curr = main_contexts_without_pipe;
530 g_main_context_init_pipe ((GMainContext *)curr->data);
533 g_slist_free (main_contexts_without_pipe);
534 main_contexts_without_pipe = NULL;
536 #endif /* G_THREADS_ENABLED */
539 * g_main_context_new:
541 * Creates a new #GMainContext structure.
543 * Return value: the new #GMainContext
546 g_main_context_new (void)
548 GMainContext *context = g_new0 (GMainContext, 1);
550 #ifdef G_MAIN_POLL_DEBUG
552 static gboolean beenhere = FALSE;
556 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
557 _g_main_poll_debug = TRUE;
563 #ifdef G_THREADS_ENABLED
564 g_static_mutex_init (&context->mutex);
566 context->owner = NULL;
567 context->waiters = NULL;
570 context->wake_up_pipe[0] = -1;
571 context->wake_up_pipe[1] = -1;
573 context->wake_up_semaphore = NULL;
577 context->ref_count = 1;
579 context->next_id = 1;
581 context->source_list = NULL;
583 context->poll_func = g_poll;
585 context->cached_poll_array = NULL;
586 context->cached_poll_array_size = 0;
588 context->pending_dispatches = g_ptr_array_new ();
590 context->time_is_current = FALSE;
592 #ifdef G_THREADS_ENABLED
593 if (g_thread_supported ())
594 g_main_context_init_pipe (context);
596 main_contexts_without_pipe = g_slist_prepend (main_contexts_without_pipe,
600 G_LOCK (main_context_list);
601 main_context_list = g_slist_append (main_context_list, context);
603 #ifdef G_MAIN_POLL_DEBUG
604 if (_g_main_poll_debug)
605 g_print ("created context=%p\n", context);
608 G_UNLOCK (main_context_list);
614 * g_main_context_default:
616 * Returns the global default main context. This is the main context
617 * used for main loop functions when a main loop is not explicitly
618 * specified, and corresponds to the "main" main loop. See also
619 * g_main_context_get_thread_default().
621 * Return value: the global default main context.
624 g_main_context_default (void)
630 if (!default_main_context)
632 default_main_context = g_main_context_new ();
633 #ifdef G_MAIN_POLL_DEBUG
634 if (_g_main_poll_debug)
635 g_print ("default context=%p\n", default_main_context);
639 G_UNLOCK (main_loop);
641 return default_main_context;
644 static GStaticPrivate thread_context_stack = G_STATIC_PRIVATE_INIT;
647 free_context_stack (gpointer data)
649 GQueue *stack = data;
650 GMainContext *context;
652 while (!g_queue_is_empty (stack))
654 context = g_queue_pop_head (stack);
655 g_main_context_release (context);
657 g_main_context_unref (context);
659 g_queue_free (stack);
663 * g_main_context_push_thread_default:
664 * @context: a #GMainContext, or %NULL for the global default context
666 * Acquires @context and sets it as the thread-default context for the
667 * current thread. This will cause certain asynchronous operations
668 * (such as most <link linkend="gio">gio</link>-based I/O) which are
669 * started in this thread to run under @context and deliver their
670 * results to its main loop, rather than running under the global
671 * default context in the main thread. Note that calling this function
672 * changes the context returned by
673 * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
674 * one returned by g_main_context_default(), so it does not affect the
675 * context used by functions like g_idle_add().
677 * Normally you would call this function shortly after creating a new
678 * thread, passing it a #GMainContext which will be run by a
679 * #GMainLoop in that thread, to set a new default context for all
680 * async operations in that thread. (In this case, you don't need to
681 * ever call g_main_context_pop_thread_default().) In some cases
682 * however, you may want to schedule a single operation in a
683 * non-default context, or temporarily use a non-default context in
684 * the main thread. In that case, you can wrap the call to the
685 * asynchronous operation inside a
686 * g_main_context_push_thread_default() /
687 * g_main_context_pop_thread_default() pair, but it is up to you to
688 * ensure that no other asynchronous operations accidentally get
689 * started while the non-default context is active.
691 * Beware that libraries that predate this function may not correctly
692 * handle being used from a thread with a thread-default context. Eg,
693 * see g_file_supports_thread_contexts().
698 g_main_context_push_thread_default (GMainContext *context)
701 gboolean acquired_context;
703 acquired_context = g_main_context_acquire (context);
704 g_return_if_fail (acquired_context);
706 if (context == g_main_context_default ())
709 g_main_context_ref (context);
711 stack = g_static_private_get (&thread_context_stack);
714 stack = g_queue_new ();
715 g_static_private_set (&thread_context_stack, stack,
719 g_queue_push_head (stack, context);
723 * g_main_context_pop_thread_default:
724 * @context: a #GMainContext object, or %NULL
726 * Pops @context off the thread-default context stack (verifying that
727 * it was on the top of the stack).
732 g_main_context_pop_thread_default (GMainContext *context)
736 if (context == g_main_context_default ())
739 stack = g_static_private_get (&thread_context_stack);
741 g_return_if_fail (stack != NULL);
742 g_return_if_fail (g_queue_peek_head (stack) == context);
744 g_queue_pop_head (stack);
746 g_main_context_release (context);
748 g_main_context_unref (context);
752 * g_main_context_get_thread_default:
754 * Gets the thread-default #GMainContext for this thread. Asynchronous
755 * operations that want to be able to be run in contexts other than
756 * the default one should call this method to get a #GMainContext to
757 * add their #GSource<!-- -->s to. (Note that even in single-threaded
758 * programs applications may sometimes want to temporarily push a
759 * non-default context, so it is not safe to assume that this will
760 * always return %NULL if threads are not initialized.)
762 * Returns: the thread-default #GMainContext, or %NULL if the
763 * thread-default context is the global default context.
768 g_main_context_get_thread_default (void)
772 stack = g_static_private_get (&thread_context_stack);
774 return g_queue_peek_head (stack);
779 /* Hooks for adding to the main loop */
783 * @source_funcs: structure containing functions that implement
784 * the sources behavior.
785 * @struct_size: size of the #GSource structure to create.
787 * Creates a new #GSource structure. The size is specified to
788 * allow creating structures derived from #GSource that contain
789 * additional data. The size passed in must be at least
790 * <literal>sizeof (GSource)</literal>.
792 * The source will not initially be associated with any #GMainContext
793 * and must be added to one with g_source_attach() before it will be
796 * Return value: the newly-created #GSource.
799 g_source_new (GSourceFuncs *source_funcs,
804 g_return_val_if_fail (source_funcs != NULL, NULL);
805 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
807 source = (GSource*) g_malloc0 (struct_size);
809 source->source_funcs = source_funcs;
810 source->ref_count = 1;
812 source->priority = G_PRIORITY_DEFAULT;
814 source->flags = G_HOOK_FLAG_ACTIVE;
816 /* NULL/0 initialization for all other fields */
821 /* Holds context's lock
824 g_source_list_add (GSource *source,
825 GMainContext *context)
827 GSource *tmp_source, *last_source;
830 tmp_source = context->source_list;
831 while (tmp_source && tmp_source->priority <= source->priority)
833 last_source = tmp_source;
834 tmp_source = tmp_source->next;
837 source->next = tmp_source;
839 tmp_source->prev = source;
841 source->prev = last_source;
843 last_source->next = source;
845 context->source_list = source;
848 /* Holds context's lock
851 g_source_list_remove (GSource *source,
852 GMainContext *context)
855 source->prev->next = source->next;
857 context->source_list = source->next;
860 source->next->prev = source->prev;
868 * @source: a #GSource
869 * @context: a #GMainContext (if %NULL, the default context will be used)
871 * Adds a #GSource to a @context so that it will be executed within
872 * that context. Remove it by calling g_source_destroy().
874 * Return value: the ID (greater than 0) for the source within the
878 g_source_attach (GSource *source,
879 GMainContext *context)
884 g_return_val_if_fail (source->context == NULL, 0);
885 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
888 context = g_main_context_default ();
890 LOCK_CONTEXT (context);
892 source->context = context;
893 result = source->source_id = context->next_id++;
896 g_source_list_add (source, context);
898 tmp_list = source->poll_fds;
901 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
902 tmp_list = tmp_list->next;
905 #ifdef G_THREADS_ENABLED
906 /* Now wake up the main loop if it is waiting in the poll() */
907 g_main_context_wakeup_unlocked (context);
910 UNLOCK_CONTEXT (context);
916 g_source_destroy_internal (GSource *source,
917 GMainContext *context,
921 LOCK_CONTEXT (context);
923 if (!SOURCE_DESTROYED (source))
926 gpointer old_cb_data;
927 GSourceCallbackFuncs *old_cb_funcs;
929 source->flags &= ~G_HOOK_FLAG_ACTIVE;
931 old_cb_data = source->callback_data;
932 old_cb_funcs = source->callback_funcs;
934 source->callback_data = NULL;
935 source->callback_funcs = NULL;
939 UNLOCK_CONTEXT (context);
940 old_cb_funcs->unref (old_cb_data);
941 LOCK_CONTEXT (context);
944 if (!SOURCE_BLOCKED (source))
946 tmp_list = source->poll_fds;
949 g_main_context_remove_poll_unlocked (context, tmp_list->data);
950 tmp_list = tmp_list->next;
954 g_source_unref_internal (source, context, TRUE);
958 UNLOCK_CONTEXT (context);
963 * @source: a #GSource
965 * Removes a source from its #GMainContext, if any, and mark it as
966 * destroyed. The source cannot be subsequently added to another
970 g_source_destroy (GSource *source)
972 GMainContext *context;
974 g_return_if_fail (source != NULL);
976 context = source->context;
979 g_source_destroy_internal (source, context, FALSE);
981 source->flags &= ~G_HOOK_FLAG_ACTIVE;
986 * @source: a #GSource
988 * Returns the numeric ID for a particular source. The ID of a source
989 * is a positive integer which is unique within a particular main loop
990 * context. The reverse
991 * mapping from ID to source is done by g_main_context_find_source_by_id().
993 * Return value: the ID (greater than 0) for the source
996 g_source_get_id (GSource *source)
1000 g_return_val_if_fail (source != NULL, 0);
1001 g_return_val_if_fail (source->context != NULL, 0);
1003 LOCK_CONTEXT (source->context);
1004 result = source->source_id;
1005 UNLOCK_CONTEXT (source->context);
1011 * g_source_get_context:
1012 * @source: a #GSource
1014 * Gets the #GMainContext with which the source is associated.
1015 * Calling this function on a destroyed source is an error.
1017 * Return value: the #GMainContext with which the source is associated,
1018 * or %NULL if the context has not yet been added
1022 g_source_get_context (GSource *source)
1024 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1026 return source->context;
1030 * g_source_add_poll:
1031 * @source:a #GSource
1032 * @fd: a #GPollFD structure holding information about a file
1033 * descriptor to watch.
1035 * Adds a file descriptor to the set of file descriptors polled for
1036 * this source. This is usually combined with g_source_new() to add an
1037 * event source. The event source's check function will typically test
1038 * the @revents field in the #GPollFD struct and return %TRUE if events need
1042 g_source_add_poll (GSource *source,
1045 GMainContext *context;
1047 g_return_if_fail (source != NULL);
1048 g_return_if_fail (fd != NULL);
1049 g_return_if_fail (!SOURCE_DESTROYED (source));
1051 context = source->context;
1054 LOCK_CONTEXT (context);
1056 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1060 if (!SOURCE_BLOCKED (source))
1061 g_main_context_add_poll_unlocked (context, source->priority, fd);
1062 UNLOCK_CONTEXT (context);
1067 * g_source_remove_poll:
1068 * @source:a #GSource
1069 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1071 * Removes a file descriptor from the set of file descriptors polled for
1075 g_source_remove_poll (GSource *source,
1078 GMainContext *context;
1080 g_return_if_fail (source != NULL);
1081 g_return_if_fail (fd != NULL);
1082 g_return_if_fail (!SOURCE_DESTROYED (source));
1084 context = source->context;
1087 LOCK_CONTEXT (context);
1089 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1093 if (!SOURCE_BLOCKED (source))
1094 g_main_context_remove_poll_unlocked (context, fd);
1095 UNLOCK_CONTEXT (context);
1100 * g_source_set_callback_indirect:
1101 * @source: the source
1102 * @callback_data: pointer to callback data "object"
1103 * @callback_funcs: functions for reference counting @callback_data
1104 * and getting the callback and data
1106 * Sets the callback function storing the data as a refcounted callback
1107 * "object". This is used internally. Note that calling
1108 * g_source_set_callback_indirect() assumes
1109 * an initial reference count on @callback_data, and thus
1110 * @callback_funcs->unref will eventually be called once more
1111 * than @callback_funcs->ref.
1114 g_source_set_callback_indirect (GSource *source,
1115 gpointer callback_data,
1116 GSourceCallbackFuncs *callback_funcs)
1118 GMainContext *context;
1119 gpointer old_cb_data;
1120 GSourceCallbackFuncs *old_cb_funcs;
1122 g_return_if_fail (source != NULL);
1123 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1125 context = source->context;
1128 LOCK_CONTEXT (context);
1130 old_cb_data = source->callback_data;
1131 old_cb_funcs = source->callback_funcs;
1133 source->callback_data = callback_data;
1134 source->callback_funcs = callback_funcs;
1137 UNLOCK_CONTEXT (context);
1140 old_cb_funcs->unref (old_cb_data);
1144 g_source_callback_ref (gpointer cb_data)
1146 GSourceCallback *callback = cb_data;
1148 callback->ref_count++;
1153 g_source_callback_unref (gpointer cb_data)
1155 GSourceCallback *callback = cb_data;
1157 callback->ref_count--;
1158 if (callback->ref_count == 0)
1160 if (callback->notify)
1161 callback->notify (callback->data);
1167 g_source_callback_get (gpointer cb_data,
1172 GSourceCallback *callback = cb_data;
1174 *func = callback->func;
1175 *data = callback->data;
1178 static GSourceCallbackFuncs g_source_callback_funcs = {
1179 g_source_callback_ref,
1180 g_source_callback_unref,
1181 g_source_callback_get,
1185 * g_source_set_callback:
1186 * @source: the source
1187 * @func: a callback function
1188 * @data: the data to pass to callback function
1189 * @notify: a function to call when @data is no longer in use, or %NULL.
1191 * Sets the callback function for a source. The callback for a source is
1192 * called from the source's dispatch function.
1194 * The exact type of @func depends on the type of source; ie. you
1195 * should not count on @func being called with @data as its first
1198 * Typically, you won't use this function. Instead use functions specific
1199 * to the type of source you are using.
1202 g_source_set_callback (GSource *source,
1205 GDestroyNotify notify)
1207 GSourceCallback *new_callback;
1209 g_return_if_fail (source != NULL);
1211 new_callback = g_new (GSourceCallback, 1);
1213 new_callback->ref_count = 1;
1214 new_callback->func = func;
1215 new_callback->data = data;
1216 new_callback->notify = notify;
1218 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1223 * g_source_set_funcs:
1224 * @source: a #GSource
1225 * @funcs: the new #GSourceFuncs
1227 * Sets the source functions (can be used to override
1228 * default implementations) of an unattached source.
1233 g_source_set_funcs (GSource *source,
1234 GSourceFuncs *funcs)
1236 g_return_if_fail (source != NULL);
1237 g_return_if_fail (source->context == NULL);
1238 g_return_if_fail (source->ref_count > 0);
1239 g_return_if_fail (funcs != NULL);
1241 source->source_funcs = funcs;
1245 * g_source_set_priority:
1246 * @source: a #GSource
1247 * @priority: the new priority.
1249 * Sets the priority of a source. While the main loop is being
1250 * run, a source will be dispatched if it is ready to be dispatched and no sources
1251 * at a higher (numerically smaller) priority are ready to be dispatched.
1254 g_source_set_priority (GSource *source,
1258 GMainContext *context;
1260 g_return_if_fail (source != NULL);
1262 context = source->context;
1265 LOCK_CONTEXT (context);
1267 source->priority = priority;
1271 /* Remove the source from the context's source and then
1272 * add it back so it is sorted in the correct plcae
1274 g_source_list_remove (source, source->context);
1275 g_source_list_add (source, source->context);
1277 if (!SOURCE_BLOCKED (source))
1279 tmp_list = source->poll_fds;
1282 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1283 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1285 tmp_list = tmp_list->next;
1289 UNLOCK_CONTEXT (source->context);
1294 * g_source_get_priority:
1295 * @source: a #GSource
1297 * Gets the priority of a source.
1299 * Return value: the priority of the source
1302 g_source_get_priority (GSource *source)
1304 g_return_val_if_fail (source != NULL, 0);
1306 return source->priority;
1310 * g_source_set_can_recurse:
1311 * @source: a #GSource
1312 * @can_recurse: whether recursion is allowed for this source
1314 * Sets whether a source can be called recursively. If @can_recurse is
1315 * %TRUE, then while the source is being dispatched then this source
1316 * will be processed normally. Otherwise, all processing of this
1317 * source is blocked until the dispatch function returns.
1320 g_source_set_can_recurse (GSource *source,
1321 gboolean can_recurse)
1323 GMainContext *context;
1325 g_return_if_fail (source != NULL);
1327 context = source->context;
1330 LOCK_CONTEXT (context);
1333 source->flags |= G_SOURCE_CAN_RECURSE;
1335 source->flags &= ~G_SOURCE_CAN_RECURSE;
1338 UNLOCK_CONTEXT (context);
1342 * g_source_get_can_recurse:
1343 * @source: a #GSource
1345 * Checks whether a source is allowed to be called recursively.
1346 * see g_source_set_can_recurse().
1348 * Return value: whether recursion is allowed.
1351 g_source_get_can_recurse (GSource *source)
1353 g_return_val_if_fail (source != NULL, FALSE);
1355 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1360 * g_source_set_name:
1361 * @source: a #GSource
1362 * @name: debug name for the source
1364 * Sets a name for the source, used in debugging and profiling.
1365 * The name defaults to #NULL.
1367 * The source name should describe in a human-readable way
1368 * what the source does. For example, "X11 event queue"
1369 * or "GTK+ repaint idle handler" or whatever it is.
1371 * It is permitted to call this function multiple times, but is not
1372 * recommended due to the potential performance impact. For example,
1373 * one could change the name in the "check" function of a #GSourceFuncs
1374 * to include details like the event type in the source name.
1379 g_source_set_name (GSource *source,
1382 g_return_if_fail (source != NULL);
1384 /* setting back to NULL is allowed, just because it's
1385 * weird if get_name can return NULL but you can't
1389 g_free (source->name);
1390 source->name = g_strdup (name);
1394 * g_source_get_name:
1395 * @source: a #GSource
1397 * Gets a name for the source, used in debugging and profiling.
1398 * The name may be #NULL if it has never been set with
1399 * g_source_set_name().
1401 * Return value: the name of the source
1404 G_CONST_RETURN char*
1405 g_source_get_name (GSource *source)
1407 g_return_val_if_fail (source != NULL, NULL);
1409 return source->name;
1413 * g_source_set_name_by_id:
1414 * @tag: a #GSource ID
1415 * @name: debug name for the source
1417 * Sets the name of a source using its ID.
1419 * This is a convenience utility to set source names from the return
1420 * value of g_idle_add(), g_timeout_add(), etc.
1425 g_source_set_name_by_id (guint tag,
1430 g_return_if_fail (tag > 0);
1432 source = g_main_context_find_source_by_id (NULL, tag);
1436 g_source_set_name (source, name);
1442 * @source: a #GSource
1444 * Increases the reference count on a source by one.
1446 * Return value: @source
1449 g_source_ref (GSource *source)
1451 GMainContext *context;
1453 g_return_val_if_fail (source != NULL, NULL);
1455 context = source->context;
1458 LOCK_CONTEXT (context);
1460 source->ref_count++;
1463 UNLOCK_CONTEXT (context);
1468 /* g_source_unref() but possible to call within context lock
1471 g_source_unref_internal (GSource *source,
1472 GMainContext *context,
1475 gpointer old_cb_data = NULL;
1476 GSourceCallbackFuncs *old_cb_funcs = NULL;
1478 g_return_if_fail (source != NULL);
1480 if (!have_lock && context)
1481 LOCK_CONTEXT (context);
1483 source->ref_count--;
1484 if (source->ref_count == 0)
1486 old_cb_data = source->callback_data;
1487 old_cb_funcs = source->callback_funcs;
1489 source->callback_data = NULL;
1490 source->callback_funcs = NULL;
1492 if (context && !SOURCE_DESTROYED (source))
1494 g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1495 source->ref_count++;
1498 g_source_list_remove (source, context);
1500 if (source->source_funcs->finalize)
1501 source->source_funcs->finalize (source);
1503 g_free (source->name);
1504 source->name = NULL;
1506 g_slist_free (source->poll_fds);
1507 source->poll_fds = NULL;
1511 if (!have_lock && context)
1512 UNLOCK_CONTEXT (context);
1517 UNLOCK_CONTEXT (context);
1519 old_cb_funcs->unref (old_cb_data);
1522 LOCK_CONTEXT (context);
1528 * @source: a #GSource
1530 * Decreases the reference count of a source by one. If the
1531 * resulting reference count is zero the source and associated
1532 * memory will be destroyed.
1535 g_source_unref (GSource *source)
1537 g_return_if_fail (source != NULL);
1539 g_source_unref_internal (source, source->context, FALSE);
1543 * g_main_context_find_source_by_id:
1544 * @context: a #GMainContext (if %NULL, the default context will be used)
1545 * @source_id: the source ID, as returned by g_source_get_id().
1547 * Finds a #GSource given a pair of context and ID.
1549 * Return value: the #GSource if found, otherwise, %NULL
1552 g_main_context_find_source_by_id (GMainContext *context,
1557 g_return_val_if_fail (source_id > 0, NULL);
1559 if (context == NULL)
1560 context = g_main_context_default ();
1562 LOCK_CONTEXT (context);
1564 source = context->source_list;
1567 if (!SOURCE_DESTROYED (source) &&
1568 source->source_id == source_id)
1570 source = source->next;
1573 UNLOCK_CONTEXT (context);
1579 * g_main_context_find_source_by_funcs_user_data:
1580 * @context: a #GMainContext (if %NULL, the default context will be used).
1581 * @funcs: the @source_funcs passed to g_source_new().
1582 * @user_data: the user data from the callback.
1584 * Finds a source with the given source functions and user data. If
1585 * multiple sources exist with the same source function and user data,
1586 * the first one found will be returned.
1588 * Return value: the source, if one was found, otherwise %NULL
1591 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1592 GSourceFuncs *funcs,
1597 g_return_val_if_fail (funcs != NULL, NULL);
1599 if (context == NULL)
1600 context = g_main_context_default ();
1602 LOCK_CONTEXT (context);
1604 source = context->source_list;
1607 if (!SOURCE_DESTROYED (source) &&
1608 source->source_funcs == funcs &&
1609 source->callback_funcs)
1611 GSourceFunc callback;
1612 gpointer callback_data;
1614 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1616 if (callback_data == user_data)
1619 source = source->next;
1622 UNLOCK_CONTEXT (context);
1628 * g_main_context_find_source_by_user_data:
1629 * @context: a #GMainContext
1630 * @user_data: the user_data for the callback.
1632 * Finds a source with the given user data for the callback. If
1633 * multiple sources exist with the same user data, the first
1634 * one found will be returned.
1636 * Return value: the source, if one was found, otherwise %NULL
1639 g_main_context_find_source_by_user_data (GMainContext *context,
1644 if (context == NULL)
1645 context = g_main_context_default ();
1647 LOCK_CONTEXT (context);
1649 source = context->source_list;
1652 if (!SOURCE_DESTROYED (source) &&
1653 source->callback_funcs)
1655 GSourceFunc callback;
1656 gpointer callback_data = NULL;
1658 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1660 if (callback_data == user_data)
1663 source = source->next;
1666 UNLOCK_CONTEXT (context);
1673 * @tag: the ID of the source to remove.
1675 * Removes the source with the given id from the default main context.
1677 * a #GSource is given by g_source_get_id(), or will be returned by the
1678 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1679 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1680 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1682 * See also g_source_destroy(). You must use g_source_destroy() for sources
1683 * added to a non-default main context.
1685 * Return value: %TRUE if the source was found and removed.
1688 g_source_remove (guint tag)
1692 g_return_val_if_fail (tag > 0, FALSE);
1694 source = g_main_context_find_source_by_id (NULL, tag);
1696 g_source_destroy (source);
1698 return source != NULL;
1702 * g_source_remove_by_user_data:
1703 * @user_data: the user_data for the callback.
1705 * Removes a source from the default main loop context given the user
1706 * data for the callback. If multiple sources exist with the same user
1707 * data, only one will be destroyed.
1709 * Return value: %TRUE if a source was found and removed.
1712 g_source_remove_by_user_data (gpointer user_data)
1716 source = g_main_context_find_source_by_user_data (NULL, user_data);
1719 g_source_destroy (source);
1727 * g_source_remove_by_funcs_user_data:
1728 * @funcs: The @source_funcs passed to g_source_new()
1729 * @user_data: the user data for the callback
1731 * Removes a source from the default main loop context given the
1732 * source functions and user data. If multiple sources exist with the
1733 * same source functions and user data, only one will be destroyed.
1735 * Return value: %TRUE if a source was found and removed.
1738 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1743 g_return_val_if_fail (funcs != NULL, FALSE);
1745 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1748 g_source_destroy (source);
1756 * g_get_current_time:
1757 * @result: #GTimeVal structure in which to store current time.
1759 * Equivalent to the UNIX gettimeofday() function, but portable.
1762 g_get_current_time (GTimeVal *result)
1767 g_return_if_fail (result != NULL);
1769 /*this is required on alpha, there the timeval structs are int's
1770 not longs and a cast only would fail horribly*/
1771 gettimeofday (&r, NULL);
1772 result->tv_sec = r.tv_sec;
1773 result->tv_usec = r.tv_usec;
1778 g_return_if_fail (result != NULL);
1780 GetSystemTimeAsFileTime (&ft);
1781 memmove (&time64, &ft, sizeof (FILETIME));
1783 /* Convert from 100s of nanoseconds since 1601-01-01
1784 * to Unix epoch. Yes, this is Y2038 unsafe.
1786 time64 -= G_GINT64_CONSTANT (116444736000000000);
1789 result->tv_sec = time64 / 1000000;
1790 result->tv_usec = time64 % 1000000;
1795 g_main_dispatch_free (gpointer dispatch)
1797 g_slice_free (GMainDispatch, dispatch);
1800 /* Running the main loop */
1802 static GMainDispatch *
1805 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
1806 GMainDispatch *dispatch = g_static_private_get (&depth_private);
1809 dispatch = g_slice_new0 (GMainDispatch);
1810 g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
1819 * Returns the depth of the stack of calls to
1820 * g_main_context_dispatch() on any #GMainContext in the current thread.
1821 * That is, when called from the toplevel, it gives 0. When
1822 * called from within a callback from g_main_context_iteration()
1823 * (or g_main_loop_run(), etc.) it returns 1. When called from within
1824 * a callback to a recursive call to g_main_context_iterate(),
1825 * it returns 2. And so forth.
1827 * This function is useful in a situation like the following:
1828 * Imagine an extremely simple "garbage collected" system.
1831 * static GList *free_list;
1834 * allocate_memory (gsize size)
1836 * gpointer result = g_malloc (size);
1837 * free_list = g_list_prepend (free_list, result);
1842 * free_allocated_memory (void)
1845 * for (l = free_list; l; l = l->next);
1847 * g_list_free (free_list);
1855 * g_main_context_iteration (NULL, TRUE);
1856 * free_allocated_memory();
1860 * This works from an application, however, if you want to do the same
1861 * thing from a library, it gets more difficult, since you no longer
1862 * control the main loop. You might think you can simply use an idle
1863 * function to make the call to free_allocated_memory(), but that
1864 * doesn't work, since the idle function could be called from a
1865 * recursive callback. This can be fixed by using g_main_depth()
1869 * allocate_memory (gsize size)
1871 * FreeListBlock *block = g_new (FreeListBlock, 1);
1872 * block->mem = g_malloc (size);
1873 * block->depth = g_main_depth ();
1874 * free_list = g_list_prepend (free_list, block);
1875 * return block->mem;
1879 * free_allocated_memory (void)
1883 * int depth = g_main_depth ();
1884 * for (l = free_list; l; );
1886 * GList *next = l->next;
1887 * FreeListBlock *block = l->data;
1888 * if (block->depth > depth)
1890 * g_free (block->mem);
1892 * free_list = g_list_delete_link (free_list, l);
1900 * There is a temptation to use g_main_depth() to solve
1901 * problems with reentrancy. For instance, while waiting for data
1902 * to be received from the network in response to a menu item,
1903 * the menu item might be selected again. It might seem that
1904 * one could make the menu item's callback return immediately
1905 * and do nothing if g_main_depth() returns a value greater than 1.
1906 * However, this should be avoided since the user then sees selecting
1907 * the menu item do nothing. Furthermore, you'll find yourself adding
1908 * these checks all over your code, since there are doubtless many,
1909 * many things that the user could do. Instead, you can use the
1910 * following techniques:
1915 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
1916 * the user from interacting with elements while the main
1917 * loop is recursing.
1922 * Avoid main loop recursion in situations where you can't handle
1923 * arbitrary callbacks. Instead, structure your code so that you
1924 * simply return to the main loop and then get called again when
1925 * there is more work to do.
1930 * Return value: The main loop recursion level in the current thread
1935 GMainDispatch *dispatch = get_dispatch ();
1936 return dispatch->depth;
1940 * g_main_current_source:
1942 * Returns the currently firing source for this thread.
1944 * Return value: The currently firing source or %NULL.
1949 g_main_current_source (void)
1951 GMainDispatch *dispatch = get_dispatch ();
1952 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
1956 * g_source_is_destroyed:
1957 * @source: a #GSource
1959 * Returns whether @source has been destroyed.
1961 * This is important when you operate upon your objects
1962 * from within idle handlers, but may have freed the object
1963 * before the dispatch of your idle handler.
1967 * idle_callback (gpointer data)
1969 * SomeWidget *self = data;
1971 * GDK_THREADS_ENTER (<!-- -->);
1972 * /<!-- -->* do stuff with self *<!-- -->/
1973 * self->idle_id = 0;
1974 * GDK_THREADS_LEAVE (<!-- -->);
1980 * some_widget_do_stuff_later (SomeWidget *self)
1982 * self->idle_id = g_idle_add (idle_callback, self);
1986 * some_widget_finalize (GObject *object)
1988 * SomeWidget *self = SOME_WIDGET (object);
1990 * if (self->idle_id)
1991 * g_source_remove (self->idle_id);
1993 * G_OBJECT_CLASS (parent_class)->finalize (object);
1997 * This will fail in a multi-threaded application if the
1998 * widget is destroyed before the idle handler fires due
1999 * to the use after free in the callback. A solution, to
2000 * this particular problem, is to check to if the source
2001 * has already been destroy within the callback.
2005 * idle_callback (gpointer data)
2007 * SomeWidget *self = data;
2009 * GDK_THREADS_ENTER ();
2010 * if (!g_source_is_destroyed (g_main_current_source ()))
2012 * /<!-- -->* do stuff with self *<!-- -->/
2014 * GDK_THREADS_LEAVE ();
2020 * Return value: %TRUE if the source has been destroyed
2025 g_source_is_destroyed (GSource *source)
2027 return SOURCE_DESTROYED (source);
2030 /* Temporarily remove all this source's file descriptors from the
2031 * poll(), so that if data comes available for one of the file descriptors
2032 * we don't continually spin in the poll()
2034 /* HOLDS: source->context's lock */
2036 block_source (GSource *source)
2040 g_return_if_fail (!SOURCE_BLOCKED (source));
2042 tmp_list = source->poll_fds;
2045 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2046 tmp_list = tmp_list->next;
2050 /* HOLDS: source->context's lock */
2052 unblock_source (GSource *source)
2056 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
2057 g_return_if_fail (!SOURCE_DESTROYED (source));
2059 tmp_list = source->poll_fds;
2062 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2063 tmp_list = tmp_list->next;
2067 /* HOLDS: context's lock */
2069 g_main_dispatch (GMainContext *context)
2071 GMainDispatch *current = get_dispatch ();
2074 for (i = 0; i < context->pending_dispatches->len; i++)
2076 GSource *source = context->pending_dispatches->pdata[i];
2078 context->pending_dispatches->pdata[i] = NULL;
2081 source->flags &= ~G_SOURCE_READY;
2083 if (!SOURCE_DESTROYED (source))
2085 gboolean was_in_call;
2086 gpointer user_data = NULL;
2087 GSourceFunc callback = NULL;
2088 GSourceCallbackFuncs *cb_funcs;
2090 gboolean need_destroy;
2092 gboolean (*dispatch) (GSource *,
2095 GSList current_source_link;
2097 dispatch = source->source_funcs->dispatch;
2098 cb_funcs = source->callback_funcs;
2099 cb_data = source->callback_data;
2102 cb_funcs->ref (cb_data);
2104 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2105 block_source (source);
2107 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2108 source->flags |= G_HOOK_FLAG_IN_CALL;
2111 cb_funcs->get (cb_data, source, &callback, &user_data);
2113 UNLOCK_CONTEXT (context);
2116 /* The on-stack allocation of the GSList is unconventional, but
2117 * we know that the lifetime of the link is bounded to this
2118 * function as the link is kept in a thread specific list and
2119 * not manipulated outside of this function and its descendants.
2120 * Avoiding the overhead of a g_slist_alloc() is useful as many
2121 * applications do little more than dispatch events.
2123 * This is a performance hack - do not revert to g_slist_prepend()!
2125 current_source_link.data = source;
2126 current_source_link.next = current->dispatching_sources;
2127 current->dispatching_sources = ¤t_source_link;
2128 need_destroy = ! dispatch (source,
2131 g_assert (current->dispatching_sources == ¤t_source_link);
2132 current->dispatching_sources = current_source_link.next;
2136 cb_funcs->unref (cb_data);
2138 LOCK_CONTEXT (context);
2141 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2143 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2144 !SOURCE_DESTROYED (source))
2145 unblock_source (source);
2147 /* Note: this depends on the fact that we can't switch
2148 * sources from one main context to another
2150 if (need_destroy && !SOURCE_DESTROYED (source))
2152 g_assert (source->context == context);
2153 g_source_destroy_internal (source, context, TRUE);
2157 SOURCE_UNREF (source, context);
2160 g_ptr_array_set_size (context->pending_dispatches, 0);
2163 /* Holds context's lock */
2164 static inline GSource *
2165 next_valid_source (GMainContext *context,
2168 GSource *new_source = source ? source->next : context->source_list;
2172 if (!SOURCE_DESTROYED (new_source))
2174 new_source->ref_count++;
2178 new_source = new_source->next;
2182 SOURCE_UNREF (source, context);
2188 * g_main_context_acquire:
2189 * @context: a #GMainContext
2191 * Tries to become the owner of the specified context.
2192 * If some other thread is the owner of the context,
2193 * returns %FALSE immediately. Ownership is properly
2194 * recursive: the owner can require ownership again
2195 * and will release ownership when g_main_context_release()
2196 * is called as many times as g_main_context_acquire().
2198 * You must be the owner of a context before you
2199 * can call g_main_context_prepare(), g_main_context_query(),
2200 * g_main_context_check(), g_main_context_dispatch().
2202 * Return value: %TRUE if the operation succeeded, and
2203 * this thread is now the owner of @context.
2206 g_main_context_acquire (GMainContext *context)
2208 #ifdef G_THREADS_ENABLED
2209 gboolean result = FALSE;
2210 GThread *self = G_THREAD_SELF;
2212 if (context == NULL)
2213 context = g_main_context_default ();
2215 LOCK_CONTEXT (context);
2217 if (!context->owner)
2219 context->owner = self;
2220 g_assert (context->owner_count == 0);
2223 if (context->owner == self)
2225 context->owner_count++;
2229 UNLOCK_CONTEXT (context);
2232 #else /* !G_THREADS_ENABLED */
2234 #endif /* G_THREADS_ENABLED */
2238 * g_main_context_release:
2239 * @context: a #GMainContext
2241 * Releases ownership of a context previously acquired by this thread
2242 * with g_main_context_acquire(). If the context was acquired multiple
2243 * times, the ownership will be released only when g_main_context_release()
2244 * is called as many times as it was acquired.
2247 g_main_context_release (GMainContext *context)
2249 #ifdef G_THREADS_ENABLED
2250 if (context == NULL)
2251 context = g_main_context_default ();
2253 LOCK_CONTEXT (context);
2255 context->owner_count--;
2256 if (context->owner_count == 0)
2258 context->owner = NULL;
2260 if (context->waiters)
2262 GMainWaiter *waiter = context->waiters->data;
2263 gboolean loop_internal_waiter =
2264 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
2265 context->waiters = g_slist_delete_link (context->waiters,
2267 if (!loop_internal_waiter)
2268 g_mutex_lock (waiter->mutex);
2270 g_cond_signal (waiter->cond);
2272 if (!loop_internal_waiter)
2273 g_mutex_unlock (waiter->mutex);
2277 UNLOCK_CONTEXT (context);
2278 #endif /* G_THREADS_ENABLED */
2282 * g_main_context_wait:
2283 * @context: a #GMainContext
2284 * @cond: a condition variable
2285 * @mutex: a mutex, currently held
2287 * Tries to become the owner of the specified context,
2288 * as with g_main_context_acquire(). But if another thread
2289 * is the owner, atomically drop @mutex and wait on @cond until
2290 * that owner releases ownership or until @cond is signaled, then
2291 * try again (once) to become the owner.
2293 * Return value: %TRUE if the operation succeeded, and
2294 * this thread is now the owner of @context.
2297 g_main_context_wait (GMainContext *context,
2301 #ifdef G_THREADS_ENABLED
2302 gboolean result = FALSE;
2303 GThread *self = G_THREAD_SELF;
2304 gboolean loop_internal_waiter;
2306 if (context == NULL)
2307 context = g_main_context_default ();
2309 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2311 if (!loop_internal_waiter)
2312 LOCK_CONTEXT (context);
2314 if (context->owner && context->owner != self)
2319 waiter.mutex = mutex;
2321 context->waiters = g_slist_append (context->waiters, &waiter);
2323 if (!loop_internal_waiter)
2324 UNLOCK_CONTEXT (context);
2325 g_cond_wait (cond, mutex);
2326 if (!loop_internal_waiter)
2327 LOCK_CONTEXT (context);
2329 context->waiters = g_slist_remove (context->waiters, &waiter);
2332 if (!context->owner)
2334 context->owner = self;
2335 g_assert (context->owner_count == 0);
2338 if (context->owner == self)
2340 context->owner_count++;
2344 if (!loop_internal_waiter)
2345 UNLOCK_CONTEXT (context);
2348 #else /* !G_THREADS_ENABLED */
2350 #endif /* G_THREADS_ENABLED */
2354 * g_main_context_prepare:
2355 * @context: a #GMainContext
2356 * @priority: location to store priority of highest priority
2357 * source already ready.
2359 * Prepares to poll sources within a main loop. The resulting information
2360 * for polling is determined by calling g_main_context_query ().
2362 * Return value: %TRUE if some source is ready to be dispatched
2366 g_main_context_prepare (GMainContext *context,
2371 gint current_priority = G_MAXINT;
2374 if (context == NULL)
2375 context = g_main_context_default ();
2377 LOCK_CONTEXT (context);
2379 context->time_is_current = FALSE;
2381 if (context->in_check_or_prepare)
2383 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2384 "prepare() member.");
2385 UNLOCK_CONTEXT (context);
2389 #ifdef G_THREADS_ENABLED
2390 if (context->poll_waiting)
2392 g_warning("g_main_context_prepare(): main loop already active in another thread");
2393 UNLOCK_CONTEXT (context);
2397 context->poll_waiting = TRUE;
2398 #endif /* G_THREADS_ENABLED */
2401 /* If recursing, finish up current dispatch, before starting over */
2402 if (context->pending_dispatches)
2405 g_main_dispatch (context, ¤t_time);
2407 UNLOCK_CONTEXT (context);
2412 /* If recursing, clear list of pending dispatches */
2414 for (i = 0; i < context->pending_dispatches->len; i++)
2416 if (context->pending_dispatches->pdata[i])
2417 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2419 g_ptr_array_set_size (context->pending_dispatches, 0);
2421 /* Prepare all sources */
2423 context->timeout = -1;
2425 source = next_valid_source (context, NULL);
2428 gint source_timeout = -1;
2430 if ((n_ready > 0) && (source->priority > current_priority))
2432 SOURCE_UNREF (source, context);
2435 if (SOURCE_BLOCKED (source))
2438 if (!(source->flags & G_SOURCE_READY))
2441 gboolean (*prepare) (GSource *source,
2444 prepare = source->source_funcs->prepare;
2445 context->in_check_or_prepare++;
2446 UNLOCK_CONTEXT (context);
2448 result = (*prepare) (source, &source_timeout);
2450 LOCK_CONTEXT (context);
2451 context->in_check_or_prepare--;
2454 source->flags |= G_SOURCE_READY;
2457 if (source->flags & G_SOURCE_READY)
2460 current_priority = source->priority;
2461 context->timeout = 0;
2464 if (source_timeout >= 0)
2466 if (context->timeout < 0)
2467 context->timeout = source_timeout;
2469 context->timeout = MIN (context->timeout, source_timeout);
2473 source = next_valid_source (context, source);
2476 UNLOCK_CONTEXT (context);
2479 *priority = current_priority;
2481 return (n_ready > 0);
2485 * g_main_context_query:
2486 * @context: a #GMainContext
2487 * @max_priority: maximum priority source to check
2488 * @timeout_: location to store timeout to be used in polling
2489 * @fds: location to store #GPollFD records that need to be polled.
2490 * @n_fds: length of @fds.
2492 * Determines information necessary to poll this main loop.
2494 * Return value: the number of records actually stored in @fds,
2495 * or, if more than @n_fds records need to be stored, the number
2496 * of records that need to be stored.
2499 g_main_context_query (GMainContext *context,
2508 LOCK_CONTEXT (context);
2510 pollrec = context->poll_records;
2512 while (pollrec && max_priority >= pollrec->priority)
2514 /* We need to include entries with fd->events == 0 in the array because
2515 * otherwise if the application changes fd->events behind our back and
2516 * makes it non-zero, we'll be out of sync when we check the fds[] array.
2517 * (Changing fd->events after adding an FD wasn't an anticipated use of
2518 * this API, but it occurs in practice.) */
2521 fds[n_poll].fd = pollrec->fd->fd;
2522 /* In direct contradiction to the Unix98 spec, IRIX runs into
2523 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2524 * flags in the events field of the pollfd while it should
2525 * just ignoring them. So we mask them out here.
2527 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2528 fds[n_poll].revents = 0;
2531 pollrec = pollrec->next;
2535 #ifdef G_THREADS_ENABLED
2536 context->poll_changed = FALSE;
2541 *timeout = context->timeout;
2543 context->time_is_current = FALSE;
2546 UNLOCK_CONTEXT (context);
2552 * g_main_context_check:
2553 * @context: a #GMainContext
2554 * @max_priority: the maximum numerical priority of sources to check
2555 * @fds: array of #GPollFD's that was passed to the last call to
2556 * g_main_context_query()
2557 * @n_fds: return value of g_main_context_query()
2559 * Passes the results of polling back to the main loop.
2561 * Return value: %TRUE if some sources are ready to be dispatched.
2564 g_main_context_check (GMainContext *context,
2574 LOCK_CONTEXT (context);
2576 if (context->in_check_or_prepare)
2578 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2579 "prepare() member.");
2580 UNLOCK_CONTEXT (context);
2584 #ifdef G_THREADS_ENABLED
2585 if (!context->poll_waiting)
2589 read (context->wake_up_pipe[0], &a, 1);
2593 context->poll_waiting = FALSE;
2595 /* If the set of poll file descriptors changed, bail out
2596 * and let the main loop rerun
2598 if (context->poll_changed)
2600 UNLOCK_CONTEXT (context);
2603 #endif /* G_THREADS_ENABLED */
2605 pollrec = context->poll_records;
2609 if (pollrec->fd->events)
2610 pollrec->fd->revents = fds[i].revents;
2612 pollrec = pollrec->next;
2616 source = next_valid_source (context, NULL);
2619 if ((n_ready > 0) && (source->priority > max_priority))
2621 SOURCE_UNREF (source, context);
2624 if (SOURCE_BLOCKED (source))
2627 if (!(source->flags & G_SOURCE_READY))
2630 gboolean (*check) (GSource *source);
2632 check = source->source_funcs->check;
2634 context->in_check_or_prepare++;
2635 UNLOCK_CONTEXT (context);
2637 result = (*check) (source);
2639 LOCK_CONTEXT (context);
2640 context->in_check_or_prepare--;
2643 source->flags |= G_SOURCE_READY;
2646 if (source->flags & G_SOURCE_READY)
2648 source->ref_count++;
2649 g_ptr_array_add (context->pending_dispatches, source);
2653 /* never dispatch sources with less priority than the first
2654 * one we choose to dispatch
2656 max_priority = source->priority;
2660 source = next_valid_source (context, source);
2663 UNLOCK_CONTEXT (context);
2669 * g_main_context_dispatch:
2670 * @context: a #GMainContext
2672 * Dispatches all pending sources.
2675 g_main_context_dispatch (GMainContext *context)
2677 LOCK_CONTEXT (context);
2679 if (context->pending_dispatches->len > 0)
2681 g_main_dispatch (context);
2684 UNLOCK_CONTEXT (context);
2687 /* HOLDS context lock */
2689 g_main_context_iterate (GMainContext *context,
2696 gboolean some_ready;
2697 gint nfds, allocated_nfds;
2698 GPollFD *fds = NULL;
2700 UNLOCK_CONTEXT (context);
2702 #ifdef G_THREADS_ENABLED
2703 if (!g_main_context_acquire (context))
2705 gboolean got_ownership;
2707 LOCK_CONTEXT (context);
2709 g_return_val_if_fail (g_thread_supported (), FALSE);
2715 context->cond = g_cond_new ();
2717 got_ownership = g_main_context_wait (context,
2719 g_static_mutex_get_mutex (&context->mutex));
2725 LOCK_CONTEXT (context);
2726 #endif /* G_THREADS_ENABLED */
2728 if (!context->cached_poll_array)
2730 context->cached_poll_array_size = context->n_poll_records;
2731 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2734 allocated_nfds = context->cached_poll_array_size;
2735 fds = context->cached_poll_array;
2737 UNLOCK_CONTEXT (context);
2739 g_main_context_prepare (context, &max_priority);
2741 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
2742 allocated_nfds)) > allocated_nfds)
2744 LOCK_CONTEXT (context);
2746 context->cached_poll_array_size = allocated_nfds = nfds;
2747 context->cached_poll_array = fds = g_new (GPollFD, nfds);
2748 UNLOCK_CONTEXT (context);
2754 g_main_context_poll (context, timeout, max_priority, fds, nfds);
2756 some_ready = g_main_context_check (context, max_priority, fds, nfds);
2759 g_main_context_dispatch (context);
2761 #ifdef G_THREADS_ENABLED
2762 g_main_context_release (context);
2763 #endif /* G_THREADS_ENABLED */
2765 LOCK_CONTEXT (context);
2771 * g_main_context_pending:
2772 * @context: a #GMainContext (if %NULL, the default context will be used)
2774 * Checks if any sources have pending events for the given context.
2776 * Return value: %TRUE if events are pending.
2779 g_main_context_pending (GMainContext *context)
2784 context = g_main_context_default();
2786 LOCK_CONTEXT (context);
2787 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
2788 UNLOCK_CONTEXT (context);
2794 * g_main_context_iteration:
2795 * @context: a #GMainContext (if %NULL, the default context will be used)
2796 * @may_block: whether the call may block.
2798 * Runs a single iteration for the given main loop. This involves
2799 * checking to see if any event sources are ready to be processed,
2800 * then if no events sources are ready and @may_block is %TRUE, waiting
2801 * for a source to become ready, then dispatching the highest priority
2802 * events sources that are ready. Otherwise, if @may_block is %FALSE
2803 * sources are not waited to become ready, only those highest priority
2804 * events sources will be dispatched (if any), that are ready at this
2805 * given moment without further waiting.
2807 * Note that even when @may_block is %TRUE, it is still possible for
2808 * g_main_context_iteration() to return %FALSE, since the the wait may
2809 * be interrupted for other reasons than an event source becoming ready.
2811 * Return value: %TRUE if events were dispatched.
2814 g_main_context_iteration (GMainContext *context, gboolean may_block)
2819 context = g_main_context_default();
2821 LOCK_CONTEXT (context);
2822 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
2823 UNLOCK_CONTEXT (context);
2830 * @context: a #GMainContext (if %NULL, the default context will be used).
2831 * @is_running: set to %TRUE to indicate that the loop is running. This
2832 * is not very important since calling g_main_loop_run() will set this to
2835 * Creates a new #GMainLoop structure.
2837 * Return value: a new #GMainLoop.
2840 g_main_loop_new (GMainContext *context,
2841 gboolean is_running)
2846 context = g_main_context_default();
2848 g_main_context_ref (context);
2850 loop = g_new0 (GMainLoop, 1);
2851 loop->context = context;
2852 loop->is_running = is_running != FALSE;
2853 loop->ref_count = 1;
2860 * @loop: a #GMainLoop
2862 * Increases the reference count on a #GMainLoop object by one.
2864 * Return value: @loop
2867 g_main_loop_ref (GMainLoop *loop)
2869 g_return_val_if_fail (loop != NULL, NULL);
2870 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2872 g_atomic_int_inc (&loop->ref_count);
2878 * g_main_loop_unref:
2879 * @loop: a #GMainLoop
2881 * Decreases the reference count on a #GMainLoop object by one. If
2882 * the result is zero, free the loop and free all associated memory.
2885 g_main_loop_unref (GMainLoop *loop)
2887 g_return_if_fail (loop != NULL);
2888 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2890 if (!g_atomic_int_dec_and_test (&loop->ref_count))
2893 g_main_context_unref (loop->context);
2899 * @loop: a #GMainLoop
2901 * Runs a main loop until g_main_loop_quit() is called on the loop.
2902 * If this is called for the thread of the loop's #GMainContext,
2903 * it will process events from the loop, otherwise it will
2907 g_main_loop_run (GMainLoop *loop)
2909 GThread *self = G_THREAD_SELF;
2911 g_return_if_fail (loop != NULL);
2912 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2914 #ifdef G_THREADS_ENABLED
2915 if (!g_main_context_acquire (loop->context))
2917 gboolean got_ownership = FALSE;
2919 /* Another thread owns this context */
2920 if (!g_thread_supported ())
2922 g_warning ("g_main_loop_run() was called from second thread but "
2923 "g_thread_init() was never called.");
2927 LOCK_CONTEXT (loop->context);
2929 g_atomic_int_inc (&loop->ref_count);
2931 if (!loop->is_running)
2932 loop->is_running = TRUE;
2934 if (!loop->context->cond)
2935 loop->context->cond = g_cond_new ();
2937 while (loop->is_running && !got_ownership)
2938 got_ownership = g_main_context_wait (loop->context,
2939 loop->context->cond,
2940 g_static_mutex_get_mutex (&loop->context->mutex));
2942 if (!loop->is_running)
2944 UNLOCK_CONTEXT (loop->context);
2946 g_main_context_release (loop->context);
2947 g_main_loop_unref (loop);
2951 g_assert (got_ownership);
2954 LOCK_CONTEXT (loop->context);
2955 #endif /* G_THREADS_ENABLED */
2957 if (loop->context->in_check_or_prepare)
2959 g_warning ("g_main_loop_run(): called recursively from within a source's "
2960 "check() or prepare() member, iteration not possible.");
2964 g_atomic_int_inc (&loop->ref_count);
2965 loop->is_running = TRUE;
2966 while (loop->is_running)
2967 g_main_context_iterate (loop->context, TRUE, TRUE, self);
2969 UNLOCK_CONTEXT (loop->context);
2971 #ifdef G_THREADS_ENABLED
2972 g_main_context_release (loop->context);
2973 #endif /* G_THREADS_ENABLED */
2975 g_main_loop_unref (loop);
2980 * @loop: a #GMainLoop
2982 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
2983 * for the loop will return.
2985 * Note that sources that have already been dispatched when
2986 * g_main_loop_quit() is called will still be executed.
2989 g_main_loop_quit (GMainLoop *loop)
2991 g_return_if_fail (loop != NULL);
2992 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2994 LOCK_CONTEXT (loop->context);
2995 loop->is_running = FALSE;
2996 g_main_context_wakeup_unlocked (loop->context);
2998 #ifdef G_THREADS_ENABLED
2999 if (loop->context->cond)
3000 g_cond_broadcast (loop->context->cond);
3001 #endif /* G_THREADS_ENABLED */
3003 UNLOCK_CONTEXT (loop->context);
3007 * g_main_loop_is_running:
3008 * @loop: a #GMainLoop.
3010 * Checks to see if the main loop is currently being run via g_main_loop_run().
3012 * Return value: %TRUE if the mainloop is currently being run.
3015 g_main_loop_is_running (GMainLoop *loop)
3017 g_return_val_if_fail (loop != NULL, FALSE);
3018 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3020 return loop->is_running;
3024 * g_main_loop_get_context:
3025 * @loop: a #GMainLoop.
3027 * Returns the #GMainContext of @loop.
3029 * Return value: the #GMainContext of @loop
3032 g_main_loop_get_context (GMainLoop *loop)
3034 g_return_val_if_fail (loop != NULL, NULL);
3035 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3037 return loop->context;
3040 /* HOLDS: context's lock */
3042 g_main_context_poll (GMainContext *context,
3048 #ifdef G_MAIN_POLL_DEBUG
3054 GPollFunc poll_func;
3056 if (n_fds || timeout != 0)
3058 #ifdef G_MAIN_POLL_DEBUG
3059 if (_g_main_poll_debug)
3061 g_print ("polling context=%p n=%d timeout=%d\n",
3062 context, n_fds, timeout);
3063 poll_timer = g_timer_new ();
3067 LOCK_CONTEXT (context);
3069 poll_func = context->poll_func;
3071 UNLOCK_CONTEXT (context);
3072 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3075 g_warning ("poll(2) failed due to: %s.",
3076 g_strerror (errno));
3078 /* If g_poll () returns -1, it has already called g_warning() */
3082 #ifdef G_MAIN_POLL_DEBUG
3083 if (_g_main_poll_debug)
3085 LOCK_CONTEXT (context);
3087 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3090 g_timer_elapsed (poll_timer, NULL));
3091 g_timer_destroy (poll_timer);
3092 pollrec = context->poll_records;
3094 while (pollrec != NULL)
3099 if (fds[i].fd == pollrec->fd->fd &&
3100 pollrec->fd->events &&
3103 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3104 if (fds[i].revents & G_IO_IN)
3106 if (fds[i].revents & G_IO_OUT)
3108 if (fds[i].revents & G_IO_PRI)
3110 if (fds[i].revents & G_IO_ERR)
3112 if (fds[i].revents & G_IO_HUP)
3114 if (fds[i].revents & G_IO_NVAL)
3120 pollrec = pollrec->next;
3124 UNLOCK_CONTEXT (context);
3127 } /* if (n_fds || timeout != 0) */
3131 * g_main_context_add_poll:
3132 * @context: a #GMainContext (or %NULL for the default context)
3133 * @fd: a #GPollFD structure holding information about a file
3134 * descriptor to watch.
3135 * @priority: the priority for this file descriptor which should be
3136 * the same as the priority used for g_source_attach() to ensure that the
3137 * file descriptor is polled whenever the results may be needed.
3139 * Adds a file descriptor to the set of file descriptors polled for
3140 * this context. This will very seldomly be used directly. Instead
3141 * a typical event source will use g_source_add_poll() instead.
3144 g_main_context_add_poll (GMainContext *context,
3149 context = g_main_context_default ();
3151 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3152 g_return_if_fail (fd);
3154 LOCK_CONTEXT (context);
3155 g_main_context_add_poll_unlocked (context, priority, fd);
3156 UNLOCK_CONTEXT (context);
3159 /* HOLDS: main_loop_lock */
3161 g_main_context_add_poll_unlocked (GMainContext *context,
3165 GPollRec *lastrec, *pollrec;
3166 GPollRec *newrec = g_slice_new (GPollRec);
3168 /* This file descriptor may be checked before we ever poll */
3171 newrec->priority = priority;
3174 pollrec = context->poll_records;
3175 while (pollrec && priority >= pollrec->priority)
3178 pollrec = pollrec->next;
3182 lastrec->next = newrec;
3184 context->poll_records = newrec;
3186 newrec->next = pollrec;
3188 context->n_poll_records++;
3190 #ifdef G_THREADS_ENABLED
3191 context->poll_changed = TRUE;
3193 /* Now wake up the main loop if it is waiting in the poll() */
3194 g_main_context_wakeup_unlocked (context);
3199 * g_main_context_remove_poll:
3200 * @context:a #GMainContext
3201 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3203 * Removes file descriptor from the set of file descriptors to be
3204 * polled for a particular context.
3207 g_main_context_remove_poll (GMainContext *context,
3211 context = g_main_context_default ();
3213 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3214 g_return_if_fail (fd);
3216 LOCK_CONTEXT (context);
3217 g_main_context_remove_poll_unlocked (context, fd);
3218 UNLOCK_CONTEXT (context);
3222 g_main_context_remove_poll_unlocked (GMainContext *context,
3225 GPollRec *pollrec, *lastrec;
3228 pollrec = context->poll_records;
3232 if (pollrec->fd == fd)
3234 if (lastrec != NULL)
3235 lastrec->next = pollrec->next;
3237 context->poll_records = pollrec->next;
3239 g_slice_free (GPollRec, pollrec);
3241 context->n_poll_records--;
3245 pollrec = pollrec->next;
3248 #ifdef G_THREADS_ENABLED
3249 context->poll_changed = TRUE;
3251 /* Now wake up the main loop if it is waiting in the poll() */
3252 g_main_context_wakeup_unlocked (context);
3257 * g_source_get_current_time:
3258 * @source: a #GSource
3259 * @timeval: #GTimeVal structure in which to store current time.
3261 * Gets the "current time" to be used when checking
3262 * this source. The advantage of calling this function over
3263 * calling g_get_current_time() directly is that when
3264 * checking multiple sources, GLib can cache a single value
3265 * instead of having to repeatedly get the system time.
3268 g_source_get_current_time (GSource *source,
3271 GMainContext *context;
3273 g_return_if_fail (source->context != NULL);
3275 context = source->context;
3277 LOCK_CONTEXT (context);
3279 if (!context->time_is_current)
3281 g_get_current_time (&context->current_time);
3282 context->time_is_current = TRUE;
3285 *timeval = context->current_time;
3287 UNLOCK_CONTEXT (context);
3291 * g_main_context_set_poll_func:
3292 * @context: a #GMainContext
3293 * @func: the function to call to poll all file descriptors
3295 * Sets the function to use to handle polling of file descriptors. It
3296 * will be used instead of the poll() system call
3297 * (or GLib's replacement function, which is used where
3298 * poll() isn't available).
3300 * This function could possibly be used to integrate the GLib event
3301 * loop with an external event loop.
3304 g_main_context_set_poll_func (GMainContext *context,
3308 context = g_main_context_default ();
3310 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3312 LOCK_CONTEXT (context);
3315 context->poll_func = func;
3317 context->poll_func = g_poll;
3319 UNLOCK_CONTEXT (context);
3323 * g_main_context_get_poll_func:
3324 * @context: a #GMainContext
3326 * Gets the poll function set by g_main_context_set_poll_func().
3328 * Return value: the poll function
3331 g_main_context_get_poll_func (GMainContext *context)
3336 context = g_main_context_default ();
3338 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3340 LOCK_CONTEXT (context);
3341 result = context->poll_func;
3342 UNLOCK_CONTEXT (context);
3347 /* HOLDS: context's lock */
3348 /* Wake the main loop up from a poll() */
3350 g_main_context_wakeup_unlocked (GMainContext *context)
3352 #ifdef G_THREADS_ENABLED
3353 if (g_thread_supported() && context->poll_waiting)
3355 context->poll_waiting = FALSE;
3357 write (context->wake_up_pipe[1], "A", 1);
3359 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
3366 * g_main_context_wakeup:
3367 * @context: a #GMainContext
3369 * If @context is currently waiting in a poll(), interrupt
3370 * the poll(), and continue the iteration process.
3373 g_main_context_wakeup (GMainContext *context)
3376 context = g_main_context_default ();
3378 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3380 LOCK_CONTEXT (context);
3381 g_main_context_wakeup_unlocked (context);
3382 UNLOCK_CONTEXT (context);
3386 * g_main_context_is_owner:
3387 * @context: a #GMainContext
3389 * Determines whether this thread holds the (recursive)
3390 * ownership of this #GMaincontext. This is useful to
3391 * know before waiting on another thread that may be
3392 * blocking to get ownership of @context.
3394 * Returns: %TRUE if current thread is owner of @context.
3399 g_main_context_is_owner (GMainContext *context)
3404 context = g_main_context_default ();
3406 #ifdef G_THREADS_ENABLED
3407 LOCK_CONTEXT (context);
3408 is_owner = context->owner == G_THREAD_SELF;
3409 UNLOCK_CONTEXT (context);
3420 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3421 GTimeVal *current_time)
3423 guint seconds = timeout_source->interval / 1000;
3424 guint msecs = timeout_source->interval - seconds * 1000;
3426 timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
3427 timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
3428 if (timeout_source->expiration.tv_usec >= 1000000)
3430 timeout_source->expiration.tv_usec -= 1000000;
3431 timeout_source->expiration.tv_sec++;
3433 if (timer_perturb==-1)
3436 * we want a per machine/session unique 'random' value; try the dbus
3437 * address first, that has a UUID in it. If there is no dbus, use the
3438 * hostname for hashing.
3440 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3441 if (!session_bus_address)
3442 session_bus_address = g_getenv ("HOSTNAME");
3443 if (session_bus_address)
3444 timer_perturb = ABS ((gint) g_str_hash (session_bus_address));
3448 if (timeout_source->granularity)
3451 gint gran; /* in usecs */
3454 gran = timeout_source->granularity * 1000;
3455 perturb = timer_perturb % gran;
3457 * We want to give each machine a per machine pertubation;
3458 * shift time back first, and forward later after the rounding
3461 timeout_source->expiration.tv_usec -= perturb;
3462 if (timeout_source->expiration.tv_usec < 0)
3464 timeout_source->expiration.tv_usec += 1000000;
3465 timeout_source->expiration.tv_sec--;
3468 remainder = timeout_source->expiration.tv_usec % gran;
3469 if (remainder >= gran/4) /* round up */
3470 timeout_source->expiration.tv_usec += gran;
3471 timeout_source->expiration.tv_usec -= remainder;
3473 timeout_source->expiration.tv_usec += perturb;
3475 /* the rounding may have overflown tv_usec */
3476 while (timeout_source->expiration.tv_usec > 1000000)
3478 timeout_source->expiration.tv_usec -= 1000000;
3479 timeout_source->expiration.tv_sec++;
3485 g_timeout_prepare (GSource *source,
3490 GTimeVal current_time;
3492 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3494 g_source_get_current_time (source, ¤t_time);
3496 sec = timeout_source->expiration.tv_sec - current_time.tv_sec;
3497 msec = (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000;
3499 /* We do the following in a rather convoluted fashion to deal with
3500 * the fact that we don't have an integral type big enough to hold
3501 * the difference of two timevals in millseconds.
3503 if (sec < 0 || (sec == 0 && msec < 0))
3507 glong interval_sec = timeout_source->interval / 1000;
3508 glong interval_msec = timeout_source->interval % 1000;
3516 if (sec > interval_sec ||
3517 (sec == interval_sec && msec > interval_msec))
3519 /* The system time has been set backwards, so we
3520 * reset the expiration time to now + timeout_source->interval;
3521 * this at least avoids hanging for long periods of time.
3523 g_timeout_set_expiration (timeout_source, ¤t_time);
3524 msec = MIN (G_MAXINT, timeout_source->interval);
3528 msec = MIN (G_MAXINT, (guint)msec + 1000 * (guint)sec);
3532 *timeout = (gint)msec;
3538 g_timeout_check (GSource *source)
3540 GTimeVal current_time;
3541 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3543 g_source_get_current_time (source, ¤t_time);
3545 return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
3546 ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
3547 (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
3551 g_timeout_dispatch (GSource *source,
3552 GSourceFunc callback,
3555 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3559 g_warning ("Timeout source dispatched without callback\n"
3560 "You must call g_source_set_callback().");
3564 if (callback (user_data))
3566 GTimeVal current_time;
3568 g_source_get_current_time (source, ¤t_time);
3569 g_timeout_set_expiration (timeout_source, ¤t_time);
3578 * g_timeout_source_new:
3579 * @interval: the timeout interval in milliseconds.
3581 * Creates a new timeout source.
3583 * The source will not initially be associated with any #GMainContext
3584 * and must be added to one with g_source_attach() before it will be
3587 * Return value: the newly-created timeout source
3590 g_timeout_source_new (guint interval)
3592 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3593 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3594 GTimeVal current_time;
3596 timeout_source->interval = interval;
3598 g_get_current_time (¤t_time);
3599 g_timeout_set_expiration (timeout_source, ¤t_time);
3605 * g_timeout_source_new_seconds:
3606 * @interval: the timeout interval in seconds
3608 * Creates a new timeout source.
3610 * The source will not initially be associated with any #GMainContext
3611 * and must be added to one with g_source_attach() before it will be
3614 * The scheduling granularity/accuracy of this timeout source will be
3617 * Return value: the newly-created timeout source
3622 g_timeout_source_new_seconds (guint interval)
3624 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3625 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3626 GTimeVal current_time;
3628 timeout_source->interval = 1000*interval;
3629 timeout_source->granularity = 1000;
3631 g_get_current_time (¤t_time);
3632 g_timeout_set_expiration (timeout_source, ¤t_time);
3639 * g_timeout_add_full:
3640 * @priority: the priority of the timeout source. Typically this will be in
3641 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3642 * @interval: the time between calls to the function, in milliseconds
3643 * (1/1000ths of a second)
3644 * @function: function to call
3645 * @data: data to pass to @function
3646 * @notify: function to call when the timeout is removed, or %NULL
3648 * Sets a function to be called at regular intervals, with the given
3649 * priority. The function is called repeatedly until it returns
3650 * %FALSE, at which point the timeout is automatically destroyed and
3651 * the function will not be called again. The @notify function is
3652 * called when the timeout is destroyed. The first call to the
3653 * function will be at the end of the first @interval.
3655 * Note that timeout functions may be delayed, due to the processing of other
3656 * event sources. Thus they should not be relied on for precise timing.
3657 * After each call to the timeout function, the time of the next
3658 * timeout is recalculated based on the current time and the given interval
3659 * (it does not try to 'catch up' time lost in delays).
3661 * This internally creates a main loop source using g_timeout_source_new()
3662 * and attaches it to the main loop context using g_source_attach(). You can
3663 * do these steps manually if you need greater control.
3665 * Return value: the ID (greater than 0) of the event source.
3668 g_timeout_add_full (gint priority,
3670 GSourceFunc function,
3672 GDestroyNotify notify)
3677 g_return_val_if_fail (function != NULL, 0);
3679 source = g_timeout_source_new (interval);
3681 if (priority != G_PRIORITY_DEFAULT)
3682 g_source_set_priority (source, priority);
3684 g_source_set_callback (source, function, data, notify);
3685 id = g_source_attach (source, NULL);
3686 g_source_unref (source);
3693 * @interval: the time between calls to the function, in milliseconds
3694 * (1/1000ths of a second)
3695 * @function: function to call
3696 * @data: data to pass to @function
3698 * Sets a function to be called at regular intervals, with the default
3699 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
3700 * until it returns %FALSE, at which point the timeout is automatically
3701 * destroyed and the function will not be called again. The first call
3702 * to the function will be at the end of the first @interval.
3704 * Note that timeout functions may be delayed, due to the processing of other
3705 * event sources. Thus they should not be relied on for precise timing.
3706 * After each call to the timeout function, the time of the next
3707 * timeout is recalculated based on the current time and the given interval
3708 * (it does not try to 'catch up' time lost in delays).
3710 * If you want to have a timer in the "seconds" range and do not care
3711 * about the exact time of the first call of the timer, use the
3712 * g_timeout_add_seconds() function; this function allows for more
3713 * optimizations and more efficient system power usage.
3715 * This internally creates a main loop source using g_timeout_source_new()
3716 * and attaches it to the main loop context using g_source_attach(). You can
3717 * do these steps manually if you need greater control.
3719 * Return value: the ID (greater than 0) of the event source.
3722 g_timeout_add (guint32 interval,
3723 GSourceFunc function,
3726 return g_timeout_add_full (G_PRIORITY_DEFAULT,
3727 interval, function, data, NULL);
3731 * g_timeout_add_seconds_full:
3732 * @priority: the priority of the timeout source. Typically this will be in
3733 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3734 * @interval: the time between calls to the function, in seconds
3735 * @function: function to call
3736 * @data: data to pass to @function
3737 * @notify: function to call when the timeout is removed, or %NULL
3739 * Sets a function to be called at regular intervals, with @priority.
3740 * The function is called repeatedly until it returns %FALSE, at which
3741 * point the timeout is automatically destroyed and the function will
3742 * not be called again.
3744 * Unlike g_timeout_add(), this function operates at whole second granularity.
3745 * The initial starting point of the timer is determined by the implementation
3746 * and the implementation is expected to group multiple timers together so that
3747 * they fire all at the same time.
3748 * To allow this grouping, the @interval to the first timer is rounded
3749 * and can deviate up to one second from the specified interval.
3750 * Subsequent timer iterations will generally run at the specified interval.
3752 * Note that timeout functions may be delayed, due to the processing of other
3753 * event sources. Thus they should not be relied on for precise timing.
3754 * After each call to the timeout function, the time of the next
3755 * timeout is recalculated based on the current time and the given @interval
3757 * If you want timing more precise than whole seconds, use g_timeout_add()
3760 * The grouping of timers to fire at the same time results in a more power
3761 * and CPU efficient behavior so if your timer is in multiples of seconds
3762 * and you don't require the first timer exactly one second from now, the
3763 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
3765 * This internally creates a main loop source using
3766 * g_timeout_source_new_seconds() and attaches it to the main loop context
3767 * using g_source_attach(). You can do these steps manually if you need
3770 * Return value: the ID (greater than 0) of the event source.
3775 g_timeout_add_seconds_full (gint priority,
3777 GSourceFunc function,
3779 GDestroyNotify notify)
3784 g_return_val_if_fail (function != NULL, 0);
3786 source = g_timeout_source_new_seconds (interval);
3788 if (priority != G_PRIORITY_DEFAULT)
3789 g_source_set_priority (source, priority);
3791 g_source_set_callback (source, function, data, notify);
3792 id = g_source_attach (source, NULL);
3793 g_source_unref (source);
3799 * g_timeout_add_seconds:
3800 * @interval: the time between calls to the function, in seconds
3801 * @function: function to call
3802 * @data: data to pass to @function
3804 * Sets a function to be called at regular intervals with the default
3805 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
3806 * it returns %FALSE, at which point the timeout is automatically destroyed
3807 * and the function will not be called again.
3809 * This internally creates a main loop source using
3810 * g_timeout_source_new_seconds() and attaches it to the main loop context
3811 * using g_source_attach(). You can do these steps manually if you need
3812 * greater control. Also see g_timout_add_seconds_full().
3814 * Return value: the ID (greater than 0) of the event source.
3819 g_timeout_add_seconds (guint interval,
3820 GSourceFunc function,
3823 g_return_val_if_fail (function != NULL, 0);
3825 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
3828 /* Child watch functions */
3833 g_child_watch_prepare (GSource *source,
3842 g_child_watch_check (GSource *source)
3844 GChildWatchSource *child_watch_source;
3845 gboolean child_exited;
3847 child_watch_source = (GChildWatchSource *) source;
3849 child_exited = child_watch_source->poll.revents & G_IO_IN;
3856 * Note: We do _not_ check for the special value of STILL_ACTIVE
3857 * since we know that the process has exited and doing so runs into
3858 * problems if the child process "happens to return STILL_ACTIVE(259)"
3859 * as Microsoft's Platform SDK puts it.
3861 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
3863 gchar *emsg = g_win32_error_message (GetLastError ());
3864 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
3867 child_watch_source->child_status = -1;
3870 child_watch_source->child_status = child_status;
3873 return child_exited;
3876 #else /* G_OS_WIN32 */
3879 check_for_child_exited (GSource *source)
3881 GChildWatchSource *child_watch_source;
3884 /* protect against another SIGCHLD in the middle of this call */
3885 count = child_watch_count;
3887 child_watch_source = (GChildWatchSource *) source;
3889 if (child_watch_source->child_exited)
3892 if (child_watch_source->count < count)
3896 if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
3898 child_watch_source->child_status = child_status;
3899 child_watch_source->child_exited = TRUE;
3901 child_watch_source->count = count;
3904 return child_watch_source->child_exited;
3908 g_child_watch_prepare (GSource *source,
3913 return check_for_child_exited (source);
3918 g_child_watch_check (GSource *source)
3920 return check_for_child_exited (source);
3923 #endif /* G_OS_WIN32 */
3926 g_child_watch_dispatch (GSource *source,
3927 GSourceFunc callback,
3930 GChildWatchSource *child_watch_source;
3931 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
3933 child_watch_source = (GChildWatchSource *) source;
3937 g_warning ("Child watch source dispatched without callback\n"
3938 "You must call g_source_set_callback().");
3942 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
3944 /* We never keep a child watch source around as the child is gone */
3951 g_child_watch_signal_handler (int signum)
3953 child_watch_count ++;
3955 if (child_watch_init_state == CHILD_WATCH_INITIALIZED_THREADED)
3957 write (child_watch_wake_up_pipe[1], "B", 1);
3961 /* We count on the signal interrupting the poll in the same thread.
3967 g_child_watch_source_init_single (void)
3969 struct sigaction action;
3971 g_assert (! g_thread_supported());
3972 g_assert (child_watch_init_state == CHILD_WATCH_UNINITIALIZED);
3974 child_watch_init_state = CHILD_WATCH_INITIALIZED_SINGLE;
3976 action.sa_handler = g_child_watch_signal_handler;
3977 sigemptyset (&action.sa_mask);
3978 action.sa_flags = SA_NOCLDSTOP;
3979 sigaction (SIGCHLD, &action, NULL);
3982 G_GNUC_NORETURN static gpointer
3983 child_watch_helper_thread (gpointer data)
3990 read (child_watch_wake_up_pipe[0], b, 20);
3992 /* We were woken up. Wake up all other contexts in all other threads */
3993 G_LOCK (main_context_list);
3994 for (list = main_context_list; list; list = list->next)
3996 GMainContext *context;
3998 context = list->data;
3999 if (g_atomic_int_get (&context->ref_count) > 0)
4000 /* Due to racing conditions we can find ref_count == 0, in
4001 * that case, however, the context is still not destroyed
4002 * and no poll can be active, otherwise the ref_count
4004 g_main_context_wakeup (context);
4006 G_UNLOCK (main_context_list);
4011 g_child_watch_source_init_multi_threaded (void)
4013 GError *error = NULL;
4014 struct sigaction action;
4016 g_assert (g_thread_supported());
4018 if (pipe (child_watch_wake_up_pipe) < 0)
4019 g_error ("Cannot create wake up pipe: %s\n", g_strerror (errno));
4020 fcntl (child_watch_wake_up_pipe[1], F_SETFL, O_NONBLOCK | fcntl (child_watch_wake_up_pipe[1], F_GETFL));
4022 /* We create a helper thread that polls on the wakeup pipe indefinitely */
4023 /* FIXME: Think this through for races */
4024 if (g_thread_create (child_watch_helper_thread, NULL, FALSE, &error) == NULL)
4025 g_error ("Cannot create a thread to monitor child exit status: %s\n", error->message);
4026 child_watch_init_state = CHILD_WATCH_INITIALIZED_THREADED;
4028 action.sa_handler = g_child_watch_signal_handler;
4029 sigemptyset (&action.sa_mask);
4030 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4031 sigaction (SIGCHLD, &action, NULL);
4035 g_child_watch_source_init_promote_single_to_threaded (void)
4037 g_child_watch_source_init_multi_threaded ();
4041 g_child_watch_source_init (void)
4043 if (g_thread_supported())
4045 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
4046 g_child_watch_source_init_multi_threaded ();
4047 else if (child_watch_init_state == CHILD_WATCH_INITIALIZED_SINGLE)
4048 g_child_watch_source_init_promote_single_to_threaded ();
4052 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
4053 g_child_watch_source_init_single ();
4057 #endif /* !G_OS_WIN32 */
4060 * g_child_watch_source_new:
4061 * @pid: process to watch. On POSIX the pid of a child process. On
4062 * Windows a handle for a process (which doesn't have to be a child).
4064 * Creates a new child_watch source.
4066 * The source will not initially be associated with any #GMainContext
4067 * and must be added to one with g_source_attach() before it will be
4070 * Note that child watch sources can only be used in conjunction with
4071 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4074 * Note that on platforms where #GPid must be explicitly closed
4075 * (see g_spawn_close_pid()) @pid must not be closed while the
4076 * source is still active. Typically, you will want to call
4077 * g_spawn_close_pid() in the callback function for the source.
4079 * Note further that using g_child_watch_source_new() is not
4080 * compatible with calling <literal>waitpid(-1)</literal> in
4081 * the application. Calling waitpid() for individual pids will
4084 * Return value: the newly-created child watch source
4089 g_child_watch_source_new (GPid pid)
4091 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4092 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4095 child_watch_source->poll.fd = (gintptr) pid;
4096 child_watch_source->poll.events = G_IO_IN;
4098 g_source_add_poll (source, &child_watch_source->poll);
4099 #else /* G_OS_WIN32 */
4100 g_child_watch_source_init ();
4101 #endif /* G_OS_WIN32 */
4103 child_watch_source->pid = pid;
4109 * g_child_watch_add_full:
4110 * @priority: the priority of the idle source. Typically this will be in the
4111 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4112 * @pid: process to watch. On POSIX the pid of a child process. On
4113 * Windows a handle for a process (which doesn't have to be a child).
4114 * @function: function to call
4115 * @data: data to pass to @function
4116 * @notify: function to call when the idle is removed, or %NULL
4118 * Sets a function to be called when the child indicated by @pid
4119 * exits, at the priority @priority.
4121 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4122 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4123 * the spawn function for the child watching to work.
4125 * Note that on platforms where #GPid must be explicitly closed
4126 * (see g_spawn_close_pid()) @pid must not be closed while the
4127 * source is still active. Typically, you will want to call
4128 * g_spawn_close_pid() in the callback function for the source.
4130 * GLib supports only a single callback per process id.
4132 * This internally creates a main loop source using
4133 * g_child_watch_source_new() and attaches it to the main loop context
4134 * using g_source_attach(). You can do these steps manually if you
4135 * need greater control.
4137 * Return value: the ID (greater than 0) of the event source.
4142 g_child_watch_add_full (gint priority,
4144 GChildWatchFunc function,
4146 GDestroyNotify notify)
4151 g_return_val_if_fail (function != NULL, 0);
4153 source = g_child_watch_source_new (pid);
4155 if (priority != G_PRIORITY_DEFAULT)
4156 g_source_set_priority (source, priority);
4158 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4159 id = g_source_attach (source, NULL);
4160 g_source_unref (source);
4166 * g_child_watch_add:
4167 * @pid: process id to watch. On POSIX the pid of a child process. On
4168 * Windows a handle for a process (which doesn't have to be a child).
4169 * @function: function to call
4170 * @data: data to pass to @function
4172 * Sets a function to be called when the child indicated by @pid
4173 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4175 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4176 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4177 * the spawn function for the child watching to work.
4179 * Note that on platforms where #GPid must be explicitly closed
4180 * (see g_spawn_close_pid()) @pid must not be closed while the
4181 * source is still active. Typically, you will want to call
4182 * g_spawn_close_pid() in the callback function for the source.
4184 * GLib supports only a single callback per process id.
4186 * This internally creates a main loop source using
4187 * g_child_watch_source_new() and attaches it to the main loop context
4188 * using g_source_attach(). You can do these steps manually if you
4189 * need greater control.
4191 * Return value: the ID (greater than 0) of the event source.
4196 g_child_watch_add (GPid pid,
4197 GChildWatchFunc function,
4200 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4204 /* Idle functions */
4207 g_idle_prepare (GSource *source,
4216 g_idle_check (GSource *source)
4222 g_idle_dispatch (GSource *source,
4223 GSourceFunc callback,
4228 g_warning ("Idle source dispatched without callback\n"
4229 "You must call g_source_set_callback().");
4233 return callback (user_data);
4237 * g_idle_source_new:
4239 * Creates a new idle source.
4241 * The source will not initially be associated with any #GMainContext
4242 * and must be added to one with g_source_attach() before it will be
4243 * executed. Note that the default priority for idle sources is
4244 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4245 * have a default priority of %G_PRIORITY_DEFAULT.
4247 * Return value: the newly-created idle source
4250 g_idle_source_new (void)
4254 source = g_source_new (&g_idle_funcs, sizeof (GSource));
4255 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4262 * @priority: the priority of the idle source. Typically this will be in the
4263 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4264 * @function: function to call
4265 * @data: data to pass to @function
4266 * @notify: function to call when the idle is removed, or %NULL
4268 * Adds a function to be called whenever there are no higher priority
4269 * events pending. If the function returns %FALSE it is automatically
4270 * removed from the list of event sources and will not be called again.
4272 * This internally creates a main loop source using g_idle_source_new()
4273 * and attaches it to the main loop context using g_source_attach().
4274 * You can do these steps manually if you need greater control.
4276 * Return value: the ID (greater than 0) of the event source.
4279 g_idle_add_full (gint priority,
4280 GSourceFunc function,
4282 GDestroyNotify notify)
4287 g_return_val_if_fail (function != NULL, 0);
4289 source = g_idle_source_new ();
4291 if (priority != G_PRIORITY_DEFAULT_IDLE)
4292 g_source_set_priority (source, priority);
4294 g_source_set_callback (source, function, data, notify);
4295 id = g_source_attach (source, NULL);
4296 g_source_unref (source);
4303 * @function: function to call
4304 * @data: data to pass to @function.
4306 * Adds a function to be called whenever there are no higher priority
4307 * events pending to the default main loop. The function is given the
4308 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4309 * returns %FALSE it is automatically removed from the list of event
4310 * sources and will not be called again.
4312 * This internally creates a main loop source using g_idle_source_new()
4313 * and attaches it to the main loop context using g_source_attach().
4314 * You can do these steps manually if you need greater control.
4316 * Return value: the ID (greater than 0) of the event source.
4319 g_idle_add (GSourceFunc function,
4322 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4326 * g_idle_remove_by_data:
4327 * @data: the data for the idle source's callback.
4329 * Removes the idle function with the given data.
4331 * Return value: %TRUE if an idle source was found and removed.
4334 g_idle_remove_by_data (gpointer data)
4336 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);