1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * gmain.c: Main loop abstraction, timeouts, and idle functions
5 * Copyright 1998 Owen Taylor
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the
19 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 * Boston, MA 02111-1307, USA.
24 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
25 * file for a list of people on the GLib Team. See the ChangeLog
26 * files for a list of changes. These files are distributed with
27 * GLib at ftp://ftp.gtk.org/pub/gtk/.
35 /* for pipe2; need to define it first to avoid
36 * other headers pulling in unistd.h
38 /* The meaning of_GNU_SOURCE that is intended here is present only on
39 * Linux; avoid the possibility that some misguided header in MinGW
40 * looks at it. Ideally we should define _GNU_SOURCE only on platforms
41 * where we know what it means and that is what we want here
42 * (i.e. Linux with glibc). After all, there might be some other POSIX
43 * platform even where _GNU_SOURCE is used for some unrelated change
44 * in semantics that isn't wanted. Sigh.
50 #include "glibconfig.h"
52 /* Uncomment the next line (and the corresponding line in gpoll.c) to
53 * enable debugging printouts if the environment variable
54 * G_MAIN_POLL_DEBUG is set to some value.
56 /* #define G_MAIN_POLL_DEBUG */
59 /* Always enable debugging printout on Windows, as it is more often
62 #define G_MAIN_POLL_DEBUG
66 #include <sys/types.h>
69 #ifdef HAVE_SYS_TIME_H
71 #endif /* HAVE_SYS_TIME_H */
74 #endif /* HAVE_UNISTD_H */
80 #endif /* G_OS_WIN32 */
83 #include <sys/socket.h>
85 #endif /* G_OS_BEOS */
95 #include "giochannel.h"
99 #include "gstrfuncs.h"
100 #include "gtestutils.h"
101 #include "gthreadprivate.h"
107 #ifdef G_MAIN_POLL_DEBUG
113 * @title: The Main Event Loop
114 * @short_description: manages all available sources of events
116 * The main event loop manages all the available sources of events for
117 * GLib and GTK+ applications. These events can come from any number of
118 * different types of sources such as file descriptors (plain files,
119 * pipes or sockets) and timeouts. New types of event sources can also
120 * be added using g_source_attach().
122 * To allow multiple independent sets of sources to be handled in
123 * different threads, each source is associated with a #GMainContext.
124 * A GMainContext can only be running in a single thread, but
125 * sources can be added to it and removed from it from other threads.
127 * Each event source is assigned a priority. The default priority,
128 * #G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
129 * Values greater than 0 denote lower priorities. Events from high priority
130 * sources are always processed before events from lower priority sources.
132 * Idle functions can also be added, and assigned a priority. These will
133 * be run whenever no events with a higher priority are ready to be processed.
135 * The #GMainLoop data type represents a main event loop. A GMainLoop is
136 * created with g_main_loop_new(). After adding the initial event sources,
137 * g_main_loop_run() is called. This continuously checks for new events from
138 * each of the event sources and dispatches them. Finally, the processing of
139 * an event from one of the sources leads to a call to g_main_loop_quit() to
140 * exit the main loop, and g_main_loop_run() returns.
142 * It is possible to create new instances of #GMainLoop recursively.
143 * This is often used in GTK+ applications when showing modal dialog
144 * boxes. Note that event sources are associated with a particular
145 * #GMainContext, and will be checked and dispatched for all main
146 * loops associated with that GMainContext.
148 * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
149 * gtk_main_quit() and gtk_events_pending().
151 * <refsect2><title>Creating new source types</title>
152 * <para>One of the unusual features of the #GMainLoop functionality
153 * is that new types of event source can be created and used in
154 * addition to the builtin type of event source. A new event source
155 * type is used for handling GDK events. A new source type is created
156 * by <firstterm>deriving</firstterm> from the #GSource structure.
157 * The derived type of source is represented by a structure that has
158 * the #GSource structure as a first element, and other elements specific
159 * to the new source type. To create an instance of the new source type,
160 * call g_source_new() passing in the size of the derived structure and
161 * a table of functions. These #GSourceFuncs determine the behavior of
162 * the new source type.</para>
163 * <para>New source types basically interact with the main context
164 * in two ways. Their prepare function in #GSourceFuncs can set a timeout
165 * to determine the maximum amount of time that the main loop will sleep
166 * before checking the source again. In addition, or as well, the source
167 * can add file descriptors to the set that the main context checks using
168 * g_source_add_poll().</para>
170 * <refsect2><title>Customizing the main loop iteration</title>
171 * <para>Single iterations of a #GMainContext can be run with
172 * g_main_context_iteration(). In some cases, more detailed control
173 * of exactly how the details of the main loop work is desired, for
174 * instance, when integrating the #GMainLoop with an external main loop.
175 * In such cases, you can call the component functions of
176 * g_main_context_iteration() directly. These functions are
177 * g_main_context_prepare(), g_main_context_query(),
178 * g_main_context_check() and g_main_context_dispatch().</para>
179 * <para>The operation of these functions can best be seen in terms
180 * of a state diagram, as shown in <xref linkend="mainloop-states"/>.</para>
181 * <figure id="mainloop-states"><title>States of a Main Context</title>
182 * <graphic fileref="mainloop-states.gif" format="GIF"></graphic>
189 typedef struct _GTimeoutSource GTimeoutSource;
190 typedef struct _GChildWatchSource GChildWatchSource;
191 typedef struct _GPollRec GPollRec;
192 typedef struct _GSourceCallback GSourceCallback;
196 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
197 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
200 #ifdef G_THREADS_ENABLED
201 typedef struct _GMainWaiter GMainWaiter;
210 typedef struct _GMainDispatch GMainDispatch;
212 struct _GMainDispatch
215 GSList *dispatching_sources; /* stack of current sources */
218 #ifdef G_MAIN_POLL_DEBUG
219 gboolean _g_main_poll_debug = FALSE;
224 #ifdef G_THREADS_ENABLED
225 /* The following lock is used for both the list of sources
226 * and the list of poll records
237 GPtrArray *pending_dispatches;
238 gint timeout; /* Timeout for current iteration */
241 GSource *source_list;
242 gint in_check_or_prepare;
244 GPollRec *poll_records;
245 guint n_poll_records;
246 GPollFD *cached_poll_array;
247 guint cached_poll_array_size;
249 #ifdef G_THREADS_ENABLED
251 /* this pipe is used to wake up the main loop when a source is added.
253 gint wake_up_pipe[2];
254 #else /* G_OS_WIN32 */
255 HANDLE wake_up_semaphore;
256 #endif /* G_OS_WIN32 */
259 gboolean poll_waiting;
261 /* Flag indicating whether the set of fd's changed during a poll */
262 gboolean poll_changed;
263 #endif /* G_THREADS_ENABLED */
268 gboolean time_is_fresh;
269 GTimeVal current_time;
270 gboolean current_time_is_fresh;
273 struct _GSourceCallback
278 GDestroyNotify notify;
283 GMainContext *context;
288 struct _GTimeoutSource
291 GTimeSpec expiration;
296 struct _GChildWatchSource
303 #else /* G_OS_WIN32 */
305 gboolean child_exited;
306 #endif /* G_OS_WIN32 */
316 #ifdef G_THREADS_ENABLED
317 #define LOCK_CONTEXT(context) g_static_mutex_lock (&context->mutex)
318 #define UNLOCK_CONTEXT(context) g_static_mutex_unlock (&context->mutex)
319 #define G_THREAD_SELF g_thread_self ()
321 #define LOCK_CONTEXT(context) (void)0
322 #define UNLOCK_CONTEXT(context) (void)0
323 #define G_THREAD_SELF NULL
326 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
327 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
328 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
330 #define SOURCE_UNREF(source, context) \
332 if ((source)->ref_count > 1) \
333 (source)->ref_count--; \
335 g_source_unref_internal ((source), (context), TRUE); \
339 /* Forward declarations */
341 static void g_source_unref_internal (GSource *source,
342 GMainContext *context,
344 static void g_source_destroy_internal (GSource *source,
345 GMainContext *context,
347 static void g_main_context_poll (GMainContext *context,
352 static void g_main_context_add_poll_unlocked (GMainContext *context,
355 static void g_main_context_remove_poll_unlocked (GMainContext *context,
357 static void g_main_context_wakeup_unlocked (GMainContext *context);
359 static gboolean g_timeout_prepare (GSource *source,
361 static gboolean g_timeout_check (GSource *source);
362 static gboolean g_timeout_dispatch (GSource *source,
363 GSourceFunc callback,
365 static gboolean g_child_watch_prepare (GSource *source,
367 static gboolean g_child_watch_check (GSource *source);
368 static gboolean g_child_watch_dispatch (GSource *source,
369 GSourceFunc callback,
371 static gboolean g_idle_prepare (GSource *source,
373 static gboolean g_idle_check (GSource *source);
374 static gboolean g_idle_dispatch (GSource *source,
375 GSourceFunc callback,
378 G_LOCK_DEFINE_STATIC (main_loop);
379 static GMainContext *default_main_context;
380 static GSList *main_contexts_without_pipe = NULL;
383 /* Child status monitoring code */
385 CHILD_WATCH_UNINITIALIZED,
386 CHILD_WATCH_INITIALIZED_SINGLE,
387 CHILD_WATCH_INITIALIZED_THREADED
389 static gint child_watch_init_state = CHILD_WATCH_UNINITIALIZED;
390 static gint child_watch_count = 1;
391 static gint child_watch_wake_up_pipe[2] = {0, 0};
392 #endif /* !G_OS_WIN32 */
393 G_LOCK_DEFINE_STATIC (main_context_list);
394 static GSList *main_context_list = NULL;
396 GSourceFuncs g_timeout_funcs =
404 GSourceFuncs g_child_watch_funcs =
406 g_child_watch_prepare,
408 g_child_watch_dispatch,
412 GSourceFuncs g_idle_funcs =
421 * g_main_context_ref:
422 * @context: a #GMainContext
424 * Increases the reference count on a #GMainContext object by one.
426 * Returns: the @context that was passed in (since 2.6)
429 g_main_context_ref (GMainContext *context)
431 g_return_val_if_fail (context != NULL, NULL);
432 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
434 g_atomic_int_inc (&context->ref_count);
440 poll_rec_list_free (GMainContext *context,
443 g_slice_free_chain (GPollRec, list, next);
447 * g_main_context_unref:
448 * @context: a #GMainContext
450 * Decreases the reference count on a #GMainContext object by one. If
451 * the result is zero, free the context and free all associated memory.
454 g_main_context_unref (GMainContext *context)
457 g_return_if_fail (context != NULL);
458 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
460 if (!g_atomic_int_dec_and_test (&context->ref_count))
463 G_LOCK (main_context_list);
464 main_context_list = g_slist_remove (main_context_list, context);
465 G_UNLOCK (main_context_list);
467 source = context->source_list;
470 GSource *next = source->next;
471 g_source_destroy_internal (source, context, FALSE);
475 #ifdef G_THREADS_ENABLED
476 g_static_mutex_free (&context->mutex);
479 g_ptr_array_free (context->pending_dispatches, TRUE);
480 g_free (context->cached_poll_array);
482 poll_rec_list_free (context, context->poll_records);
484 #ifdef G_THREADS_ENABLED
485 if (g_thread_supported())
488 close (context->wake_up_pipe[0]);
489 close (context->wake_up_pipe[1]);
491 CloseHandle (context->wake_up_semaphore);
495 main_contexts_without_pipe = g_slist_remove (main_contexts_without_pipe,
498 if (context->cond != NULL)
499 g_cond_free (context->cond);
505 #ifdef G_THREADS_ENABLED
507 g_main_context_init_pipe (GMainContext *context)
510 if (context->wake_up_pipe[0] != -1)
514 /* if this fails, we fall through and try pipe */
515 pipe2 (context->wake_up_pipe, O_CLOEXEC);
517 if (context->wake_up_pipe[0] == -1)
519 if (pipe (context->wake_up_pipe) < 0)
520 g_error ("Cannot create pipe main loop wake-up: %s\n",
523 fcntl (context->wake_up_pipe[0], F_SETFD, FD_CLOEXEC);
524 fcntl (context->wake_up_pipe[1], F_SETFD, FD_CLOEXEC);
527 context->wake_up_rec.fd = context->wake_up_pipe[0];
528 context->wake_up_rec.events = G_IO_IN;
530 if (context->wake_up_semaphore != NULL)
532 context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
533 if (context->wake_up_semaphore == NULL)
534 g_error ("Cannot create wake-up semaphore: %s",
535 g_win32_error_message (GetLastError ()));
536 context->wake_up_rec.fd = (gintptr) context->wake_up_semaphore;
537 context->wake_up_rec.events = G_IO_IN;
539 if (_g_main_poll_debug)
540 g_print ("wake-up semaphore: %p\n", context->wake_up_semaphore);
542 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
546 _g_main_thread_init (void)
548 GSList *curr = main_contexts_without_pipe;
551 g_main_context_init_pipe ((GMainContext *)curr->data);
554 g_slist_free (main_contexts_without_pipe);
555 main_contexts_without_pipe = NULL;
557 #endif /* G_THREADS_ENABLED */
560 * g_main_context_new:
562 * Creates a new #GMainContext structure.
564 * Return value: the new #GMainContext
567 g_main_context_new (void)
569 GMainContext *context = g_new0 (GMainContext, 1);
571 #ifdef G_MAIN_POLL_DEBUG
573 static gboolean beenhere = FALSE;
577 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
578 _g_main_poll_debug = TRUE;
584 #ifdef G_THREADS_ENABLED
585 g_static_mutex_init (&context->mutex);
587 context->owner = NULL;
588 context->waiters = NULL;
591 context->wake_up_pipe[0] = -1;
592 context->wake_up_pipe[1] = -1;
594 context->wake_up_semaphore = NULL;
598 context->ref_count = 1;
600 context->next_id = 1;
602 context->source_list = NULL;
604 context->poll_func = g_poll;
606 context->cached_poll_array = NULL;
607 context->cached_poll_array_size = 0;
609 context->pending_dispatches = g_ptr_array_new ();
611 context->time_is_fresh = FALSE;
612 context->current_time_is_fresh = FALSE;
614 #ifdef G_THREADS_ENABLED
615 if (g_thread_supported ())
616 g_main_context_init_pipe (context);
618 main_contexts_without_pipe = g_slist_prepend (main_contexts_without_pipe,
622 G_LOCK (main_context_list);
623 main_context_list = g_slist_append (main_context_list, context);
625 #ifdef G_MAIN_POLL_DEBUG
626 if (_g_main_poll_debug)
627 g_print ("created context=%p\n", context);
630 G_UNLOCK (main_context_list);
636 * g_main_context_default:
638 * Returns the global default main context. This is the main context
639 * used for main loop functions when a main loop is not explicitly
640 * specified, and corresponds to the "main" main loop. See also
641 * g_main_context_get_thread_default().
643 * Return value: the global default main context.
646 g_main_context_default (void)
652 if (!default_main_context)
654 default_main_context = g_main_context_new ();
655 #ifdef G_MAIN_POLL_DEBUG
656 if (_g_main_poll_debug)
657 g_print ("default context=%p\n", default_main_context);
661 G_UNLOCK (main_loop);
663 return default_main_context;
666 static GStaticPrivate thread_context_stack = G_STATIC_PRIVATE_INIT;
669 free_context_stack (gpointer data)
671 GQueue *stack = data;
672 GMainContext *context;
674 while (!g_queue_is_empty (stack))
676 context = g_queue_pop_head (stack);
677 g_main_context_release (context);
679 g_main_context_unref (context);
681 g_queue_free (stack);
685 * g_main_context_push_thread_default:
686 * @context: a #GMainContext, or %NULL for the global default context
688 * Acquires @context and sets it as the thread-default context for the
689 * current thread. This will cause certain asynchronous operations
690 * (such as most <link linkend="gio">gio</link>-based I/O) which are
691 * started in this thread to run under @context and deliver their
692 * results to its main loop, rather than running under the global
693 * default context in the main thread. Note that calling this function
694 * changes the context returned by
695 * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
696 * one returned by g_main_context_default(), so it does not affect the
697 * context used by functions like g_idle_add().
699 * Normally you would call this function shortly after creating a new
700 * thread, passing it a #GMainContext which will be run by a
701 * #GMainLoop in that thread, to set a new default context for all
702 * async operations in that thread. (In this case, you don't need to
703 * ever call g_main_context_pop_thread_default().) In some cases
704 * however, you may want to schedule a single operation in a
705 * non-default context, or temporarily use a non-default context in
706 * the main thread. In that case, you can wrap the call to the
707 * asynchronous operation inside a
708 * g_main_context_push_thread_default() /
709 * g_main_context_pop_thread_default() pair, but it is up to you to
710 * ensure that no other asynchronous operations accidentally get
711 * started while the non-default context is active.
713 * Beware that libraries that predate this function may not correctly
714 * handle being used from a thread with a thread-default context. Eg,
715 * see g_file_supports_thread_contexts().
720 g_main_context_push_thread_default (GMainContext *context)
723 gboolean acquired_context;
725 acquired_context = g_main_context_acquire (context);
726 g_return_if_fail (acquired_context);
728 if (context == g_main_context_default ())
731 g_main_context_ref (context);
733 stack = g_static_private_get (&thread_context_stack);
736 stack = g_queue_new ();
737 g_static_private_set (&thread_context_stack, stack,
741 g_queue_push_head (stack, context);
745 * g_main_context_pop_thread_default:
746 * @context: a #GMainContext object, or %NULL
748 * Pops @context off the thread-default context stack (verifying that
749 * it was on the top of the stack).
754 g_main_context_pop_thread_default (GMainContext *context)
758 if (context == g_main_context_default ())
761 stack = g_static_private_get (&thread_context_stack);
763 g_return_if_fail (stack != NULL);
764 g_return_if_fail (g_queue_peek_head (stack) == context);
766 g_queue_pop_head (stack);
768 g_main_context_release (context);
770 g_main_context_unref (context);
774 * g_main_context_get_thread_default:
776 * Gets the thread-default #GMainContext for this thread. Asynchronous
777 * operations that want to be able to be run in contexts other than
778 * the default one should call this method to get a #GMainContext to
779 * add their #GSource<!-- -->s to. (Note that even in single-threaded
780 * programs applications may sometimes want to temporarily push a
781 * non-default context, so it is not safe to assume that this will
782 * always return %NULL if threads are not initialized.)
784 * Returns: the thread-default #GMainContext, or %NULL if the
785 * thread-default context is the global default context.
790 g_main_context_get_thread_default (void)
794 stack = g_static_private_get (&thread_context_stack);
796 return g_queue_peek_head (stack);
801 /* Hooks for adding to the main loop */
805 * @source_funcs: structure containing functions that implement
806 * the sources behavior.
807 * @struct_size: size of the #GSource structure to create.
809 * Creates a new #GSource structure. The size is specified to
810 * allow creating structures derived from #GSource that contain
811 * additional data. The size passed in must be at least
812 * <literal>sizeof (GSource)</literal>.
814 * The source will not initially be associated with any #GMainContext
815 * and must be added to one with g_source_attach() before it will be
818 * Return value: the newly-created #GSource.
821 g_source_new (GSourceFuncs *source_funcs,
826 g_return_val_if_fail (source_funcs != NULL, NULL);
827 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
829 source = (GSource*) g_malloc0 (struct_size);
831 source->source_funcs = source_funcs;
832 source->ref_count = 1;
834 source->priority = G_PRIORITY_DEFAULT;
836 source->flags = G_HOOK_FLAG_ACTIVE;
838 /* NULL/0 initialization for all other fields */
843 /* Holds context's lock
846 g_source_list_add (GSource *source,
847 GMainContext *context)
849 GSource *tmp_source, *last_source;
852 tmp_source = context->source_list;
853 while (tmp_source && tmp_source->priority <= source->priority)
855 last_source = tmp_source;
856 tmp_source = tmp_source->next;
859 source->next = tmp_source;
861 tmp_source->prev = source;
863 source->prev = last_source;
865 last_source->next = source;
867 context->source_list = source;
870 /* Holds context's lock
873 g_source_list_remove (GSource *source,
874 GMainContext *context)
877 source->prev->next = source->next;
879 context->source_list = source->next;
882 source->next->prev = source->prev;
890 * @source: a #GSource
891 * @context: a #GMainContext (if %NULL, the default context will be used)
893 * Adds a #GSource to a @context so that it will be executed within
894 * that context. Remove it by calling g_source_destroy().
896 * Return value: the ID (greater than 0) for the source within the
900 g_source_attach (GSource *source,
901 GMainContext *context)
906 g_return_val_if_fail (source->context == NULL, 0);
907 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
910 context = g_main_context_default ();
912 LOCK_CONTEXT (context);
914 source->context = context;
915 result = source->source_id = context->next_id++;
918 g_source_list_add (source, context);
920 tmp_list = source->poll_fds;
923 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
924 tmp_list = tmp_list->next;
927 #ifdef G_THREADS_ENABLED
928 /* Now wake up the main loop if it is waiting in the poll() */
929 g_main_context_wakeup_unlocked (context);
932 UNLOCK_CONTEXT (context);
938 g_source_destroy_internal (GSource *source,
939 GMainContext *context,
943 LOCK_CONTEXT (context);
945 if (!SOURCE_DESTROYED (source))
948 gpointer old_cb_data;
949 GSourceCallbackFuncs *old_cb_funcs;
951 source->flags &= ~G_HOOK_FLAG_ACTIVE;
953 old_cb_data = source->callback_data;
954 old_cb_funcs = source->callback_funcs;
956 source->callback_data = NULL;
957 source->callback_funcs = NULL;
961 UNLOCK_CONTEXT (context);
962 old_cb_funcs->unref (old_cb_data);
963 LOCK_CONTEXT (context);
966 if (!SOURCE_BLOCKED (source))
968 tmp_list = source->poll_fds;
971 g_main_context_remove_poll_unlocked (context, tmp_list->data);
972 tmp_list = tmp_list->next;
976 g_source_unref_internal (source, context, TRUE);
980 UNLOCK_CONTEXT (context);
985 * @source: a #GSource
987 * Removes a source from its #GMainContext, if any, and mark it as
988 * destroyed. The source cannot be subsequently added to another
992 g_source_destroy (GSource *source)
994 GMainContext *context;
996 g_return_if_fail (source != NULL);
998 context = source->context;
1001 g_source_destroy_internal (source, context, FALSE);
1003 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1008 * @source: a #GSource
1010 * Returns the numeric ID for a particular source. The ID of a source
1011 * is a positive integer which is unique within a particular main loop
1012 * context. The reverse
1013 * mapping from ID to source is done by g_main_context_find_source_by_id().
1015 * Return value: the ID (greater than 0) for the source
1018 g_source_get_id (GSource *source)
1022 g_return_val_if_fail (source != NULL, 0);
1023 g_return_val_if_fail (source->context != NULL, 0);
1025 LOCK_CONTEXT (source->context);
1026 result = source->source_id;
1027 UNLOCK_CONTEXT (source->context);
1033 * g_source_get_context:
1034 * @source: a #GSource
1036 * Gets the #GMainContext with which the source is associated.
1037 * Calling this function on a destroyed source is an error.
1039 * Return value: the #GMainContext with which the source is associated,
1040 * or %NULL if the context has not yet been added
1044 g_source_get_context (GSource *source)
1046 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1048 return source->context;
1052 * g_source_add_poll:
1053 * @source:a #GSource
1054 * @fd: a #GPollFD structure holding information about a file
1055 * descriptor to watch.
1057 * Adds a file descriptor to the set of file descriptors polled for
1058 * this source. This is usually combined with g_source_new() to add an
1059 * event source. The event source's check function will typically test
1060 * the @revents field in the #GPollFD struct and return %TRUE if events need
1064 g_source_add_poll (GSource *source,
1067 GMainContext *context;
1069 g_return_if_fail (source != NULL);
1070 g_return_if_fail (fd != NULL);
1071 g_return_if_fail (!SOURCE_DESTROYED (source));
1073 context = source->context;
1076 LOCK_CONTEXT (context);
1078 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1082 if (!SOURCE_BLOCKED (source))
1083 g_main_context_add_poll_unlocked (context, source->priority, fd);
1084 UNLOCK_CONTEXT (context);
1089 * g_source_remove_poll:
1090 * @source:a #GSource
1091 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1093 * Removes a file descriptor from the set of file descriptors polled for
1097 g_source_remove_poll (GSource *source,
1100 GMainContext *context;
1102 g_return_if_fail (source != NULL);
1103 g_return_if_fail (fd != NULL);
1104 g_return_if_fail (!SOURCE_DESTROYED (source));
1106 context = source->context;
1109 LOCK_CONTEXT (context);
1111 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1115 if (!SOURCE_BLOCKED (source))
1116 g_main_context_remove_poll_unlocked (context, fd);
1117 UNLOCK_CONTEXT (context);
1122 * g_source_set_callback_indirect:
1123 * @source: the source
1124 * @callback_data: pointer to callback data "object"
1125 * @callback_funcs: functions for reference counting @callback_data
1126 * and getting the callback and data
1128 * Sets the callback function storing the data as a refcounted callback
1129 * "object". This is used internally. Note that calling
1130 * g_source_set_callback_indirect() assumes
1131 * an initial reference count on @callback_data, and thus
1132 * @callback_funcs->unref will eventually be called once more
1133 * than @callback_funcs->ref.
1136 g_source_set_callback_indirect (GSource *source,
1137 gpointer callback_data,
1138 GSourceCallbackFuncs *callback_funcs)
1140 GMainContext *context;
1141 gpointer old_cb_data;
1142 GSourceCallbackFuncs *old_cb_funcs;
1144 g_return_if_fail (source != NULL);
1145 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1147 context = source->context;
1150 LOCK_CONTEXT (context);
1152 old_cb_data = source->callback_data;
1153 old_cb_funcs = source->callback_funcs;
1155 source->callback_data = callback_data;
1156 source->callback_funcs = callback_funcs;
1159 UNLOCK_CONTEXT (context);
1162 old_cb_funcs->unref (old_cb_data);
1166 g_source_callback_ref (gpointer cb_data)
1168 GSourceCallback *callback = cb_data;
1170 callback->ref_count++;
1175 g_source_callback_unref (gpointer cb_data)
1177 GSourceCallback *callback = cb_data;
1179 callback->ref_count--;
1180 if (callback->ref_count == 0)
1182 if (callback->notify)
1183 callback->notify (callback->data);
1189 g_source_callback_get (gpointer cb_data,
1194 GSourceCallback *callback = cb_data;
1196 *func = callback->func;
1197 *data = callback->data;
1200 static GSourceCallbackFuncs g_source_callback_funcs = {
1201 g_source_callback_ref,
1202 g_source_callback_unref,
1203 g_source_callback_get,
1207 * g_source_set_callback:
1208 * @source: the source
1209 * @func: a callback function
1210 * @data: the data to pass to callback function
1211 * @notify: a function to call when @data is no longer in use, or %NULL.
1213 * Sets the callback function for a source. The callback for a source is
1214 * called from the source's dispatch function.
1216 * The exact type of @func depends on the type of source; ie. you
1217 * should not count on @func being called with @data as its first
1220 * Typically, you won't use this function. Instead use functions specific
1221 * to the type of source you are using.
1224 g_source_set_callback (GSource *source,
1227 GDestroyNotify notify)
1229 GSourceCallback *new_callback;
1231 g_return_if_fail (source != NULL);
1233 new_callback = g_new (GSourceCallback, 1);
1235 new_callback->ref_count = 1;
1236 new_callback->func = func;
1237 new_callback->data = data;
1238 new_callback->notify = notify;
1240 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1245 * g_source_set_funcs:
1246 * @source: a #GSource
1247 * @funcs: the new #GSourceFuncs
1249 * Sets the source functions (can be used to override
1250 * default implementations) of an unattached source.
1255 g_source_set_funcs (GSource *source,
1256 GSourceFuncs *funcs)
1258 g_return_if_fail (source != NULL);
1259 g_return_if_fail (source->context == NULL);
1260 g_return_if_fail (source->ref_count > 0);
1261 g_return_if_fail (funcs != NULL);
1263 source->source_funcs = funcs;
1267 * g_source_set_priority:
1268 * @source: a #GSource
1269 * @priority: the new priority.
1271 * Sets the priority of a source. While the main loop is being
1272 * run, a source will be dispatched if it is ready to be dispatched and no sources
1273 * at a higher (numerically smaller) priority are ready to be dispatched.
1276 g_source_set_priority (GSource *source,
1280 GMainContext *context;
1282 g_return_if_fail (source != NULL);
1284 context = source->context;
1287 LOCK_CONTEXT (context);
1289 source->priority = priority;
1293 /* Remove the source from the context's source and then
1294 * add it back so it is sorted in the correct plcae
1296 g_source_list_remove (source, source->context);
1297 g_source_list_add (source, source->context);
1299 if (!SOURCE_BLOCKED (source))
1301 tmp_list = source->poll_fds;
1304 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1305 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1307 tmp_list = tmp_list->next;
1311 UNLOCK_CONTEXT (source->context);
1316 * g_source_get_priority:
1317 * @source: a #GSource
1319 * Gets the priority of a source.
1321 * Return value: the priority of the source
1324 g_source_get_priority (GSource *source)
1326 g_return_val_if_fail (source != NULL, 0);
1328 return source->priority;
1332 * g_source_set_can_recurse:
1333 * @source: a #GSource
1334 * @can_recurse: whether recursion is allowed for this source
1336 * Sets whether a source can be called recursively. If @can_recurse is
1337 * %TRUE, then while the source is being dispatched then this source
1338 * will be processed normally. Otherwise, all processing of this
1339 * source is blocked until the dispatch function returns.
1342 g_source_set_can_recurse (GSource *source,
1343 gboolean can_recurse)
1345 GMainContext *context;
1347 g_return_if_fail (source != NULL);
1349 context = source->context;
1352 LOCK_CONTEXT (context);
1355 source->flags |= G_SOURCE_CAN_RECURSE;
1357 source->flags &= ~G_SOURCE_CAN_RECURSE;
1360 UNLOCK_CONTEXT (context);
1364 * g_source_get_can_recurse:
1365 * @source: a #GSource
1367 * Checks whether a source is allowed to be called recursively.
1368 * see g_source_set_can_recurse().
1370 * Return value: whether recursion is allowed.
1373 g_source_get_can_recurse (GSource *source)
1375 g_return_val_if_fail (source != NULL, FALSE);
1377 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1382 * g_source_set_name:
1383 * @source: a #GSource
1384 * @name: debug name for the source
1386 * Sets a name for the source, used in debugging and profiling.
1387 * The name defaults to #NULL.
1389 * The source name should describe in a human-readable way
1390 * what the source does. For example, "X11 event queue"
1391 * or "GTK+ repaint idle handler" or whatever it is.
1393 * It is permitted to call this function multiple times, but is not
1394 * recommended due to the potential performance impact. For example,
1395 * one could change the name in the "check" function of a #GSourceFuncs
1396 * to include details like the event type in the source name.
1401 g_source_set_name (GSource *source,
1404 g_return_if_fail (source != NULL);
1406 /* setting back to NULL is allowed, just because it's
1407 * weird if get_name can return NULL but you can't
1411 g_free (source->name);
1412 source->name = g_strdup (name);
1416 * g_source_get_name:
1417 * @source: a #GSource
1419 * Gets a name for the source, used in debugging and profiling.
1420 * The name may be #NULL if it has never been set with
1421 * g_source_set_name().
1423 * Return value: the name of the source
1426 G_CONST_RETURN char*
1427 g_source_get_name (GSource *source)
1429 g_return_val_if_fail (source != NULL, NULL);
1431 return source->name;
1435 * g_source_set_name_by_id:
1436 * @tag: a #GSource ID
1437 * @name: debug name for the source
1439 * Sets the name of a source using its ID.
1441 * This is a convenience utility to set source names from the return
1442 * value of g_idle_add(), g_timeout_add(), etc.
1447 g_source_set_name_by_id (guint tag,
1452 g_return_if_fail (tag > 0);
1454 source = g_main_context_find_source_by_id (NULL, tag);
1458 g_source_set_name (source, name);
1464 * @source: a #GSource
1466 * Increases the reference count on a source by one.
1468 * Return value: @source
1471 g_source_ref (GSource *source)
1473 GMainContext *context;
1475 g_return_val_if_fail (source != NULL, NULL);
1477 context = source->context;
1480 LOCK_CONTEXT (context);
1482 source->ref_count++;
1485 UNLOCK_CONTEXT (context);
1490 /* g_source_unref() but possible to call within context lock
1493 g_source_unref_internal (GSource *source,
1494 GMainContext *context,
1497 gpointer old_cb_data = NULL;
1498 GSourceCallbackFuncs *old_cb_funcs = NULL;
1500 g_return_if_fail (source != NULL);
1502 if (!have_lock && context)
1503 LOCK_CONTEXT (context);
1505 source->ref_count--;
1506 if (source->ref_count == 0)
1508 old_cb_data = source->callback_data;
1509 old_cb_funcs = source->callback_funcs;
1511 source->callback_data = NULL;
1512 source->callback_funcs = NULL;
1514 if (context && !SOURCE_DESTROYED (source))
1516 g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1517 source->ref_count++;
1520 g_source_list_remove (source, context);
1522 if (source->source_funcs->finalize)
1523 source->source_funcs->finalize (source);
1525 g_free (source->name);
1526 source->name = NULL;
1528 g_slist_free (source->poll_fds);
1529 source->poll_fds = NULL;
1533 if (!have_lock && context)
1534 UNLOCK_CONTEXT (context);
1539 UNLOCK_CONTEXT (context);
1541 old_cb_funcs->unref (old_cb_data);
1544 LOCK_CONTEXT (context);
1550 * @source: a #GSource
1552 * Decreases the reference count of a source by one. If the
1553 * resulting reference count is zero the source and associated
1554 * memory will be destroyed.
1557 g_source_unref (GSource *source)
1559 g_return_if_fail (source != NULL);
1561 g_source_unref_internal (source, source->context, FALSE);
1565 * g_main_context_find_source_by_id:
1566 * @context: a #GMainContext (if %NULL, the default context will be used)
1567 * @source_id: the source ID, as returned by g_source_get_id().
1569 * Finds a #GSource given a pair of context and ID.
1571 * Return value: the #GSource if found, otherwise, %NULL
1574 g_main_context_find_source_by_id (GMainContext *context,
1579 g_return_val_if_fail (source_id > 0, NULL);
1581 if (context == NULL)
1582 context = g_main_context_default ();
1584 LOCK_CONTEXT (context);
1586 source = context->source_list;
1589 if (!SOURCE_DESTROYED (source) &&
1590 source->source_id == source_id)
1592 source = source->next;
1595 UNLOCK_CONTEXT (context);
1601 * g_main_context_find_source_by_funcs_user_data:
1602 * @context: a #GMainContext (if %NULL, the default context will be used).
1603 * @funcs: the @source_funcs passed to g_source_new().
1604 * @user_data: the user data from the callback.
1606 * Finds a source with the given source functions and user data. If
1607 * multiple sources exist with the same source function and user data,
1608 * the first one found will be returned.
1610 * Return value: the source, if one was found, otherwise %NULL
1613 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1614 GSourceFuncs *funcs,
1619 g_return_val_if_fail (funcs != NULL, NULL);
1621 if (context == NULL)
1622 context = g_main_context_default ();
1624 LOCK_CONTEXT (context);
1626 source = context->source_list;
1629 if (!SOURCE_DESTROYED (source) &&
1630 source->source_funcs == funcs &&
1631 source->callback_funcs)
1633 GSourceFunc callback;
1634 gpointer callback_data;
1636 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1638 if (callback_data == user_data)
1641 source = source->next;
1644 UNLOCK_CONTEXT (context);
1650 * g_main_context_find_source_by_user_data:
1651 * @context: a #GMainContext
1652 * @user_data: the user_data for the callback.
1654 * Finds a source with the given user data for the callback. If
1655 * multiple sources exist with the same user data, the first
1656 * one found will be returned.
1658 * Return value: the source, if one was found, otherwise %NULL
1661 g_main_context_find_source_by_user_data (GMainContext *context,
1666 if (context == NULL)
1667 context = g_main_context_default ();
1669 LOCK_CONTEXT (context);
1671 source = context->source_list;
1674 if (!SOURCE_DESTROYED (source) &&
1675 source->callback_funcs)
1677 GSourceFunc callback;
1678 gpointer callback_data = NULL;
1680 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1682 if (callback_data == user_data)
1685 source = source->next;
1688 UNLOCK_CONTEXT (context);
1695 * @tag: the ID of the source to remove.
1697 * Removes the source with the given id from the default main context.
1699 * a #GSource is given by g_source_get_id(), or will be returned by the
1700 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1701 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1702 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1704 * See also g_source_destroy(). You must use g_source_destroy() for sources
1705 * added to a non-default main context.
1707 * Return value: %TRUE if the source was found and removed.
1710 g_source_remove (guint tag)
1714 g_return_val_if_fail (tag > 0, FALSE);
1716 source = g_main_context_find_source_by_id (NULL, tag);
1718 g_source_destroy (source);
1720 return source != NULL;
1724 * g_source_remove_by_user_data:
1725 * @user_data: the user_data for the callback.
1727 * Removes a source from the default main loop context given the user
1728 * data for the callback. If multiple sources exist with the same user
1729 * data, only one will be destroyed.
1731 * Return value: %TRUE if a source was found and removed.
1734 g_source_remove_by_user_data (gpointer user_data)
1738 source = g_main_context_find_source_by_user_data (NULL, user_data);
1741 g_source_destroy (source);
1749 * g_source_remove_by_funcs_user_data:
1750 * @funcs: The @source_funcs passed to g_source_new()
1751 * @user_data: the user data for the callback
1753 * Removes a source from the default main loop context given the
1754 * source functions and user data. If multiple sources exist with the
1755 * same source functions and user data, only one will be destroyed.
1757 * Return value: %TRUE if a source was found and removed.
1760 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1765 g_return_val_if_fail (funcs != NULL, FALSE);
1767 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1770 g_source_destroy (source);
1778 * g_get_current_time:
1779 * @result: #GTimeVal structure in which to store current time.
1781 * Equivalent to the UNIX gettimeofday() function, but portable.
1784 g_get_current_time (GTimeVal *result)
1789 g_return_if_fail (result != NULL);
1791 /*this is required on alpha, there the timeval structs are int's
1792 not longs and a cast only would fail horribly*/
1793 gettimeofday (&r, NULL);
1794 result->tv_sec = r.tv_sec;
1795 result->tv_usec = r.tv_usec;
1800 g_return_if_fail (result != NULL);
1802 GetSystemTimeAsFileTime (&ft);
1803 memmove (&time64, &ft, sizeof (FILETIME));
1805 /* Convert from 100s of nanoseconds since 1601-01-01
1806 * to Unix epoch. Yes, this is Y2038 unsafe.
1808 time64 -= G_GINT64_CONSTANT (116444736000000000);
1811 result->tv_sec = time64 / 1000000;
1812 result->tv_usec = time64 % 1000000;
1819 * Represents a precise time, with seconds and nanoseconds. This is
1820 * similar to POSIX <structname>struct timespec</structname>. This
1821 * structure can be filled in with g_get_monotonic_time().
1827 * g_get_monotonic_time:
1828 * @result: #GTimeSpec structure in which to store the time
1830 * Queries the system monotonic time, if available.
1832 * On POSIX systems with clock_gettime() and %CLOCK_MONOTONIC this call
1833 * is a very shallow wrapper for that. Otherwise, we make a best effort
1834 * that probably involves returning the wall clock time (with at least
1835 * microsecond accuracy, subject to the limitations of the OS kernel).
1837 * Note that, on Windows, "limitations of the OS kernel" is a rather
1838 * substantial statement. Depending on the configuration of the system,
1839 * the wall clock time is updated as infrequently as 64 times a second
1840 * (which is approximately every 16ms).
1845 g_get_monotonic_time (GTimeSpec *result)
1847 g_return_if_fail (result != NULL);
1849 #ifdef HAVE_CLOCK_GETTIME
1850 /* librt clock_gettime() is our first choice */
1852 static int clockid = CLOCK_REALTIME;
1855 #ifdef HAVE_MONOTONIC_CLOCK
1856 /* We have to check if we actually have monotonic clock support.
1858 * There is no thread safety issue here since there is no harm if we
1862 static gboolean checked;
1864 if G_UNLIKELY (!checked)
1866 if (sysconf (_SC_MONOTONIC_CLOCK) >= 0)
1867 clockid = CLOCK_MONOTONIC;
1873 clock_gettime (clockid, &ts);
1874 result->tv_sec = ts.tv_sec;
1875 result->tv_nsec = ts.tv_nsec;
1878 /* It may look like we are discarding accuracy on Windows (since its
1879 * current time is expressed in 100s of nanoseconds) but according to
1880 * many sources, the time is only updated 64 times per second, so
1881 * microsecond accuracy is more than enough.
1886 g_get_current_time (&tv);
1887 result->tv_sec = tv.tv_sec;
1888 result->tv_nsec = tv.tv_usec * 1000;
1894 g_main_dispatch_free (gpointer dispatch)
1896 g_slice_free (GMainDispatch, dispatch);
1899 /* Running the main loop */
1901 static GMainDispatch *
1904 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
1905 GMainDispatch *dispatch = g_static_private_get (&depth_private);
1908 dispatch = g_slice_new0 (GMainDispatch);
1909 g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
1918 * Returns the depth of the stack of calls to
1919 * g_main_context_dispatch() on any #GMainContext in the current thread.
1920 * That is, when called from the toplevel, it gives 0. When
1921 * called from within a callback from g_main_context_iteration()
1922 * (or g_main_loop_run(), etc.) it returns 1. When called from within
1923 * a callback to a recursive call to g_main_context_iterate(),
1924 * it returns 2. And so forth.
1926 * This function is useful in a situation like the following:
1927 * Imagine an extremely simple "garbage collected" system.
1930 * static GList *free_list;
1933 * allocate_memory (gsize size)
1935 * gpointer result = g_malloc (size);
1936 * free_list = g_list_prepend (free_list, result);
1941 * free_allocated_memory (void)
1944 * for (l = free_list; l; l = l->next);
1946 * g_list_free (free_list);
1954 * g_main_context_iteration (NULL, TRUE);
1955 * free_allocated_memory();
1959 * This works from an application, however, if you want to do the same
1960 * thing from a library, it gets more difficult, since you no longer
1961 * control the main loop. You might think you can simply use an idle
1962 * function to make the call to free_allocated_memory(), but that
1963 * doesn't work, since the idle function could be called from a
1964 * recursive callback. This can be fixed by using g_main_depth()
1968 * allocate_memory (gsize size)
1970 * FreeListBlock *block = g_new (FreeListBlock, 1);
1971 * block->mem = g_malloc (size);
1972 * block->depth = g_main_depth ();
1973 * free_list = g_list_prepend (free_list, block);
1974 * return block->mem;
1978 * free_allocated_memory (void)
1982 * int depth = g_main_depth ();
1983 * for (l = free_list; l; );
1985 * GList *next = l->next;
1986 * FreeListBlock *block = l->data;
1987 * if (block->depth > depth)
1989 * g_free (block->mem);
1991 * free_list = g_list_delete_link (free_list, l);
1999 * There is a temptation to use g_main_depth() to solve
2000 * problems with reentrancy. For instance, while waiting for data
2001 * to be received from the network in response to a menu item,
2002 * the menu item might be selected again. It might seem that
2003 * one could make the menu item's callback return immediately
2004 * and do nothing if g_main_depth() returns a value greater than 1.
2005 * However, this should be avoided since the user then sees selecting
2006 * the menu item do nothing. Furthermore, you'll find yourself adding
2007 * these checks all over your code, since there are doubtless many,
2008 * many things that the user could do. Instead, you can use the
2009 * following techniques:
2014 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
2015 * the user from interacting with elements while the main
2016 * loop is recursing.
2021 * Avoid main loop recursion in situations where you can't handle
2022 * arbitrary callbacks. Instead, structure your code so that you
2023 * simply return to the main loop and then get called again when
2024 * there is more work to do.
2029 * Return value: The main loop recursion level in the current thread
2034 GMainDispatch *dispatch = get_dispatch ();
2035 return dispatch->depth;
2039 * g_main_current_source:
2041 * Returns the currently firing source for this thread.
2043 * Return value: The currently firing source or %NULL.
2048 g_main_current_source (void)
2050 GMainDispatch *dispatch = get_dispatch ();
2051 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
2055 * g_source_is_destroyed:
2056 * @source: a #GSource
2058 * Returns whether @source has been destroyed.
2060 * This is important when you operate upon your objects
2061 * from within idle handlers, but may have freed the object
2062 * before the dispatch of your idle handler.
2066 * idle_callback (gpointer data)
2068 * SomeWidget *self = data;
2070 * GDK_THREADS_ENTER (<!-- -->);
2071 * /<!-- -->* do stuff with self *<!-- -->/
2072 * self->idle_id = 0;
2073 * GDK_THREADS_LEAVE (<!-- -->);
2079 * some_widget_do_stuff_later (SomeWidget *self)
2081 * self->idle_id = g_idle_add (idle_callback, self);
2085 * some_widget_finalize (GObject *object)
2087 * SomeWidget *self = SOME_WIDGET (object);
2089 * if (self->idle_id)
2090 * g_source_remove (self->idle_id);
2092 * G_OBJECT_CLASS (parent_class)->finalize (object);
2096 * This will fail in a multi-threaded application if the
2097 * widget is destroyed before the idle handler fires due
2098 * to the use after free in the callback. A solution, to
2099 * this particular problem, is to check to if the source
2100 * has already been destroy within the callback.
2104 * idle_callback (gpointer data)
2106 * SomeWidget *self = data;
2108 * GDK_THREADS_ENTER ();
2109 * if (!g_source_is_destroyed (g_main_current_source ()))
2111 * /<!-- -->* do stuff with self *<!-- -->/
2113 * GDK_THREADS_LEAVE ();
2119 * Return value: %TRUE if the source has been destroyed
2124 g_source_is_destroyed (GSource *source)
2126 return SOURCE_DESTROYED (source);
2129 /* Temporarily remove all this source's file descriptors from the
2130 * poll(), so that if data comes available for one of the file descriptors
2131 * we don't continually spin in the poll()
2133 /* HOLDS: source->context's lock */
2135 block_source (GSource *source)
2139 g_return_if_fail (!SOURCE_BLOCKED (source));
2141 tmp_list = source->poll_fds;
2144 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2145 tmp_list = tmp_list->next;
2149 /* HOLDS: source->context's lock */
2151 unblock_source (GSource *source)
2155 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
2156 g_return_if_fail (!SOURCE_DESTROYED (source));
2158 tmp_list = source->poll_fds;
2161 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2162 tmp_list = tmp_list->next;
2166 /* HOLDS: context's lock */
2168 g_main_dispatch (GMainContext *context)
2170 GMainDispatch *current = get_dispatch ();
2173 for (i = 0; i < context->pending_dispatches->len; i++)
2175 GSource *source = context->pending_dispatches->pdata[i];
2177 context->pending_dispatches->pdata[i] = NULL;
2180 source->flags &= ~G_SOURCE_READY;
2182 if (!SOURCE_DESTROYED (source))
2184 gboolean was_in_call;
2185 gpointer user_data = NULL;
2186 GSourceFunc callback = NULL;
2187 GSourceCallbackFuncs *cb_funcs;
2189 gboolean need_destroy;
2191 gboolean (*dispatch) (GSource *,
2194 GSList current_source_link;
2196 dispatch = source->source_funcs->dispatch;
2197 cb_funcs = source->callback_funcs;
2198 cb_data = source->callback_data;
2201 cb_funcs->ref (cb_data);
2203 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2204 block_source (source);
2206 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2207 source->flags |= G_HOOK_FLAG_IN_CALL;
2210 cb_funcs->get (cb_data, source, &callback, &user_data);
2212 UNLOCK_CONTEXT (context);
2215 /* The on-stack allocation of the GSList is unconventional, but
2216 * we know that the lifetime of the link is bounded to this
2217 * function as the link is kept in a thread specific list and
2218 * not manipulated outside of this function and its descendants.
2219 * Avoiding the overhead of a g_slist_alloc() is useful as many
2220 * applications do little more than dispatch events.
2222 * This is a performance hack - do not revert to g_slist_prepend()!
2224 current_source_link.data = source;
2225 current_source_link.next = current->dispatching_sources;
2226 current->dispatching_sources = ¤t_source_link;
2227 need_destroy = ! dispatch (source,
2230 g_assert (current->dispatching_sources == ¤t_source_link);
2231 current->dispatching_sources = current_source_link.next;
2235 cb_funcs->unref (cb_data);
2237 LOCK_CONTEXT (context);
2240 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2242 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2243 !SOURCE_DESTROYED (source))
2244 unblock_source (source);
2246 /* Note: this depends on the fact that we can't switch
2247 * sources from one main context to another
2249 if (need_destroy && !SOURCE_DESTROYED (source))
2251 g_assert (source->context == context);
2252 g_source_destroy_internal (source, context, TRUE);
2256 SOURCE_UNREF (source, context);
2259 g_ptr_array_set_size (context->pending_dispatches, 0);
2262 /* Holds context's lock */
2263 static inline GSource *
2264 next_valid_source (GMainContext *context,
2267 GSource *new_source = source ? source->next : context->source_list;
2271 if (!SOURCE_DESTROYED (new_source))
2273 new_source->ref_count++;
2277 new_source = new_source->next;
2281 SOURCE_UNREF (source, context);
2287 * g_main_context_acquire:
2288 * @context: a #GMainContext
2290 * Tries to become the owner of the specified context.
2291 * If some other thread is the owner of the context,
2292 * returns %FALSE immediately. Ownership is properly
2293 * recursive: the owner can require ownership again
2294 * and will release ownership when g_main_context_release()
2295 * is called as many times as g_main_context_acquire().
2297 * You must be the owner of a context before you
2298 * can call g_main_context_prepare(), g_main_context_query(),
2299 * g_main_context_check(), g_main_context_dispatch().
2301 * Return value: %TRUE if the operation succeeded, and
2302 * this thread is now the owner of @context.
2305 g_main_context_acquire (GMainContext *context)
2307 #ifdef G_THREADS_ENABLED
2308 gboolean result = FALSE;
2309 GThread *self = G_THREAD_SELF;
2311 if (context == NULL)
2312 context = g_main_context_default ();
2314 LOCK_CONTEXT (context);
2316 if (!context->owner)
2318 context->owner = self;
2319 g_assert (context->owner_count == 0);
2322 if (context->owner == self)
2324 context->owner_count++;
2328 UNLOCK_CONTEXT (context);
2331 #else /* !G_THREADS_ENABLED */
2333 #endif /* G_THREADS_ENABLED */
2337 * g_main_context_release:
2338 * @context: a #GMainContext
2340 * Releases ownership of a context previously acquired by this thread
2341 * with g_main_context_acquire(). If the context was acquired multiple
2342 * times, the ownership will be released only when g_main_context_release()
2343 * is called as many times as it was acquired.
2346 g_main_context_release (GMainContext *context)
2348 #ifdef G_THREADS_ENABLED
2349 if (context == NULL)
2350 context = g_main_context_default ();
2352 LOCK_CONTEXT (context);
2354 context->owner_count--;
2355 if (context->owner_count == 0)
2357 context->owner = NULL;
2359 if (context->waiters)
2361 GMainWaiter *waiter = context->waiters->data;
2362 gboolean loop_internal_waiter =
2363 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
2364 context->waiters = g_slist_delete_link (context->waiters,
2366 if (!loop_internal_waiter)
2367 g_mutex_lock (waiter->mutex);
2369 g_cond_signal (waiter->cond);
2371 if (!loop_internal_waiter)
2372 g_mutex_unlock (waiter->mutex);
2376 UNLOCK_CONTEXT (context);
2377 #endif /* G_THREADS_ENABLED */
2381 * g_main_context_wait:
2382 * @context: a #GMainContext
2383 * @cond: a condition variable
2384 * @mutex: a mutex, currently held
2386 * Tries to become the owner of the specified context,
2387 * as with g_main_context_acquire(). But if another thread
2388 * is the owner, atomically drop @mutex and wait on @cond until
2389 * that owner releases ownership or until @cond is signaled, then
2390 * try again (once) to become the owner.
2392 * Return value: %TRUE if the operation succeeded, and
2393 * this thread is now the owner of @context.
2396 g_main_context_wait (GMainContext *context,
2400 #ifdef G_THREADS_ENABLED
2401 gboolean result = FALSE;
2402 GThread *self = G_THREAD_SELF;
2403 gboolean loop_internal_waiter;
2405 if (context == NULL)
2406 context = g_main_context_default ();
2408 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2410 if (!loop_internal_waiter)
2411 LOCK_CONTEXT (context);
2413 if (context->owner && context->owner != self)
2418 waiter.mutex = mutex;
2420 context->waiters = g_slist_append (context->waiters, &waiter);
2422 if (!loop_internal_waiter)
2423 UNLOCK_CONTEXT (context);
2424 g_cond_wait (cond, mutex);
2425 if (!loop_internal_waiter)
2426 LOCK_CONTEXT (context);
2428 context->waiters = g_slist_remove (context->waiters, &waiter);
2431 if (!context->owner)
2433 context->owner = self;
2434 g_assert (context->owner_count == 0);
2437 if (context->owner == self)
2439 context->owner_count++;
2443 if (!loop_internal_waiter)
2444 UNLOCK_CONTEXT (context);
2447 #else /* !G_THREADS_ENABLED */
2449 #endif /* G_THREADS_ENABLED */
2453 * g_main_context_prepare:
2454 * @context: a #GMainContext
2455 * @priority: location to store priority of highest priority
2456 * source already ready.
2458 * Prepares to poll sources within a main loop. The resulting information
2459 * for polling is determined by calling g_main_context_query ().
2461 * Return value: %TRUE if some source is ready to be dispatched
2465 g_main_context_prepare (GMainContext *context,
2470 gint current_priority = G_MAXINT;
2473 if (context == NULL)
2474 context = g_main_context_default ();
2476 LOCK_CONTEXT (context);
2478 context->time_is_fresh = FALSE;
2479 context->current_time_is_fresh = FALSE;
2481 if (context->in_check_or_prepare)
2483 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2484 "prepare() member.");
2485 UNLOCK_CONTEXT (context);
2489 #ifdef G_THREADS_ENABLED
2490 if (context->poll_waiting)
2492 g_warning("g_main_context_prepare(): main loop already active in another thread");
2493 UNLOCK_CONTEXT (context);
2497 context->poll_waiting = TRUE;
2498 #endif /* G_THREADS_ENABLED */
2501 /* If recursing, finish up current dispatch, before starting over */
2502 if (context->pending_dispatches)
2505 g_main_dispatch (context, ¤t_time);
2507 UNLOCK_CONTEXT (context);
2512 /* If recursing, clear list of pending dispatches */
2514 for (i = 0; i < context->pending_dispatches->len; i++)
2516 if (context->pending_dispatches->pdata[i])
2517 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2519 g_ptr_array_set_size (context->pending_dispatches, 0);
2521 /* Prepare all sources */
2523 context->timeout = -1;
2525 source = next_valid_source (context, NULL);
2528 gint source_timeout = -1;
2530 if ((n_ready > 0) && (source->priority > current_priority))
2532 SOURCE_UNREF (source, context);
2535 if (SOURCE_BLOCKED (source))
2538 if (!(source->flags & G_SOURCE_READY))
2541 gboolean (*prepare) (GSource *source,
2544 prepare = source->source_funcs->prepare;
2545 context->in_check_or_prepare++;
2546 UNLOCK_CONTEXT (context);
2548 result = (*prepare) (source, &source_timeout);
2550 LOCK_CONTEXT (context);
2551 context->in_check_or_prepare--;
2554 source->flags |= G_SOURCE_READY;
2557 if (source->flags & G_SOURCE_READY)
2560 current_priority = source->priority;
2561 context->timeout = 0;
2564 if (source_timeout >= 0)
2566 if (context->timeout < 0)
2567 context->timeout = source_timeout;
2569 context->timeout = MIN (context->timeout, source_timeout);
2573 source = next_valid_source (context, source);
2576 UNLOCK_CONTEXT (context);
2579 *priority = current_priority;
2581 return (n_ready > 0);
2585 * g_main_context_query:
2586 * @context: a #GMainContext
2587 * @max_priority: maximum priority source to check
2588 * @timeout_: location to store timeout to be used in polling
2589 * @fds: location to store #GPollFD records that need to be polled.
2590 * @n_fds: length of @fds.
2592 * Determines information necessary to poll this main loop.
2594 * Return value: the number of records actually stored in @fds,
2595 * or, if more than @n_fds records need to be stored, the number
2596 * of records that need to be stored.
2599 g_main_context_query (GMainContext *context,
2608 LOCK_CONTEXT (context);
2610 pollrec = context->poll_records;
2612 while (pollrec && max_priority >= pollrec->priority)
2614 /* We need to include entries with fd->events == 0 in the array because
2615 * otherwise if the application changes fd->events behind our back and
2616 * makes it non-zero, we'll be out of sync when we check the fds[] array.
2617 * (Changing fd->events after adding an FD wasn't an anticipated use of
2618 * this API, but it occurs in practice.) */
2621 fds[n_poll].fd = pollrec->fd->fd;
2622 /* In direct contradiction to the Unix98 spec, IRIX runs into
2623 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2624 * flags in the events field of the pollfd while it should
2625 * just ignoring them. So we mask them out here.
2627 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2628 fds[n_poll].revents = 0;
2631 pollrec = pollrec->next;
2635 #ifdef G_THREADS_ENABLED
2636 context->poll_changed = FALSE;
2641 *timeout = context->timeout;
2644 context->time_is_fresh = FALSE;
2645 context->current_time_is_fresh = FALSE;
2649 UNLOCK_CONTEXT (context);
2655 * g_main_context_check:
2656 * @context: a #GMainContext
2657 * @max_priority: the maximum numerical priority of sources to check
2658 * @fds: array of #GPollFD's that was passed to the last call to
2659 * g_main_context_query()
2660 * @n_fds: return value of g_main_context_query()
2662 * Passes the results of polling back to the main loop.
2664 * Return value: %TRUE if some sources are ready to be dispatched.
2667 g_main_context_check (GMainContext *context,
2677 LOCK_CONTEXT (context);
2679 if (context->in_check_or_prepare)
2681 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2682 "prepare() member.");
2683 UNLOCK_CONTEXT (context);
2687 #ifdef G_THREADS_ENABLED
2688 if (!context->poll_waiting)
2692 read (context->wake_up_pipe[0], &a, 1);
2696 context->poll_waiting = FALSE;
2698 /* If the set of poll file descriptors changed, bail out
2699 * and let the main loop rerun
2701 if (context->poll_changed)
2703 UNLOCK_CONTEXT (context);
2706 #endif /* G_THREADS_ENABLED */
2708 pollrec = context->poll_records;
2712 if (pollrec->fd->events)
2713 pollrec->fd->revents = fds[i].revents;
2715 pollrec = pollrec->next;
2719 source = next_valid_source (context, NULL);
2722 if ((n_ready > 0) && (source->priority > max_priority))
2724 SOURCE_UNREF (source, context);
2727 if (SOURCE_BLOCKED (source))
2730 if (!(source->flags & G_SOURCE_READY))
2733 gboolean (*check) (GSource *source);
2735 check = source->source_funcs->check;
2737 context->in_check_or_prepare++;
2738 UNLOCK_CONTEXT (context);
2740 result = (*check) (source);
2742 LOCK_CONTEXT (context);
2743 context->in_check_or_prepare--;
2746 source->flags |= G_SOURCE_READY;
2749 if (source->flags & G_SOURCE_READY)
2751 source->ref_count++;
2752 g_ptr_array_add (context->pending_dispatches, source);
2756 /* never dispatch sources with less priority than the first
2757 * one we choose to dispatch
2759 max_priority = source->priority;
2763 source = next_valid_source (context, source);
2766 UNLOCK_CONTEXT (context);
2772 * g_main_context_dispatch:
2773 * @context: a #GMainContext
2775 * Dispatches all pending sources.
2778 g_main_context_dispatch (GMainContext *context)
2780 LOCK_CONTEXT (context);
2782 if (context->pending_dispatches->len > 0)
2784 g_main_dispatch (context);
2787 UNLOCK_CONTEXT (context);
2790 /* HOLDS context lock */
2792 g_main_context_iterate (GMainContext *context,
2799 gboolean some_ready;
2800 gint nfds, allocated_nfds;
2801 GPollFD *fds = NULL;
2803 UNLOCK_CONTEXT (context);
2805 #ifdef G_THREADS_ENABLED
2806 if (!g_main_context_acquire (context))
2808 gboolean got_ownership;
2810 LOCK_CONTEXT (context);
2812 g_return_val_if_fail (g_thread_supported (), FALSE);
2818 context->cond = g_cond_new ();
2820 got_ownership = g_main_context_wait (context,
2822 g_static_mutex_get_mutex (&context->mutex));
2828 LOCK_CONTEXT (context);
2829 #endif /* G_THREADS_ENABLED */
2831 if (!context->cached_poll_array)
2833 context->cached_poll_array_size = context->n_poll_records;
2834 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2837 allocated_nfds = context->cached_poll_array_size;
2838 fds = context->cached_poll_array;
2840 UNLOCK_CONTEXT (context);
2842 g_main_context_prepare (context, &max_priority);
2844 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
2845 allocated_nfds)) > allocated_nfds)
2847 LOCK_CONTEXT (context);
2849 context->cached_poll_array_size = allocated_nfds = nfds;
2850 context->cached_poll_array = fds = g_new (GPollFD, nfds);
2851 UNLOCK_CONTEXT (context);
2857 g_main_context_poll (context, timeout, max_priority, fds, nfds);
2859 some_ready = g_main_context_check (context, max_priority, fds, nfds);
2862 g_main_context_dispatch (context);
2864 #ifdef G_THREADS_ENABLED
2865 g_main_context_release (context);
2866 #endif /* G_THREADS_ENABLED */
2868 LOCK_CONTEXT (context);
2874 * g_main_context_pending:
2875 * @context: a #GMainContext (if %NULL, the default context will be used)
2877 * Checks if any sources have pending events for the given context.
2879 * Return value: %TRUE if events are pending.
2882 g_main_context_pending (GMainContext *context)
2887 context = g_main_context_default();
2889 LOCK_CONTEXT (context);
2890 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
2891 UNLOCK_CONTEXT (context);
2897 * g_main_context_iteration:
2898 * @context: a #GMainContext (if %NULL, the default context will be used)
2899 * @may_block: whether the call may block.
2901 * Runs a single iteration for the given main loop. This involves
2902 * checking to see if any event sources are ready to be processed,
2903 * then if no events sources are ready and @may_block is %TRUE, waiting
2904 * for a source to become ready, then dispatching the highest priority
2905 * events sources that are ready. Otherwise, if @may_block is %FALSE
2906 * sources are not waited to become ready, only those highest priority
2907 * events sources will be dispatched (if any), that are ready at this
2908 * given moment without further waiting.
2910 * Note that even when @may_block is %TRUE, it is still possible for
2911 * g_main_context_iteration() to return %FALSE, since the the wait may
2912 * be interrupted for other reasons than an event source becoming ready.
2914 * Return value: %TRUE if events were dispatched.
2917 g_main_context_iteration (GMainContext *context, gboolean may_block)
2922 context = g_main_context_default();
2924 LOCK_CONTEXT (context);
2925 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
2926 UNLOCK_CONTEXT (context);
2933 * @context: a #GMainContext (if %NULL, the default context will be used).
2934 * @is_running: set to %TRUE to indicate that the loop is running. This
2935 * is not very important since calling g_main_loop_run() will set this to
2938 * Creates a new #GMainLoop structure.
2940 * Return value: a new #GMainLoop.
2943 g_main_loop_new (GMainContext *context,
2944 gboolean is_running)
2949 context = g_main_context_default();
2951 g_main_context_ref (context);
2953 loop = g_new0 (GMainLoop, 1);
2954 loop->context = context;
2955 loop->is_running = is_running != FALSE;
2956 loop->ref_count = 1;
2963 * @loop: a #GMainLoop
2965 * Increases the reference count on a #GMainLoop object by one.
2967 * Return value: @loop
2970 g_main_loop_ref (GMainLoop *loop)
2972 g_return_val_if_fail (loop != NULL, NULL);
2973 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2975 g_atomic_int_inc (&loop->ref_count);
2981 * g_main_loop_unref:
2982 * @loop: a #GMainLoop
2984 * Decreases the reference count on a #GMainLoop object by one. If
2985 * the result is zero, free the loop and free all associated memory.
2988 g_main_loop_unref (GMainLoop *loop)
2990 g_return_if_fail (loop != NULL);
2991 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2993 if (!g_atomic_int_dec_and_test (&loop->ref_count))
2996 g_main_context_unref (loop->context);
3002 * @loop: a #GMainLoop
3004 * Runs a main loop until g_main_loop_quit() is called on the loop.
3005 * If this is called for the thread of the loop's #GMainContext,
3006 * it will process events from the loop, otherwise it will
3010 g_main_loop_run (GMainLoop *loop)
3012 GThread *self = G_THREAD_SELF;
3014 g_return_if_fail (loop != NULL);
3015 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3017 #ifdef G_THREADS_ENABLED
3018 if (!g_main_context_acquire (loop->context))
3020 gboolean got_ownership = FALSE;
3022 /* Another thread owns this context */
3023 if (!g_thread_supported ())
3025 g_warning ("g_main_loop_run() was called from second thread but "
3026 "g_thread_init() was never called.");
3030 LOCK_CONTEXT (loop->context);
3032 g_atomic_int_inc (&loop->ref_count);
3034 if (!loop->is_running)
3035 loop->is_running = TRUE;
3037 if (!loop->context->cond)
3038 loop->context->cond = g_cond_new ();
3040 while (loop->is_running && !got_ownership)
3041 got_ownership = g_main_context_wait (loop->context,
3042 loop->context->cond,
3043 g_static_mutex_get_mutex (&loop->context->mutex));
3045 if (!loop->is_running)
3047 UNLOCK_CONTEXT (loop->context);
3049 g_main_context_release (loop->context);
3050 g_main_loop_unref (loop);
3054 g_assert (got_ownership);
3057 LOCK_CONTEXT (loop->context);
3058 #endif /* G_THREADS_ENABLED */
3060 if (loop->context->in_check_or_prepare)
3062 g_warning ("g_main_loop_run(): called recursively from within a source's "
3063 "check() or prepare() member, iteration not possible.");
3067 g_atomic_int_inc (&loop->ref_count);
3068 loop->is_running = TRUE;
3069 while (loop->is_running)
3070 g_main_context_iterate (loop->context, TRUE, TRUE, self);
3072 UNLOCK_CONTEXT (loop->context);
3074 #ifdef G_THREADS_ENABLED
3075 g_main_context_release (loop->context);
3076 #endif /* G_THREADS_ENABLED */
3078 g_main_loop_unref (loop);
3083 * @loop: a #GMainLoop
3085 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3086 * for the loop will return.
3088 * Note that sources that have already been dispatched when
3089 * g_main_loop_quit() is called will still be executed.
3092 g_main_loop_quit (GMainLoop *loop)
3094 g_return_if_fail (loop != NULL);
3095 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3097 LOCK_CONTEXT (loop->context);
3098 loop->is_running = FALSE;
3099 g_main_context_wakeup_unlocked (loop->context);
3101 #ifdef G_THREADS_ENABLED
3102 if (loop->context->cond)
3103 g_cond_broadcast (loop->context->cond);
3104 #endif /* G_THREADS_ENABLED */
3106 UNLOCK_CONTEXT (loop->context);
3110 * g_main_loop_is_running:
3111 * @loop: a #GMainLoop.
3113 * Checks to see if the main loop is currently being run via g_main_loop_run().
3115 * Return value: %TRUE if the mainloop is currently being run.
3118 g_main_loop_is_running (GMainLoop *loop)
3120 g_return_val_if_fail (loop != NULL, FALSE);
3121 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3123 return loop->is_running;
3127 * g_main_loop_get_context:
3128 * @loop: a #GMainLoop.
3130 * Returns the #GMainContext of @loop.
3132 * Return value: the #GMainContext of @loop
3135 g_main_loop_get_context (GMainLoop *loop)
3137 g_return_val_if_fail (loop != NULL, NULL);
3138 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3140 return loop->context;
3143 /* HOLDS: context's lock */
3145 g_main_context_poll (GMainContext *context,
3151 #ifdef G_MAIN_POLL_DEBUG
3157 GPollFunc poll_func;
3159 if (n_fds || timeout != 0)
3161 #ifdef G_MAIN_POLL_DEBUG
3162 if (_g_main_poll_debug)
3164 g_print ("polling context=%p n=%d timeout=%d\n",
3165 context, n_fds, timeout);
3166 poll_timer = g_timer_new ();
3170 LOCK_CONTEXT (context);
3172 poll_func = context->poll_func;
3174 UNLOCK_CONTEXT (context);
3175 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3178 g_warning ("poll(2) failed due to: %s.",
3179 g_strerror (errno));
3181 /* If g_poll () returns -1, it has already called g_warning() */
3185 #ifdef G_MAIN_POLL_DEBUG
3186 if (_g_main_poll_debug)
3188 LOCK_CONTEXT (context);
3190 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3193 g_timer_elapsed (poll_timer, NULL));
3194 g_timer_destroy (poll_timer);
3195 pollrec = context->poll_records;
3197 while (pollrec != NULL)
3202 if (fds[i].fd == pollrec->fd->fd &&
3203 pollrec->fd->events &&
3206 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3207 if (fds[i].revents & G_IO_IN)
3209 if (fds[i].revents & G_IO_OUT)
3211 if (fds[i].revents & G_IO_PRI)
3213 if (fds[i].revents & G_IO_ERR)
3215 if (fds[i].revents & G_IO_HUP)
3217 if (fds[i].revents & G_IO_NVAL)
3223 pollrec = pollrec->next;
3227 UNLOCK_CONTEXT (context);
3230 } /* if (n_fds || timeout != 0) */
3234 * g_main_context_add_poll:
3235 * @context: a #GMainContext (or %NULL for the default context)
3236 * @fd: a #GPollFD structure holding information about a file
3237 * descriptor to watch.
3238 * @priority: the priority for this file descriptor which should be
3239 * the same as the priority used for g_source_attach() to ensure that the
3240 * file descriptor is polled whenever the results may be needed.
3242 * Adds a file descriptor to the set of file descriptors polled for
3243 * this context. This will very seldomly be used directly. Instead
3244 * a typical event source will use g_source_add_poll() instead.
3247 g_main_context_add_poll (GMainContext *context,
3252 context = g_main_context_default ();
3254 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3255 g_return_if_fail (fd);
3257 LOCK_CONTEXT (context);
3258 g_main_context_add_poll_unlocked (context, priority, fd);
3259 UNLOCK_CONTEXT (context);
3262 /* HOLDS: main_loop_lock */
3264 g_main_context_add_poll_unlocked (GMainContext *context,
3268 GPollRec *lastrec, *pollrec;
3269 GPollRec *newrec = g_slice_new (GPollRec);
3271 /* This file descriptor may be checked before we ever poll */
3274 newrec->priority = priority;
3277 pollrec = context->poll_records;
3278 while (pollrec && priority >= pollrec->priority)
3281 pollrec = pollrec->next;
3285 lastrec->next = newrec;
3287 context->poll_records = newrec;
3289 newrec->next = pollrec;
3291 context->n_poll_records++;
3293 #ifdef G_THREADS_ENABLED
3294 context->poll_changed = TRUE;
3296 /* Now wake up the main loop if it is waiting in the poll() */
3297 g_main_context_wakeup_unlocked (context);
3302 * g_main_context_remove_poll:
3303 * @context:a #GMainContext
3304 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3306 * Removes file descriptor from the set of file descriptors to be
3307 * polled for a particular context.
3310 g_main_context_remove_poll (GMainContext *context,
3314 context = g_main_context_default ();
3316 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3317 g_return_if_fail (fd);
3319 LOCK_CONTEXT (context);
3320 g_main_context_remove_poll_unlocked (context, fd);
3321 UNLOCK_CONTEXT (context);
3325 g_main_context_remove_poll_unlocked (GMainContext *context,
3328 GPollRec *pollrec, *lastrec;
3331 pollrec = context->poll_records;
3335 if (pollrec->fd == fd)
3337 if (lastrec != NULL)
3338 lastrec->next = pollrec->next;
3340 context->poll_records = pollrec->next;
3342 g_slice_free (GPollRec, pollrec);
3344 context->n_poll_records--;
3348 pollrec = pollrec->next;
3351 #ifdef G_THREADS_ENABLED
3352 context->poll_changed = TRUE;
3354 /* Now wake up the main loop if it is waiting in the poll() */
3355 g_main_context_wakeup_unlocked (context);
3360 * g_source_get_current_time:
3361 * @source: a #GSource
3362 * @timeval: #GTimeVal structure in which to store current time.
3364 * Gets the "current time" to be used when checking
3365 * this source. The advantage of calling this function over
3366 * calling g_get_current_time() directly is that when
3367 * checking multiple sources, GLib can cache a single value
3368 * instead of having to repeatedly get the system time.
3370 * Deprecated: 2.28: use g_source_get_time() instead
3373 g_source_get_current_time (GSource *source,
3376 GMainContext *context;
3378 g_return_if_fail (source->context != NULL);
3380 context = source->context;
3382 LOCK_CONTEXT (context);
3384 if (!context->current_time_is_fresh)
3386 g_get_current_time (&context->current_time);
3387 context->current_time_is_fresh = TRUE;
3390 *timeval = context->current_time;
3392 UNLOCK_CONTEXT (context);
3396 * g_source_get_time:
3397 * @source: a #GSource
3398 * @timespec: #GTimeSpec structure in which to store the time
3400 * Gets the time to be used when checking this source. The advantage of
3401 * calling this function over calling g_get_monotonic_time() directly is
3402 * that when checking multiple sources, GLib can cache a single value
3403 * instead of having to repeatedly get the system monotonic time.
3405 * The time here is the system monotonic time, if available, or some
3406 * other reasonable alternative otherwise. See g_get_monotonic_time().
3411 g_source_get_time (GSource *source,
3412 GTimeSpec *timespec)
3414 GMainContext *context;
3416 g_return_if_fail (source->context != NULL);
3418 context = source->context;
3420 LOCK_CONTEXT (context);
3422 if (!context->time_is_fresh)
3424 g_get_monotonic_time (&context->time);
3425 context->time_is_fresh = TRUE;
3428 *timespec = context->time;
3430 UNLOCK_CONTEXT (context);
3434 * g_main_context_set_poll_func:
3435 * @context: a #GMainContext
3436 * @func: the function to call to poll all file descriptors
3438 * Sets the function to use to handle polling of file descriptors. It
3439 * will be used instead of the poll() system call
3440 * (or GLib's replacement function, which is used where
3441 * poll() isn't available).
3443 * This function could possibly be used to integrate the GLib event
3444 * loop with an external event loop.
3447 g_main_context_set_poll_func (GMainContext *context,
3451 context = g_main_context_default ();
3453 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3455 LOCK_CONTEXT (context);
3458 context->poll_func = func;
3460 context->poll_func = g_poll;
3462 UNLOCK_CONTEXT (context);
3466 * g_main_context_get_poll_func:
3467 * @context: a #GMainContext
3469 * Gets the poll function set by g_main_context_set_poll_func().
3471 * Return value: the poll function
3474 g_main_context_get_poll_func (GMainContext *context)
3479 context = g_main_context_default ();
3481 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3483 LOCK_CONTEXT (context);
3484 result = context->poll_func;
3485 UNLOCK_CONTEXT (context);
3490 /* HOLDS: context's lock */
3491 /* Wake the main loop up from a poll() */
3493 g_main_context_wakeup_unlocked (GMainContext *context)
3495 #ifdef G_THREADS_ENABLED
3496 if (g_thread_supported() && context->poll_waiting)
3498 context->poll_waiting = FALSE;
3500 write (context->wake_up_pipe[1], "A", 1);
3502 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
3509 * g_main_context_wakeup:
3510 * @context: a #GMainContext
3512 * If @context is currently waiting in a poll(), interrupt
3513 * the poll(), and continue the iteration process.
3516 g_main_context_wakeup (GMainContext *context)
3519 context = g_main_context_default ();
3521 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3523 LOCK_CONTEXT (context);
3524 g_main_context_wakeup_unlocked (context);
3525 UNLOCK_CONTEXT (context);
3529 * g_main_context_is_owner:
3530 * @context: a #GMainContext
3532 * Determines whether this thread holds the (recursive)
3533 * ownership of this #GMaincontext. This is useful to
3534 * know before waiting on another thread that may be
3535 * blocking to get ownership of @context.
3537 * Returns: %TRUE if current thread is owner of @context.
3542 g_main_context_is_owner (GMainContext *context)
3547 context = g_main_context_default ();
3549 #ifdef G_THREADS_ENABLED
3550 LOCK_CONTEXT (context);
3551 is_owner = context->owner == G_THREAD_SELF;
3552 UNLOCK_CONTEXT (context);
3563 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3564 GTimeSpec *current_time)
3566 guint seconds = timeout_source->interval / 1000;
3567 guint msecs = timeout_source->interval - seconds * 1000;
3569 timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
3570 timeout_source->expiration.tv_nsec = current_time->tv_nsec + msecs * 1000000;
3571 if (timeout_source->expiration.tv_nsec >= 1000000000)
3573 timeout_source->expiration.tv_nsec -= 1000000000;
3574 timeout_source->expiration.tv_sec++;
3576 if (timeout_source->seconds)
3578 static gint timer_perturb = -1;
3580 if (timer_perturb == -1)
3583 * we want a per machine/session unique 'random' value; try the dbus
3584 * address first, that has a UUID in it. If there is no dbus, use the
3585 * hostname for hashing.
3587 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3588 if (!session_bus_address)
3589 session_bus_address = g_getenv ("HOSTNAME");
3590 if (session_bus_address)
3591 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
3596 /* We want the microseconds part of the timeout to land on the
3597 * 'timer_perturb' mark, but we need to make sure we don't try to
3598 * set the timeout in the past. We do this by ensuring that we
3599 * always only *increase* the expiration time by adding a full
3600 * second in the case that the microsecond portion decreases.
3602 if (timer_perturb * 1000 < timeout_source->expiration.tv_nsec)
3603 timeout_source->expiration.tv_sec++;
3605 timeout_source->expiration.tv_nsec = timer_perturb * 1000;
3610 g_timeout_prepare (GSource *source,
3617 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3619 g_source_get_time (source, &now);
3621 sec = timeout_source->expiration.tv_sec - now.tv_sec;
3622 msec = (timeout_source->expiration.tv_nsec - now.tv_nsec) / 1000000;
3624 /* We do the following in a rather convoluted fashion to deal with
3625 * the fact that we don't have an integral type big enough to hold
3626 * the difference of two timevals in millseconds.
3628 if (sec < 0 || (sec == 0 && msec < 0))
3632 glong interval_sec = timeout_source->interval / 1000;
3633 glong interval_msec = timeout_source->interval % 1000;
3641 if (sec > interval_sec ||
3642 (sec == interval_sec && msec > interval_msec))
3644 /* The system time has been set backwards, so we
3645 * reset the expiration time to now + timeout_source->interval;
3646 * this at least avoids hanging for long periods of time.
3648 g_timeout_set_expiration (timeout_source, &now);
3649 msec = MIN (G_MAXINT, timeout_source->interval);
3653 msec = MIN (G_MAXINT, (guint)msec + 1000 * (guint)sec);
3657 *timeout = (gint)msec;
3663 g_timeout_check (GSource *source)
3666 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3668 g_source_get_time (source, &now);
3670 return ((timeout_source->expiration.tv_sec < now.tv_sec) ||
3671 ((timeout_source->expiration.tv_sec == now.tv_sec) &&
3672 (timeout_source->expiration.tv_nsec <= now.tv_nsec)));
3676 g_timeout_dispatch (GSource *source,
3677 GSourceFunc callback,
3680 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3684 g_warning ("Timeout source dispatched without callback\n"
3685 "You must call g_source_set_callback().");
3689 if (callback (user_data))
3693 g_source_get_time (source, &now);
3694 g_timeout_set_expiration (timeout_source, &now);
3703 * g_timeout_source_new:
3704 * @interval: the timeout interval in milliseconds.
3706 * Creates a new timeout source.
3708 * The source will not initially be associated with any #GMainContext
3709 * and must be added to one with g_source_attach() before it will be
3712 * Return value: the newly-created timeout source
3715 g_timeout_source_new (guint interval)
3717 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3718 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3721 timeout_source->interval = interval;
3723 g_get_monotonic_time (&now);
3724 g_timeout_set_expiration (timeout_source, &now);
3730 * g_timeout_source_new_seconds:
3731 * @interval: the timeout interval in seconds
3733 * Creates a new timeout source.
3735 * The source will not initially be associated with any #GMainContext
3736 * and must be added to one with g_source_attach() before it will be
3739 * The scheduling granularity/accuracy of this timeout source will be
3742 * Return value: the newly-created timeout source
3747 g_timeout_source_new_seconds (guint interval)
3749 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3750 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3753 timeout_source->interval = 1000 * interval;
3754 timeout_source->seconds = TRUE;
3756 g_get_monotonic_time (&now);
3757 g_timeout_set_expiration (timeout_source, &now);
3764 * g_timeout_add_full:
3765 * @priority: the priority of the timeout source. Typically this will be in
3766 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3767 * @interval: the time between calls to the function, in milliseconds
3768 * (1/1000ths of a second)
3769 * @function: function to call
3770 * @data: data to pass to @function
3771 * @notify: function to call when the timeout is removed, or %NULL
3773 * Sets a function to be called at regular intervals, with the given
3774 * priority. The function is called repeatedly until it returns
3775 * %FALSE, at which point the timeout is automatically destroyed and
3776 * the function will not be called again. The @notify function is
3777 * called when the timeout is destroyed. The first call to the
3778 * function will be at the end of the first @interval.
3780 * Note that timeout functions may be delayed, due to the processing of other
3781 * event sources. Thus they should not be relied on for precise timing.
3782 * After each call to the timeout function, the time of the next
3783 * timeout is recalculated based on the current time and the given interval
3784 * (it does not try to 'catch up' time lost in delays).
3786 * This internally creates a main loop source using g_timeout_source_new()
3787 * and attaches it to the main loop context using g_source_attach(). You can
3788 * do these steps manually if you need greater control.
3790 * Return value: the ID (greater than 0) of the event source.
3793 g_timeout_add_full (gint priority,
3795 GSourceFunc function,
3797 GDestroyNotify notify)
3802 g_return_val_if_fail (function != NULL, 0);
3804 source = g_timeout_source_new (interval);
3806 if (priority != G_PRIORITY_DEFAULT)
3807 g_source_set_priority (source, priority);
3809 g_source_set_callback (source, function, data, notify);
3810 id = g_source_attach (source, NULL);
3811 g_source_unref (source);
3818 * @interval: the time between calls to the function, in milliseconds
3819 * (1/1000ths of a second)
3820 * @function: function to call
3821 * @data: data to pass to @function
3823 * Sets a function to be called at regular intervals, with the default
3824 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
3825 * until it returns %FALSE, at which point the timeout is automatically
3826 * destroyed and the function will not be called again. The first call
3827 * to the function will be at the end of the first @interval.
3829 * Note that timeout functions may be delayed, due to the processing of other
3830 * event sources. Thus they should not be relied on for precise timing.
3831 * After each call to the timeout function, the time of the next
3832 * timeout is recalculated based on the current time and the given interval
3833 * (it does not try to 'catch up' time lost in delays).
3835 * If you want to have a timer in the "seconds" range and do not care
3836 * about the exact time of the first call of the timer, use the
3837 * g_timeout_add_seconds() function; this function allows for more
3838 * optimizations and more efficient system power usage.
3840 * This internally creates a main loop source using g_timeout_source_new()
3841 * and attaches it to the main loop context using g_source_attach(). You can
3842 * do these steps manually if you need greater control.
3844 * Return value: the ID (greater than 0) of the event source.
3847 g_timeout_add (guint32 interval,
3848 GSourceFunc function,
3851 return g_timeout_add_full (G_PRIORITY_DEFAULT,
3852 interval, function, data, NULL);
3856 * g_timeout_add_seconds_full:
3857 * @priority: the priority of the timeout source. Typically this will be in
3858 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3859 * @interval: the time between calls to the function, in seconds
3860 * @function: function to call
3861 * @data: data to pass to @function
3862 * @notify: function to call when the timeout is removed, or %NULL
3864 * Sets a function to be called at regular intervals, with @priority.
3865 * The function is called repeatedly until it returns %FALSE, at which
3866 * point the timeout is automatically destroyed and the function will
3867 * not be called again.
3869 * Unlike g_timeout_add(), this function operates at whole second granularity.
3870 * The initial starting point of the timer is determined by the implementation
3871 * and the implementation is expected to group multiple timers together so that
3872 * they fire all at the same time.
3873 * To allow this grouping, the @interval to the first timer is rounded
3874 * and can deviate up to one second from the specified interval.
3875 * Subsequent timer iterations will generally run at the specified interval.
3877 * Note that timeout functions may be delayed, due to the processing of other
3878 * event sources. Thus they should not be relied on for precise timing.
3879 * After each call to the timeout function, the time of the next
3880 * timeout is recalculated based on the current time and the given @interval
3882 * If you want timing more precise than whole seconds, use g_timeout_add()
3885 * The grouping of timers to fire at the same time results in a more power
3886 * and CPU efficient behavior so if your timer is in multiples of seconds
3887 * and you don't require the first timer exactly one second from now, the
3888 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
3890 * This internally creates a main loop source using
3891 * g_timeout_source_new_seconds() and attaches it to the main loop context
3892 * using g_source_attach(). You can do these steps manually if you need
3895 * Return value: the ID (greater than 0) of the event source.
3900 g_timeout_add_seconds_full (gint priority,
3902 GSourceFunc function,
3904 GDestroyNotify notify)
3909 g_return_val_if_fail (function != NULL, 0);
3911 source = g_timeout_source_new_seconds (interval);
3913 if (priority != G_PRIORITY_DEFAULT)
3914 g_source_set_priority (source, priority);
3916 g_source_set_callback (source, function, data, notify);
3917 id = g_source_attach (source, NULL);
3918 g_source_unref (source);
3924 * g_timeout_add_seconds:
3925 * @interval: the time between calls to the function, in seconds
3926 * @function: function to call
3927 * @data: data to pass to @function
3929 * Sets a function to be called at regular intervals with the default
3930 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
3931 * it returns %FALSE, at which point the timeout is automatically destroyed
3932 * and the function will not be called again.
3934 * This internally creates a main loop source using
3935 * g_timeout_source_new_seconds() and attaches it to the main loop context
3936 * using g_source_attach(). You can do these steps manually if you need
3937 * greater control. Also see g_timout_add_seconds_full().
3939 * Return value: the ID (greater than 0) of the event source.
3944 g_timeout_add_seconds (guint interval,
3945 GSourceFunc function,
3948 g_return_val_if_fail (function != NULL, 0);
3950 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
3953 /* Child watch functions */
3958 g_child_watch_prepare (GSource *source,
3967 g_child_watch_check (GSource *source)
3969 GChildWatchSource *child_watch_source;
3970 gboolean child_exited;
3972 child_watch_source = (GChildWatchSource *) source;
3974 child_exited = child_watch_source->poll.revents & G_IO_IN;
3981 * Note: We do _not_ check for the special value of STILL_ACTIVE
3982 * since we know that the process has exited and doing so runs into
3983 * problems if the child process "happens to return STILL_ACTIVE(259)"
3984 * as Microsoft's Platform SDK puts it.
3986 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
3988 gchar *emsg = g_win32_error_message (GetLastError ());
3989 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
3992 child_watch_source->child_status = -1;
3995 child_watch_source->child_status = child_status;
3998 return child_exited;
4001 #else /* G_OS_WIN32 */
4004 check_for_child_exited (GSource *source)
4006 GChildWatchSource *child_watch_source;
4009 /* protect against another SIGCHLD in the middle of this call */
4010 count = child_watch_count;
4012 child_watch_source = (GChildWatchSource *) source;
4014 if (child_watch_source->child_exited)
4017 if (child_watch_source->count < count)
4021 if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
4023 child_watch_source->child_status = child_status;
4024 child_watch_source->child_exited = TRUE;
4026 child_watch_source->count = count;
4029 return child_watch_source->child_exited;
4033 g_child_watch_prepare (GSource *source,
4038 return check_for_child_exited (source);
4043 g_child_watch_check (GSource *source)
4045 return check_for_child_exited (source);
4048 #endif /* G_OS_WIN32 */
4051 g_child_watch_dispatch (GSource *source,
4052 GSourceFunc callback,
4055 GChildWatchSource *child_watch_source;
4056 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
4058 child_watch_source = (GChildWatchSource *) source;
4062 g_warning ("Child watch source dispatched without callback\n"
4063 "You must call g_source_set_callback().");
4067 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
4069 /* We never keep a child watch source around as the child is gone */
4076 g_child_watch_signal_handler (int signum)
4078 child_watch_count ++;
4080 if (child_watch_init_state == CHILD_WATCH_INITIALIZED_THREADED)
4082 write (child_watch_wake_up_pipe[1], "B", 1);
4086 /* We count on the signal interrupting the poll in the same thread.
4092 g_child_watch_source_init_single (void)
4094 struct sigaction action;
4096 g_assert (! g_thread_supported());
4097 g_assert (child_watch_init_state == CHILD_WATCH_UNINITIALIZED);
4099 child_watch_init_state = CHILD_WATCH_INITIALIZED_SINGLE;
4101 action.sa_handler = g_child_watch_signal_handler;
4102 sigemptyset (&action.sa_mask);
4103 action.sa_flags = SA_NOCLDSTOP;
4104 sigaction (SIGCHLD, &action, NULL);
4107 G_GNUC_NORETURN static gpointer
4108 child_watch_helper_thread (gpointer data)
4115 read (child_watch_wake_up_pipe[0], b, 20);
4117 /* We were woken up. Wake up all other contexts in all other threads */
4118 G_LOCK (main_context_list);
4119 for (list = main_context_list; list; list = list->next)
4121 GMainContext *context;
4123 context = list->data;
4124 if (g_atomic_int_get (&context->ref_count) > 0)
4125 /* Due to racing conditions we can find ref_count == 0, in
4126 * that case, however, the context is still not destroyed
4127 * and no poll can be active, otherwise the ref_count
4129 g_main_context_wakeup (context);
4131 G_UNLOCK (main_context_list);
4136 g_child_watch_source_init_multi_threaded (void)
4138 GError *error = NULL;
4139 struct sigaction action;
4141 g_assert (g_thread_supported());
4143 if (pipe (child_watch_wake_up_pipe) < 0)
4144 g_error ("Cannot create wake up pipe: %s\n", g_strerror (errno));
4145 fcntl (child_watch_wake_up_pipe[1], F_SETFL, O_NONBLOCK | fcntl (child_watch_wake_up_pipe[1], F_GETFL));
4147 /* We create a helper thread that polls on the wakeup pipe indefinitely */
4148 /* FIXME: Think this through for races */
4149 if (g_thread_create (child_watch_helper_thread, NULL, FALSE, &error) == NULL)
4150 g_error ("Cannot create a thread to monitor child exit status: %s\n", error->message);
4151 child_watch_init_state = CHILD_WATCH_INITIALIZED_THREADED;
4153 action.sa_handler = g_child_watch_signal_handler;
4154 sigemptyset (&action.sa_mask);
4155 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4156 sigaction (SIGCHLD, &action, NULL);
4160 g_child_watch_source_init_promote_single_to_threaded (void)
4162 g_child_watch_source_init_multi_threaded ();
4166 g_child_watch_source_init (void)
4168 if (g_thread_supported())
4170 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
4171 g_child_watch_source_init_multi_threaded ();
4172 else if (child_watch_init_state == CHILD_WATCH_INITIALIZED_SINGLE)
4173 g_child_watch_source_init_promote_single_to_threaded ();
4177 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
4178 g_child_watch_source_init_single ();
4182 #endif /* !G_OS_WIN32 */
4185 * g_child_watch_source_new:
4186 * @pid: process to watch. On POSIX the pid of a child process. On
4187 * Windows a handle for a process (which doesn't have to be a child).
4189 * Creates a new child_watch source.
4191 * The source will not initially be associated with any #GMainContext
4192 * and must be added to one with g_source_attach() before it will be
4195 * Note that child watch sources can only be used in conjunction with
4196 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4199 * Note that on platforms where #GPid must be explicitly closed
4200 * (see g_spawn_close_pid()) @pid must not be closed while the
4201 * source is still active. Typically, you will want to call
4202 * g_spawn_close_pid() in the callback function for the source.
4204 * Note further that using g_child_watch_source_new() is not
4205 * compatible with calling <literal>waitpid(-1)</literal> in
4206 * the application. Calling waitpid() for individual pids will
4209 * Return value: the newly-created child watch source
4214 g_child_watch_source_new (GPid pid)
4216 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4217 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4220 child_watch_source->poll.fd = (gintptr) pid;
4221 child_watch_source->poll.events = G_IO_IN;
4223 g_source_add_poll (source, &child_watch_source->poll);
4224 #else /* G_OS_WIN32 */
4225 g_child_watch_source_init ();
4226 #endif /* G_OS_WIN32 */
4228 child_watch_source->pid = pid;
4234 * g_child_watch_add_full:
4235 * @priority: the priority of the idle source. Typically this will be in the
4236 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4237 * @pid: process to watch. On POSIX the pid of a child process. On
4238 * Windows a handle for a process (which doesn't have to be a child).
4239 * @function: function to call
4240 * @data: data to pass to @function
4241 * @notify: function to call when the idle is removed, or %NULL
4243 * Sets a function to be called when the child indicated by @pid
4244 * exits, at the priority @priority.
4246 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4247 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4248 * the spawn function for the child watching to work.
4250 * Note that on platforms where #GPid must be explicitly closed
4251 * (see g_spawn_close_pid()) @pid must not be closed while the
4252 * source is still active. Typically, you will want to call
4253 * g_spawn_close_pid() in the callback function for the source.
4255 * GLib supports only a single callback per process id.
4257 * This internally creates a main loop source using
4258 * g_child_watch_source_new() and attaches it to the main loop context
4259 * using g_source_attach(). You can do these steps manually if you
4260 * need greater control.
4262 * Return value: the ID (greater than 0) of the event source.
4267 g_child_watch_add_full (gint priority,
4269 GChildWatchFunc function,
4271 GDestroyNotify notify)
4276 g_return_val_if_fail (function != NULL, 0);
4278 source = g_child_watch_source_new (pid);
4280 if (priority != G_PRIORITY_DEFAULT)
4281 g_source_set_priority (source, priority);
4283 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4284 id = g_source_attach (source, NULL);
4285 g_source_unref (source);
4291 * g_child_watch_add:
4292 * @pid: process id to watch. On POSIX the pid of a child process. On
4293 * Windows a handle for a process (which doesn't have to be a child).
4294 * @function: function to call
4295 * @data: data to pass to @function
4297 * Sets a function to be called when the child indicated by @pid
4298 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4300 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4301 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4302 * the spawn function for the child watching to work.
4304 * Note that on platforms where #GPid must be explicitly closed
4305 * (see g_spawn_close_pid()) @pid must not be closed while the
4306 * source is still active. Typically, you will want to call
4307 * g_spawn_close_pid() in the callback function for the source.
4309 * GLib supports only a single callback per process id.
4311 * This internally creates a main loop source using
4312 * g_child_watch_source_new() and attaches it to the main loop context
4313 * using g_source_attach(). You can do these steps manually if you
4314 * need greater control.
4316 * Return value: the ID (greater than 0) of the event source.
4321 g_child_watch_add (GPid pid,
4322 GChildWatchFunc function,
4325 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4329 /* Idle functions */
4332 g_idle_prepare (GSource *source,
4341 g_idle_check (GSource *source)
4347 g_idle_dispatch (GSource *source,
4348 GSourceFunc callback,
4353 g_warning ("Idle source dispatched without callback\n"
4354 "You must call g_source_set_callback().");
4358 return callback (user_data);
4362 * g_idle_source_new:
4364 * Creates a new idle source.
4366 * The source will not initially be associated with any #GMainContext
4367 * and must be added to one with g_source_attach() before it will be
4368 * executed. Note that the default priority for idle sources is
4369 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4370 * have a default priority of %G_PRIORITY_DEFAULT.
4372 * Return value: the newly-created idle source
4375 g_idle_source_new (void)
4379 source = g_source_new (&g_idle_funcs, sizeof (GSource));
4380 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4387 * @priority: the priority of the idle source. Typically this will be in the
4388 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4389 * @function: function to call
4390 * @data: data to pass to @function
4391 * @notify: function to call when the idle is removed, or %NULL
4393 * Adds a function to be called whenever there are no higher priority
4394 * events pending. If the function returns %FALSE it is automatically
4395 * removed from the list of event sources and will not be called again.
4397 * This internally creates a main loop source using g_idle_source_new()
4398 * and attaches it to the main loop context using g_source_attach().
4399 * You can do these steps manually if you need greater control.
4401 * Return value: the ID (greater than 0) of the event source.
4404 g_idle_add_full (gint priority,
4405 GSourceFunc function,
4407 GDestroyNotify notify)
4412 g_return_val_if_fail (function != NULL, 0);
4414 source = g_idle_source_new ();
4416 if (priority != G_PRIORITY_DEFAULT_IDLE)
4417 g_source_set_priority (source, priority);
4419 g_source_set_callback (source, function, data, notify);
4420 id = g_source_attach (source, NULL);
4421 g_source_unref (source);
4428 * @function: function to call
4429 * @data: data to pass to @function.
4431 * Adds a function to be called whenever there are no higher priority
4432 * events pending to the default main loop. The function is given the
4433 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4434 * returns %FALSE it is automatically removed from the list of event
4435 * sources and will not be called again.
4437 * This internally creates a main loop source using g_idle_source_new()
4438 * and attaches it to the main loop context using g_source_attach().
4439 * You can do these steps manually if you need greater control.
4441 * Return value: the ID (greater than 0) of the event source.
4444 g_idle_add (GSourceFunc function,
4447 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4451 * g_idle_remove_by_data:
4452 * @data: the data for the idle source's callback.
4454 * Removes the idle function with the given data.
4456 * Return value: %TRUE if an idle source was found and removed.
4459 g_idle_remove_by_data (gpointer data)
4461 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4465 * g_main_context_invoke:
4466 * @context: a #GMainContext, or %NULL
4467 * @function: function to call
4468 * @data: data to pass to @function
4470 * Invokes a function in such a way that @context is owned during the
4471 * invocation of @function.
4473 * If @context is %NULL then the global default main context — as
4474 * returned by g_main_context_default() — is used.
4476 * If @context is owned by the current thread, @function is called
4477 * directly. Otherwise, if @context is the thread-default main context
4478 * of the current thread and g_main_context_acquire() succeeds, then
4479 * @function is called and g_main_context_release() is called
4482 * In any other case, an idle source is created to call @function and
4483 * that source is attached to @context (presumably to be run in another
4484 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
4485 * priority. If you want a different priority, use
4486 * g_main_context_invoke_full().
4488 * Note that, as with normal idle functions, @function should probably
4489 * return %FALSE. If it returns %TRUE, it will be continuously run in a
4490 * loop (and may prevent this call from returning).
4495 g_main_context_invoke (GMainContext *context,
4496 GSourceFunc function,
4499 g_main_context_invoke_full (context,
4501 function, data, NULL);
4505 * g_main_context_invoke_full:
4506 * @context: a #GMainContext, or %NULL
4507 * @priority: the priority at which to run @function
4508 * @function: function to call
4509 * @data: data to pass to @function
4510 * @notify: a function to call when @data is no longer in use, or %NULL.
4512 * Invokes a function in such a way that @context is owned during the
4513 * invocation of @function.
4515 * This function is the same as g_main_context_invoke() except that it
4516 * lets you specify the priority incase @function ends up being
4517 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
4519 * @notify should not assume that it is called from any particular
4520 * thread or with any particular context acquired.
4525 g_main_context_invoke_full (GMainContext *context,
4527 GSourceFunc function,
4529 GDestroyNotify notify)
4531 g_return_if_fail (function != NULL);
4534 context = g_main_context_default ();
4536 if (g_main_context_is_owner (context))
4538 while (function (data));
4545 GMainContext *thread_default;
4547 thread_default = g_main_context_get_thread_default ();
4549 if (!thread_default)
4550 thread_default = g_main_context_default ();
4552 if (thread_default == context && g_main_context_acquire (context))
4554 while (function (data));
4556 g_main_context_release (context);
4565 source = g_idle_source_new ();
4566 g_source_set_priority (source, priority);
4567 g_source_set_callback (source, function, data, notify);
4568 g_source_attach (source, context);
4569 g_source_unref (source);