1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * gmain.c: Main loop abstraction, timeouts, and idle functions
5 * Copyright 1998 Owen Taylor
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the
19 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 * Boston, MA 02111-1307, USA.
24 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
25 * file for a list of people on the GLib Team. See the ChangeLog
26 * files for a list of changes. These files are distributed with
27 * GLib at ftp://ftp.gtk.org/pub/gtk/.
35 #include "glibconfig.h"
37 /* Uncomment the next line (and the corresponding line in gpoll.c) to
38 * enable debugging printouts if the environment variable
39 * G_MAIN_POLL_DEBUG is set to some value.
41 /* #define G_MAIN_POLL_DEBUG */
44 /* Always enable debugging printout on Windows, as it is more often
47 #define G_MAIN_POLL_DEBUG
51 #include "glib-unix.h"
53 #include <sys/eventfd.h>
58 #include <sys/types.h>
61 #ifdef HAVE_SYS_TIME_H
63 #endif /* HAVE_SYS_TIME_H */
66 #endif /* HAVE_UNISTD_H */
73 #endif /* G_OS_WIN32 */
76 #include <sys/socket.h>
78 #endif /* G_OS_BEOS */
83 #include "giochannel.h"
87 #include "gstrfuncs.h"
88 #include "gtestutils.h"
89 #include "gthreadprivate.h"
95 #ifdef G_MAIN_POLL_DEBUG
101 #include "glibprivate.h"
105 * @title: The Main Event Loop
106 * @short_description: manages all available sources of events
108 * The main event loop manages all the available sources of events for
109 * GLib and GTK+ applications. These events can come from any number of
110 * different types of sources such as file descriptors (plain files,
111 * pipes or sockets) and timeouts. New types of event sources can also
112 * be added using g_source_attach().
114 * To allow multiple independent sets of sources to be handled in
115 * different threads, each source is associated with a #GMainContext.
116 * A GMainContext can only be running in a single thread, but
117 * sources can be added to it and removed from it from other threads.
119 * Each event source is assigned a priority. The default priority,
120 * #G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
121 * Values greater than 0 denote lower priorities. Events from high priority
122 * sources are always processed before events from lower priority sources.
124 * Idle functions can also be added, and assigned a priority. These will
125 * be run whenever no events with a higher priority are ready to be processed.
127 * The #GMainLoop data type represents a main event loop. A GMainLoop is
128 * created with g_main_loop_new(). After adding the initial event sources,
129 * g_main_loop_run() is called. This continuously checks for new events from
130 * each of the event sources and dispatches them. Finally, the processing of
131 * an event from one of the sources leads to a call to g_main_loop_quit() to
132 * exit the main loop, and g_main_loop_run() returns.
134 * It is possible to create new instances of #GMainLoop recursively.
135 * This is often used in GTK+ applications when showing modal dialog
136 * boxes. Note that event sources are associated with a particular
137 * #GMainContext, and will be checked and dispatched for all main
138 * loops associated with that GMainContext.
140 * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
141 * gtk_main_quit() and gtk_events_pending().
143 * <refsect2><title>Creating new source types</title>
144 * <para>One of the unusual features of the #GMainLoop functionality
145 * is that new types of event source can be created and used in
146 * addition to the builtin type of event source. A new event source
147 * type is used for handling GDK events. A new source type is created
148 * by <firstterm>deriving</firstterm> from the #GSource structure.
149 * The derived type of source is represented by a structure that has
150 * the #GSource structure as a first element, and other elements specific
151 * to the new source type. To create an instance of the new source type,
152 * call g_source_new() passing in the size of the derived structure and
153 * a table of functions. These #GSourceFuncs determine the behavior of
154 * the new source type.</para>
155 * <para>New source types basically interact with the main context
156 * in two ways. Their prepare function in #GSourceFuncs can set a timeout
157 * to determine the maximum amount of time that the main loop will sleep
158 * before checking the source again. In addition, or as well, the source
159 * can add file descriptors to the set that the main context checks using
160 * g_source_add_poll().</para>
162 * <refsect2><title>Customizing the main loop iteration</title>
163 * <para>Single iterations of a #GMainContext can be run with
164 * g_main_context_iteration(). In some cases, more detailed control
165 * of exactly how the details of the main loop work is desired, for
166 * instance, when integrating the #GMainLoop with an external main loop.
167 * In such cases, you can call the component functions of
168 * g_main_context_iteration() directly. These functions are
169 * g_main_context_prepare(), g_main_context_query(),
170 * g_main_context_check() and g_main_context_dispatch().</para>
171 * <para>The operation of these functions can best be seen in terms
172 * of a state diagram, as shown in <xref linkend="mainloop-states"/>.</para>
173 * <figure id="mainloop-states"><title>States of a Main Context</title>
174 * <graphic fileref="mainloop-states.gif" format="GIF"></graphic>
181 typedef struct _GTimeoutSource GTimeoutSource;
182 typedef struct _GChildWatchSource GChildWatchSource;
183 typedef struct _GUnixSignalWatchSource GUnixSignalWatchSource;
184 typedef struct _GPollRec GPollRec;
185 typedef struct _GSourceCallback GSourceCallback;
189 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
190 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
193 typedef struct _GMainWaiter GMainWaiter;
201 typedef struct _GMainDispatch GMainDispatch;
203 struct _GMainDispatch
206 GSList *dispatching_sources; /* stack of current sources */
209 #ifdef G_MAIN_POLL_DEBUG
210 gboolean _g_main_poll_debug = FALSE;
215 /* The following lock is used for both the list of sources
216 * and the list of poll records
226 GPtrArray *pending_dispatches;
227 gint timeout; /* Timeout for current iteration */
230 GSource *source_list;
231 gint in_check_or_prepare;
233 GPollRec *poll_records, *poll_records_tail;
234 guint n_poll_records;
235 GPollFD *cached_poll_array;
236 guint cached_poll_array_size;
241 gboolean poll_waiting;
243 /* Flag indicating whether the set of fd's changed during a poll */
244 gboolean poll_changed;
249 gboolean time_is_fresh;
251 gboolean real_time_is_fresh;
254 struct _GSourceCallback
259 GDestroyNotify notify;
264 GMainContext *context;
269 struct _GTimeoutSource
277 struct _GChildWatchSource
284 #else /* G_OS_WIN32 */
285 gboolean child_exited;
286 #endif /* G_OS_WIN32 */
289 struct _GUnixSignalWatchSource
304 struct _GSourcePrivate
306 GSList *child_sources;
307 GSource *parent_source;
310 #define LOCK_CONTEXT(context) g_static_mutex_lock (&context->mutex)
311 #define UNLOCK_CONTEXT(context) g_static_mutex_unlock (&context->mutex)
312 #define G_THREAD_SELF g_thread_self ()
314 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
315 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
316 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
318 #define SOURCE_UNREF(source, context) \
320 if ((source)->ref_count > 1) \
321 (source)->ref_count--; \
323 g_source_unref_internal ((source), (context), TRUE); \
327 /* Forward declarations */
329 static void g_source_unref_internal (GSource *source,
330 GMainContext *context,
332 static void g_source_destroy_internal (GSource *source,
333 GMainContext *context,
335 static void g_source_set_priority_unlocked (GSource *source,
336 GMainContext *context,
338 static void g_main_context_poll (GMainContext *context,
343 static void g_main_context_add_poll_unlocked (GMainContext *context,
346 static void g_main_context_remove_poll_unlocked (GMainContext *context,
348 static void g_main_context_wakeup_unlocked (GMainContext *context);
350 static gboolean g_timeout_prepare (GSource *source,
352 static gboolean g_timeout_check (GSource *source);
353 static gboolean g_timeout_dispatch (GSource *source,
354 GSourceFunc callback,
356 static gboolean g_child_watch_prepare (GSource *source,
358 static gboolean g_child_watch_check (GSource *source);
359 static gboolean g_child_watch_dispatch (GSource *source,
360 GSourceFunc callback,
362 static void g_child_watch_finalize (GSource *source);
364 static void g_unix_signal_handler (int signum);
365 static gboolean g_unix_signal_watch_prepare (GSource *source,
367 static gboolean g_unix_signal_watch_check (GSource *source);
368 static gboolean g_unix_signal_watch_dispatch (GSource *source,
369 GSourceFunc callback,
371 static void g_unix_signal_watch_finalize (GSource *source);
373 static gboolean g_idle_prepare (GSource *source,
375 static gboolean g_idle_check (GSource *source);
376 static gboolean g_idle_dispatch (GSource *source,
377 GSourceFunc callback,
380 static GMainContext *glib_worker_context;
382 G_LOCK_DEFINE_STATIC (main_loop);
383 static GMainContext *default_main_context;
388 /* UNIX signals work by marking one of these variables then waking the
389 * worker context to check on them and dispatch accordingly.
391 static volatile gchar unix_signal_pending[NSIG];
392 static volatile gboolean any_unix_signal_pending;
394 /* Guards all the data below */
395 G_LOCK_DEFINE_STATIC (unix_signal_lock);
396 static GSList *unix_signal_watches;
397 static GSList *unix_child_watches;
399 static GSourceFuncs g_unix_signal_funcs =
401 g_unix_signal_watch_prepare,
402 g_unix_signal_watch_check,
403 g_unix_signal_watch_dispatch,
404 g_unix_signal_watch_finalize
406 #endif /* !G_OS_WIN32 */
407 G_LOCK_DEFINE_STATIC (main_context_list);
408 static GSList *main_context_list = NULL;
410 GSourceFuncs g_timeout_funcs =
418 GSourceFuncs g_child_watch_funcs =
420 g_child_watch_prepare,
422 g_child_watch_dispatch,
423 g_child_watch_finalize
426 GSourceFuncs g_idle_funcs =
435 * g_main_context_ref:
436 * @context: a #GMainContext
438 * Increases the reference count on a #GMainContext object by one.
440 * Returns: the @context that was passed in (since 2.6)
443 g_main_context_ref (GMainContext *context)
445 g_return_val_if_fail (context != NULL, NULL);
446 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
448 g_atomic_int_inc (&context->ref_count);
454 poll_rec_list_free (GMainContext *context,
457 g_slice_free_chain (GPollRec, list, next);
461 * g_main_context_unref:
462 * @context: a #GMainContext
464 * Decreases the reference count on a #GMainContext object by one. If
465 * the result is zero, free the context and free all associated memory.
468 g_main_context_unref (GMainContext *context)
471 g_return_if_fail (context != NULL);
472 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
474 if (!g_atomic_int_dec_and_test (&context->ref_count))
477 G_LOCK (main_context_list);
478 main_context_list = g_slist_remove (main_context_list, context);
479 G_UNLOCK (main_context_list);
481 source = context->source_list;
484 GSource *next = source->next;
485 g_source_destroy_internal (source, context, FALSE);
489 g_static_mutex_free (&context->mutex);
491 g_ptr_array_free (context->pending_dispatches, TRUE);
492 g_free (context->cached_poll_array);
494 poll_rec_list_free (context, context->poll_records);
496 g_wakeup_free (context->wakeup);
498 if (context->cond != NULL)
499 g_cond_free (context->cond);
505 g_main_context_init_pipe (GMainContext *context)
507 context->wakeup = g_wakeup_new ();
508 g_wakeup_get_pollfd (context->wakeup, &context->wake_up_rec);
509 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
513 * g_main_context_new:
515 * Creates a new #GMainContext structure.
517 * Return value: the new #GMainContext
520 g_main_context_new (void)
522 GMainContext *context;
524 g_thread_init_glib ();
526 context = g_new0 (GMainContext, 1);
528 #ifdef G_MAIN_POLL_DEBUG
530 static gboolean beenhere = FALSE;
534 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
535 _g_main_poll_debug = TRUE;
541 g_static_mutex_init (&context->mutex);
543 context->owner = NULL;
544 context->waiters = NULL;
546 context->ref_count = 1;
548 context->next_id = 1;
550 context->source_list = NULL;
552 context->poll_func = g_poll;
554 context->cached_poll_array = NULL;
555 context->cached_poll_array_size = 0;
557 context->pending_dispatches = g_ptr_array_new ();
559 context->time_is_fresh = FALSE;
560 context->real_time_is_fresh = FALSE;
562 g_main_context_init_pipe (context);
564 G_LOCK (main_context_list);
565 main_context_list = g_slist_append (main_context_list, context);
567 #ifdef G_MAIN_POLL_DEBUG
568 if (_g_main_poll_debug)
569 g_print ("created context=%p\n", context);
572 G_UNLOCK (main_context_list);
578 * g_main_context_default:
580 * Returns the global default main context. This is the main context
581 * used for main loop functions when a main loop is not explicitly
582 * specified, and corresponds to the "main" main loop. See also
583 * g_main_context_get_thread_default().
585 * Return value: (transfer none): the global default main context.
588 g_main_context_default (void)
594 if (!default_main_context)
596 default_main_context = g_main_context_new ();
597 #ifdef G_MAIN_POLL_DEBUG
598 if (_g_main_poll_debug)
599 g_print ("default context=%p\n", default_main_context);
603 G_UNLOCK (main_loop);
605 return default_main_context;
608 static GStaticPrivate thread_context_stack = G_STATIC_PRIVATE_INIT;
611 free_context_stack (gpointer data)
613 GQueue *stack = data;
614 GMainContext *context;
616 while (!g_queue_is_empty (stack))
618 context = g_queue_pop_head (stack);
619 g_main_context_release (context);
621 g_main_context_unref (context);
623 g_queue_free (stack);
627 * g_main_context_push_thread_default:
628 * @context: a #GMainContext, or %NULL for the global default context
630 * Acquires @context and sets it as the thread-default context for the
631 * current thread. This will cause certain asynchronous operations
632 * (such as most <link linkend="gio">gio</link>-based I/O) which are
633 * started in this thread to run under @context and deliver their
634 * results to its main loop, rather than running under the global
635 * default context in the main thread. Note that calling this function
636 * changes the context returned by
637 * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
638 * one returned by g_main_context_default(), so it does not affect the
639 * context used by functions like g_idle_add().
641 * Normally you would call this function shortly after creating a new
642 * thread, passing it a #GMainContext which will be run by a
643 * #GMainLoop in that thread, to set a new default context for all
644 * async operations in that thread. (In this case, you don't need to
645 * ever call g_main_context_pop_thread_default().) In some cases
646 * however, you may want to schedule a single operation in a
647 * non-default context, or temporarily use a non-default context in
648 * the main thread. In that case, you can wrap the call to the
649 * asynchronous operation inside a
650 * g_main_context_push_thread_default() /
651 * g_main_context_pop_thread_default() pair, but it is up to you to
652 * ensure that no other asynchronous operations accidentally get
653 * started while the non-default context is active.
655 * Beware that libraries that predate this function may not correctly
656 * handle being used from a thread with a thread-default context. Eg,
657 * see g_file_supports_thread_contexts().
662 g_main_context_push_thread_default (GMainContext *context)
665 gboolean acquired_context;
667 acquired_context = g_main_context_acquire (context);
668 g_return_if_fail (acquired_context);
670 if (context == g_main_context_default ())
673 g_main_context_ref (context);
675 stack = g_static_private_get (&thread_context_stack);
678 stack = g_queue_new ();
679 g_static_private_set (&thread_context_stack, stack,
683 g_queue_push_head (stack, context);
687 * g_main_context_pop_thread_default:
688 * @context: a #GMainContext object, or %NULL
690 * Pops @context off the thread-default context stack (verifying that
691 * it was on the top of the stack).
696 g_main_context_pop_thread_default (GMainContext *context)
700 if (context == g_main_context_default ())
703 stack = g_static_private_get (&thread_context_stack);
705 g_return_if_fail (stack != NULL);
706 g_return_if_fail (g_queue_peek_head (stack) == context);
708 g_queue_pop_head (stack);
710 g_main_context_release (context);
712 g_main_context_unref (context);
716 * g_main_context_get_thread_default:
718 * Gets the thread-default #GMainContext for this thread. Asynchronous
719 * operations that want to be able to be run in contexts other than
720 * the default one should call this method to get a #GMainContext to
721 * add their #GSource<!-- -->s to. (Note that even in single-threaded
722 * programs applications may sometimes want to temporarily push a
723 * non-default context, so it is not safe to assume that this will
724 * always return %NULL if threads are not initialized.)
726 * Returns: (transfer none): the thread-default #GMainContext, or
727 * %NULL if the thread-default context is the global default context.
732 g_main_context_get_thread_default (void)
736 stack = g_static_private_get (&thread_context_stack);
738 return g_queue_peek_head (stack);
743 /* Hooks for adding to the main loop */
747 * @source_funcs: structure containing functions that implement
748 * the sources behavior.
749 * @struct_size: size of the #GSource structure to create.
751 * Creates a new #GSource structure. The size is specified to
752 * allow creating structures derived from #GSource that contain
753 * additional data. The size passed in must be at least
754 * <literal>sizeof (GSource)</literal>.
756 * The source will not initially be associated with any #GMainContext
757 * and must be added to one with g_source_attach() before it will be
760 * Return value: the newly-created #GSource.
763 g_source_new (GSourceFuncs *source_funcs,
768 g_return_val_if_fail (source_funcs != NULL, NULL);
769 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
771 source = (GSource*) g_malloc0 (struct_size);
773 source->source_funcs = source_funcs;
774 source->ref_count = 1;
776 source->priority = G_PRIORITY_DEFAULT;
778 source->flags = G_HOOK_FLAG_ACTIVE;
780 /* NULL/0 initialization for all other fields */
785 /* Holds context's lock
788 g_source_list_add (GSource *source,
789 GMainContext *context)
791 GSource *tmp_source, *last_source;
793 if (source->priv && source->priv->parent_source)
795 /* Put the source immediately before its parent */
796 tmp_source = source->priv->parent_source;
797 last_source = source->priv->parent_source->prev;
802 tmp_source = context->source_list;
803 while (tmp_source && tmp_source->priority <= source->priority)
805 last_source = tmp_source;
806 tmp_source = tmp_source->next;
810 source->next = tmp_source;
812 tmp_source->prev = source;
814 source->prev = last_source;
816 last_source->next = source;
818 context->source_list = source;
821 /* Holds context's lock
824 g_source_list_remove (GSource *source,
825 GMainContext *context)
828 source->prev->next = source->next;
830 context->source_list = source->next;
833 source->next->prev = source->prev;
840 g_source_attach_unlocked (GSource *source,
841 GMainContext *context)
846 source->context = context;
847 result = source->source_id = context->next_id++;
850 g_source_list_add (source, context);
852 tmp_list = source->poll_fds;
855 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
856 tmp_list = tmp_list->next;
861 tmp_list = source->priv->child_sources;
864 g_source_attach_unlocked (tmp_list->data, context);
865 tmp_list = tmp_list->next;
874 * @source: a #GSource
875 * @context: a #GMainContext (if %NULL, the default context will be used)
877 * Adds a #GSource to a @context so that it will be executed within
878 * that context. Remove it by calling g_source_destroy().
880 * Return value: the ID (greater than 0) for the source within the
884 g_source_attach (GSource *source,
885 GMainContext *context)
889 g_return_val_if_fail (source->context == NULL, 0);
890 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
893 context = g_main_context_default ();
895 LOCK_CONTEXT (context);
897 result = g_source_attach_unlocked (source, context);
899 /* Now wake up the main loop if it is waiting in the poll() */
900 g_main_context_wakeup_unlocked (context);
902 UNLOCK_CONTEXT (context);
908 g_source_destroy_internal (GSource *source,
909 GMainContext *context,
913 LOCK_CONTEXT (context);
915 if (!SOURCE_DESTROYED (source))
918 gpointer old_cb_data;
919 GSourceCallbackFuncs *old_cb_funcs;
921 source->flags &= ~G_HOOK_FLAG_ACTIVE;
923 old_cb_data = source->callback_data;
924 old_cb_funcs = source->callback_funcs;
926 source->callback_data = NULL;
927 source->callback_funcs = NULL;
931 UNLOCK_CONTEXT (context);
932 old_cb_funcs->unref (old_cb_data);
933 LOCK_CONTEXT (context);
936 if (!SOURCE_BLOCKED (source))
938 tmp_list = source->poll_fds;
941 g_main_context_remove_poll_unlocked (context, tmp_list->data);
942 tmp_list = tmp_list->next;
946 if (source->priv && source->priv->child_sources)
948 /* This is safe because even if a child_source finalizer or
949 * closure notify tried to modify source->priv->child_sources
950 * from outside the lock, it would fail since
951 * SOURCE_DESTROYED(source) is now TRUE.
953 tmp_list = source->priv->child_sources;
956 g_source_destroy_internal (tmp_list->data, context, TRUE);
957 g_source_unref_internal (tmp_list->data, context, TRUE);
958 tmp_list = tmp_list->next;
960 g_slist_free (source->priv->child_sources);
961 source->priv->child_sources = NULL;
964 g_source_unref_internal (source, context, TRUE);
968 UNLOCK_CONTEXT (context);
973 * @source: a #GSource
975 * Removes a source from its #GMainContext, if any, and mark it as
976 * destroyed. The source cannot be subsequently added to another
980 g_source_destroy (GSource *source)
982 GMainContext *context;
984 g_return_if_fail (source != NULL);
986 context = source->context;
989 g_source_destroy_internal (source, context, FALSE);
991 source->flags &= ~G_HOOK_FLAG_ACTIVE;
996 * @source: a #GSource
998 * Returns the numeric ID for a particular source. The ID of a source
999 * is a positive integer which is unique within a particular main loop
1000 * context. The reverse
1001 * mapping from ID to source is done by g_main_context_find_source_by_id().
1003 * Return value: the ID (greater than 0) for the source
1006 g_source_get_id (GSource *source)
1010 g_return_val_if_fail (source != NULL, 0);
1011 g_return_val_if_fail (source->context != NULL, 0);
1013 LOCK_CONTEXT (source->context);
1014 result = source->source_id;
1015 UNLOCK_CONTEXT (source->context);
1021 * g_source_get_context:
1022 * @source: a #GSource
1024 * Gets the #GMainContext with which the source is associated.
1025 * Calling this function on a destroyed source is an error.
1027 * Return value: (transfer none): the #GMainContext with which the
1028 * source is associated, or %NULL if the context has not
1029 * yet been added to a source.
1032 g_source_get_context (GSource *source)
1034 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1036 return source->context;
1040 * g_source_add_poll:
1041 * @source:a #GSource
1042 * @fd: a #GPollFD structure holding information about a file
1043 * descriptor to watch.
1045 * Adds a file descriptor to the set of file descriptors polled for
1046 * this source. This is usually combined with g_source_new() to add an
1047 * event source. The event source's check function will typically test
1048 * the @revents field in the #GPollFD struct and return %TRUE if events need
1052 g_source_add_poll (GSource *source,
1055 GMainContext *context;
1057 g_return_if_fail (source != NULL);
1058 g_return_if_fail (fd != NULL);
1059 g_return_if_fail (!SOURCE_DESTROYED (source));
1061 context = source->context;
1064 LOCK_CONTEXT (context);
1066 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1070 if (!SOURCE_BLOCKED (source))
1071 g_main_context_add_poll_unlocked (context, source->priority, fd);
1072 UNLOCK_CONTEXT (context);
1077 * g_source_remove_poll:
1078 * @source:a #GSource
1079 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1081 * Removes a file descriptor from the set of file descriptors polled for
1085 g_source_remove_poll (GSource *source,
1088 GMainContext *context;
1090 g_return_if_fail (source != NULL);
1091 g_return_if_fail (fd != NULL);
1092 g_return_if_fail (!SOURCE_DESTROYED (source));
1094 context = source->context;
1097 LOCK_CONTEXT (context);
1099 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1103 if (!SOURCE_BLOCKED (source))
1104 g_main_context_remove_poll_unlocked (context, fd);
1105 UNLOCK_CONTEXT (context);
1110 * g_source_add_child_source:
1111 * @source:a #GSource
1112 * @child_source: a second #GSource that @source should "poll"
1114 * Adds @child_source to @source as a "polled" source; when @source is
1115 * added to a #GMainContext, @child_source will be automatically added
1116 * with the same priority, when @child_source is triggered, it will
1117 * cause @source to dispatch (in addition to calling its own
1118 * callback), and when @source is destroyed, it will destroy
1119 * @child_source as well. (@source will also still be dispatched if
1120 * its own prepare/check functions indicate that it is ready.)
1122 * If you don't need @child_source to do anything on its own when it
1123 * triggers, you can call g_source_set_dummy_callback() on it to set a
1124 * callback that does nothing (except return %TRUE if appropriate).
1126 * @source will hold a reference on @child_source while @child_source
1127 * is attached to it.
1132 g_source_add_child_source (GSource *source,
1133 GSource *child_source)
1135 GMainContext *context;
1137 g_return_if_fail (source != NULL);
1138 g_return_if_fail (child_source != NULL);
1139 g_return_if_fail (!SOURCE_DESTROYED (source));
1140 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1141 g_return_if_fail (child_source->context == NULL);
1142 g_return_if_fail (child_source->priv == NULL || child_source->priv->parent_source == NULL);
1144 context = source->context;
1147 LOCK_CONTEXT (context);
1150 source->priv = g_slice_new0 (GSourcePrivate);
1151 if (!child_source->priv)
1152 child_source->priv = g_slice_new0 (GSourcePrivate);
1154 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1155 g_source_ref (child_source));
1156 child_source->priv->parent_source = source;
1157 g_source_set_priority_unlocked (child_source, context, source->priority);
1161 UNLOCK_CONTEXT (context);
1162 g_source_attach (child_source, context);
1167 * g_source_remove_child_source:
1168 * @source:a #GSource
1169 * @child_source: a #GSource previously passed to
1170 * g_source_add_child_source().
1172 * Detaches @child_source from @source and destroys it.
1177 g_source_remove_child_source (GSource *source,
1178 GSource *child_source)
1180 GMainContext *context;
1182 g_return_if_fail (source != NULL);
1183 g_return_if_fail (child_source != NULL);
1184 g_return_if_fail (child_source->priv != NULL && child_source->priv->parent_source == source);
1185 g_return_if_fail (!SOURCE_DESTROYED (source));
1186 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1188 context = source->context;
1191 LOCK_CONTEXT (context);
1193 source->priv->child_sources = g_slist_remove (source->priv->child_sources, child_source);
1194 g_source_destroy_internal (child_source, context, TRUE);
1195 g_source_unref_internal (child_source, context, TRUE);
1198 UNLOCK_CONTEXT (context);
1202 * g_source_set_callback_indirect:
1203 * @source: the source
1204 * @callback_data: pointer to callback data "object"
1205 * @callback_funcs: functions for reference counting @callback_data
1206 * and getting the callback and data
1208 * Sets the callback function storing the data as a refcounted callback
1209 * "object". This is used internally. Note that calling
1210 * g_source_set_callback_indirect() assumes
1211 * an initial reference count on @callback_data, and thus
1212 * @callback_funcs->unref will eventually be called once more
1213 * than @callback_funcs->ref.
1216 g_source_set_callback_indirect (GSource *source,
1217 gpointer callback_data,
1218 GSourceCallbackFuncs *callback_funcs)
1220 GMainContext *context;
1221 gpointer old_cb_data;
1222 GSourceCallbackFuncs *old_cb_funcs;
1224 g_return_if_fail (source != NULL);
1225 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1227 context = source->context;
1230 LOCK_CONTEXT (context);
1232 old_cb_data = source->callback_data;
1233 old_cb_funcs = source->callback_funcs;
1235 source->callback_data = callback_data;
1236 source->callback_funcs = callback_funcs;
1239 UNLOCK_CONTEXT (context);
1242 old_cb_funcs->unref (old_cb_data);
1246 g_source_callback_ref (gpointer cb_data)
1248 GSourceCallback *callback = cb_data;
1250 callback->ref_count++;
1255 g_source_callback_unref (gpointer cb_data)
1257 GSourceCallback *callback = cb_data;
1259 callback->ref_count--;
1260 if (callback->ref_count == 0)
1262 if (callback->notify)
1263 callback->notify (callback->data);
1269 g_source_callback_get (gpointer cb_data,
1274 GSourceCallback *callback = cb_data;
1276 *func = callback->func;
1277 *data = callback->data;
1280 static GSourceCallbackFuncs g_source_callback_funcs = {
1281 g_source_callback_ref,
1282 g_source_callback_unref,
1283 g_source_callback_get,
1287 * g_source_set_callback:
1288 * @source: the source
1289 * @func: a callback function
1290 * @data: the data to pass to callback function
1291 * @notify: a function to call when @data is no longer in use, or %NULL.
1293 * Sets the callback function for a source. The callback for a source is
1294 * called from the source's dispatch function.
1296 * The exact type of @func depends on the type of source; ie. you
1297 * should not count on @func being called with @data as its first
1300 * Typically, you won't use this function. Instead use functions specific
1301 * to the type of source you are using.
1304 g_source_set_callback (GSource *source,
1307 GDestroyNotify notify)
1309 GSourceCallback *new_callback;
1311 g_return_if_fail (source != NULL);
1313 new_callback = g_new (GSourceCallback, 1);
1315 new_callback->ref_count = 1;
1316 new_callback->func = func;
1317 new_callback->data = data;
1318 new_callback->notify = notify;
1320 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1325 * g_source_set_funcs:
1326 * @source: a #GSource
1327 * @funcs: the new #GSourceFuncs
1329 * Sets the source functions (can be used to override
1330 * default implementations) of an unattached source.
1335 g_source_set_funcs (GSource *source,
1336 GSourceFuncs *funcs)
1338 g_return_if_fail (source != NULL);
1339 g_return_if_fail (source->context == NULL);
1340 g_return_if_fail (source->ref_count > 0);
1341 g_return_if_fail (funcs != NULL);
1343 source->source_funcs = funcs;
1347 g_source_set_priority_unlocked (GSource *source,
1348 GMainContext *context,
1353 source->priority = priority;
1357 /* Remove the source from the context's source and then
1358 * add it back so it is sorted in the correct place
1360 g_source_list_remove (source, source->context);
1361 g_source_list_add (source, source->context);
1363 if (!SOURCE_BLOCKED (source))
1365 tmp_list = source->poll_fds;
1368 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1369 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1371 tmp_list = tmp_list->next;
1376 if (source->priv && source->priv->child_sources)
1378 tmp_list = source->priv->child_sources;
1381 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1382 tmp_list = tmp_list->next;
1388 * g_source_set_priority:
1389 * @source: a #GSource
1390 * @priority: the new priority.
1392 * Sets the priority of a source. While the main loop is being run, a
1393 * source will be dispatched if it is ready to be dispatched and no
1394 * sources at a higher (numerically smaller) priority are ready to be
1398 g_source_set_priority (GSource *source,
1401 GMainContext *context;
1403 g_return_if_fail (source != NULL);
1405 context = source->context;
1408 LOCK_CONTEXT (context);
1409 g_source_set_priority_unlocked (source, context, priority);
1411 UNLOCK_CONTEXT (source->context);
1415 * g_source_get_priority:
1416 * @source: a #GSource
1418 * Gets the priority of a source.
1420 * Return value: the priority of the source
1423 g_source_get_priority (GSource *source)
1425 g_return_val_if_fail (source != NULL, 0);
1427 return source->priority;
1431 * g_source_set_can_recurse:
1432 * @source: a #GSource
1433 * @can_recurse: whether recursion is allowed for this source
1435 * Sets whether a source can be called recursively. If @can_recurse is
1436 * %TRUE, then while the source is being dispatched then this source
1437 * will be processed normally. Otherwise, all processing of this
1438 * source is blocked until the dispatch function returns.
1441 g_source_set_can_recurse (GSource *source,
1442 gboolean can_recurse)
1444 GMainContext *context;
1446 g_return_if_fail (source != NULL);
1448 context = source->context;
1451 LOCK_CONTEXT (context);
1454 source->flags |= G_SOURCE_CAN_RECURSE;
1456 source->flags &= ~G_SOURCE_CAN_RECURSE;
1459 UNLOCK_CONTEXT (context);
1463 * g_source_get_can_recurse:
1464 * @source: a #GSource
1466 * Checks whether a source is allowed to be called recursively.
1467 * see g_source_set_can_recurse().
1469 * Return value: whether recursion is allowed.
1472 g_source_get_can_recurse (GSource *source)
1474 g_return_val_if_fail (source != NULL, FALSE);
1476 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1481 * g_source_set_name:
1482 * @source: a #GSource
1483 * @name: debug name for the source
1485 * Sets a name for the source, used in debugging and profiling.
1486 * The name defaults to #NULL.
1488 * The source name should describe in a human-readable way
1489 * what the source does. For example, "X11 event queue"
1490 * or "GTK+ repaint idle handler" or whatever it is.
1492 * It is permitted to call this function multiple times, but is not
1493 * recommended due to the potential performance impact. For example,
1494 * one could change the name in the "check" function of a #GSourceFuncs
1495 * to include details like the event type in the source name.
1500 g_source_set_name (GSource *source,
1503 g_return_if_fail (source != NULL);
1505 /* setting back to NULL is allowed, just because it's
1506 * weird if get_name can return NULL but you can't
1510 g_free (source->name);
1511 source->name = g_strdup (name);
1515 * g_source_get_name:
1516 * @source: a #GSource
1518 * Gets a name for the source, used in debugging and profiling.
1519 * The name may be #NULL if it has never been set with
1520 * g_source_set_name().
1522 * Return value: the name of the source
1526 g_source_get_name (GSource *source)
1528 g_return_val_if_fail (source != NULL, NULL);
1530 return source->name;
1534 * g_source_set_name_by_id:
1535 * @tag: a #GSource ID
1536 * @name: debug name for the source
1538 * Sets the name of a source using its ID.
1540 * This is a convenience utility to set source names from the return
1541 * value of g_idle_add(), g_timeout_add(), etc.
1546 g_source_set_name_by_id (guint tag,
1551 g_return_if_fail (tag > 0);
1553 source = g_main_context_find_source_by_id (NULL, tag);
1557 g_source_set_name (source, name);
1563 * @source: a #GSource
1565 * Increases the reference count on a source by one.
1567 * Return value: @source
1570 g_source_ref (GSource *source)
1572 GMainContext *context;
1574 g_return_val_if_fail (source != NULL, NULL);
1576 context = source->context;
1579 LOCK_CONTEXT (context);
1581 source->ref_count++;
1584 UNLOCK_CONTEXT (context);
1589 /* g_source_unref() but possible to call within context lock
1592 g_source_unref_internal (GSource *source,
1593 GMainContext *context,
1596 gpointer old_cb_data = NULL;
1597 GSourceCallbackFuncs *old_cb_funcs = NULL;
1599 g_return_if_fail (source != NULL);
1601 if (!have_lock && context)
1602 LOCK_CONTEXT (context);
1604 source->ref_count--;
1605 if (source->ref_count == 0)
1607 old_cb_data = source->callback_data;
1608 old_cb_funcs = source->callback_funcs;
1610 source->callback_data = NULL;
1611 source->callback_funcs = NULL;
1615 if (!SOURCE_DESTROYED (source))
1616 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
1617 g_source_list_remove (source, context);
1620 if (source->source_funcs->finalize)
1623 UNLOCK_CONTEXT (context);
1624 source->source_funcs->finalize (source);
1626 LOCK_CONTEXT (context);
1629 g_free (source->name);
1630 source->name = NULL;
1632 g_slist_free (source->poll_fds);
1633 source->poll_fds = NULL;
1637 g_slice_free (GSourcePrivate, source->priv);
1638 source->priv = NULL;
1644 if (!have_lock && context)
1645 UNLOCK_CONTEXT (context);
1650 UNLOCK_CONTEXT (context);
1652 old_cb_funcs->unref (old_cb_data);
1655 LOCK_CONTEXT (context);
1661 * @source: a #GSource
1663 * Decreases the reference count of a source by one. If the
1664 * resulting reference count is zero the source and associated
1665 * memory will be destroyed.
1668 g_source_unref (GSource *source)
1670 g_return_if_fail (source != NULL);
1672 g_source_unref_internal (source, source->context, FALSE);
1676 * g_main_context_find_source_by_id:
1677 * @context: a #GMainContext (if %NULL, the default context will be used)
1678 * @source_id: the source ID, as returned by g_source_get_id().
1680 * Finds a #GSource given a pair of context and ID.
1682 * Return value: (transfer none): the #GSource if found, otherwise, %NULL
1685 g_main_context_find_source_by_id (GMainContext *context,
1690 g_return_val_if_fail (source_id > 0, NULL);
1692 if (context == NULL)
1693 context = g_main_context_default ();
1695 LOCK_CONTEXT (context);
1697 source = context->source_list;
1700 if (!SOURCE_DESTROYED (source) &&
1701 source->source_id == source_id)
1703 source = source->next;
1706 UNLOCK_CONTEXT (context);
1712 * g_main_context_find_source_by_funcs_user_data:
1713 * @context: a #GMainContext (if %NULL, the default context will be used).
1714 * @funcs: the @source_funcs passed to g_source_new().
1715 * @user_data: the user data from the callback.
1717 * Finds a source with the given source functions and user data. If
1718 * multiple sources exist with the same source function and user data,
1719 * the first one found will be returned.
1721 * Return value: (transfer none): the source, if one was found, otherwise %NULL
1724 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1725 GSourceFuncs *funcs,
1730 g_return_val_if_fail (funcs != NULL, NULL);
1732 if (context == NULL)
1733 context = g_main_context_default ();
1735 LOCK_CONTEXT (context);
1737 source = context->source_list;
1740 if (!SOURCE_DESTROYED (source) &&
1741 source->source_funcs == funcs &&
1742 source->callback_funcs)
1744 GSourceFunc callback;
1745 gpointer callback_data;
1747 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1749 if (callback_data == user_data)
1752 source = source->next;
1755 UNLOCK_CONTEXT (context);
1761 * g_main_context_find_source_by_user_data:
1762 * @context: a #GMainContext
1763 * @user_data: the user_data for the callback.
1765 * Finds a source with the given user data for the callback. If
1766 * multiple sources exist with the same user data, the first
1767 * one found will be returned.
1769 * Return value: (transfer none): the source, if one was found, otherwise %NULL
1772 g_main_context_find_source_by_user_data (GMainContext *context,
1777 if (context == NULL)
1778 context = g_main_context_default ();
1780 LOCK_CONTEXT (context);
1782 source = context->source_list;
1785 if (!SOURCE_DESTROYED (source) &&
1786 source->callback_funcs)
1788 GSourceFunc callback;
1789 gpointer callback_data = NULL;
1791 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1793 if (callback_data == user_data)
1796 source = source->next;
1799 UNLOCK_CONTEXT (context);
1806 * @tag: the ID of the source to remove.
1808 * Removes the source with the given id from the default main context.
1810 * a #GSource is given by g_source_get_id(), or will be returned by the
1811 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1812 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1813 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1815 * See also g_source_destroy(). You must use g_source_destroy() for sources
1816 * added to a non-default main context.
1818 * Return value: %TRUE if the source was found and removed.
1821 g_source_remove (guint tag)
1825 g_return_val_if_fail (tag > 0, FALSE);
1827 source = g_main_context_find_source_by_id (NULL, tag);
1829 g_source_destroy (source);
1831 return source != NULL;
1835 * g_source_remove_by_user_data:
1836 * @user_data: the user_data for the callback.
1838 * Removes a source from the default main loop context given the user
1839 * data for the callback. If multiple sources exist with the same user
1840 * data, only one will be destroyed.
1842 * Return value: %TRUE if a source was found and removed.
1845 g_source_remove_by_user_data (gpointer user_data)
1849 source = g_main_context_find_source_by_user_data (NULL, user_data);
1852 g_source_destroy (source);
1860 * g_source_remove_by_funcs_user_data:
1861 * @funcs: The @source_funcs passed to g_source_new()
1862 * @user_data: the user data for the callback
1864 * Removes a source from the default main loop context given the
1865 * source functions and user data. If multiple sources exist with the
1866 * same source functions and user data, only one will be destroyed.
1868 * Return value: %TRUE if a source was found and removed.
1871 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1876 g_return_val_if_fail (funcs != NULL, FALSE);
1878 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1881 g_source_destroy (source);
1889 * g_get_current_time:
1890 * @result: #GTimeVal structure in which to store current time.
1892 * Equivalent to the UNIX gettimeofday() function, but portable.
1894 * You may find g_get_real_time() to be more convenient.
1897 g_get_current_time (GTimeVal *result)
1902 g_return_if_fail (result != NULL);
1904 /*this is required on alpha, there the timeval structs are int's
1905 not longs and a cast only would fail horribly*/
1906 gettimeofday (&r, NULL);
1907 result->tv_sec = r.tv_sec;
1908 result->tv_usec = r.tv_usec;
1913 g_return_if_fail (result != NULL);
1915 GetSystemTimeAsFileTime (&ft);
1916 memmove (&time64, &ft, sizeof (FILETIME));
1918 /* Convert from 100s of nanoseconds since 1601-01-01
1919 * to Unix epoch. Yes, this is Y2038 unsafe.
1921 time64 -= G_GINT64_CONSTANT (116444736000000000);
1924 result->tv_sec = time64 / 1000000;
1925 result->tv_usec = time64 % 1000000;
1932 * Queries the system wall-clock time.
1934 * This call is functionally equivalent to g_get_current_time() except
1935 * that the return value is often more convenient than dealing with a
1938 * You should only use this call if you are actually interested in the real
1939 * wall-clock time. g_get_monotonic_time() is probably more useful for
1940 * measuring intervals.
1942 * Returns: the number of microseconds since January 1, 1970 UTC.
1947 g_get_real_time (void)
1951 g_get_current_time (&tv);
1953 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
1957 * g_get_monotonic_time:
1959 * Queries the system monotonic time, if available.
1961 * On POSIX systems with clock_gettime() and %CLOCK_MONOTONIC this call
1962 * is a very shallow wrapper for that. Otherwise, we make a best effort
1963 * that probably involves returning the wall clock time (with at least
1964 * microsecond accuracy, subject to the limitations of the OS kernel).
1966 * It's important to note that POSIX %CLOCK_MONOTONIC does not count
1967 * time spent while the machine is suspended.
1969 * On Windows, "limitations of the OS kernel" is a rather substantial
1970 * statement. Depending on the configuration of the system, the wall
1971 * clock time is updated as infrequently as 64 times a second (which
1972 * is approximately every 16ms).
1974 * Returns: the monotonic time, in microseconds
1979 g_get_monotonic_time (void)
1981 #ifdef HAVE_CLOCK_GETTIME
1982 /* librt clock_gettime() is our first choice */
1984 #ifdef HAVE_MONOTONIC_CLOCK
1985 static volatile gsize clockid = 0;
1987 static clockid_t clockid = CLOCK_REALTIME;
1991 #ifdef HAVE_MONOTONIC_CLOCK
1992 if (g_once_init_enter (&clockid))
1994 clockid_t best_clockid;
1996 if (sysconf (_SC_MONOTONIC_CLOCK) >= 0)
1997 best_clockid = CLOCK_MONOTONIC;
1999 best_clockid = CLOCK_REALTIME;
2000 g_once_init_leave (&clockid, (gsize)best_clockid);
2004 clock_gettime (clockid, &ts);
2006 /* In theory monotonic time can have any epoch.
2008 * glib presently assumes the following:
2010 * 1) The epoch comes some time after the birth of Jesus of Nazareth, but
2011 * not more than 10000 years later.
2013 * 2) The current time also falls sometime within this range.
2015 * These two reasonable assumptions leave us with a maximum deviation from
2016 * the epoch of 10000 years, or 315569520000000000 seconds.
2018 * If we restrict ourselves to this range then the number of microseconds
2019 * will always fit well inside the constraints of a int64 (by a factor of
2022 * If you actually hit the following assertion, probably you should file a
2023 * bug against your operating system for being excessively silly.
2025 g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts.tv_sec &&
2026 ts.tv_sec < G_GINT64_CONSTANT (315569520000000000));
2028 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2031 /* It may look like we are discarding accuracy on Windows (since its
2032 * current time is expressed in 100s of nanoseconds) but according to
2033 * many sources, the time is only updated 64 times per second, so
2034 * microsecond accuracy is more than enough.
2039 g_get_current_time (&tv);
2041 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2047 g_main_dispatch_free (gpointer dispatch)
2049 g_slice_free (GMainDispatch, dispatch);
2052 /* Running the main loop */
2054 static GMainDispatch *
2057 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
2058 GMainDispatch *dispatch = g_static_private_get (&depth_private);
2061 dispatch = g_slice_new0 (GMainDispatch);
2062 g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
2071 * Returns the depth of the stack of calls to
2072 * g_main_context_dispatch() on any #GMainContext in the current thread.
2073 * That is, when called from the toplevel, it gives 0. When
2074 * called from within a callback from g_main_context_iteration()
2075 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2076 * a callback to a recursive call to g_main_context_iteration(),
2077 * it returns 2. And so forth.
2079 * This function is useful in a situation like the following:
2080 * Imagine an extremely simple "garbage collected" system.
2083 * static GList *free_list;
2086 * allocate_memory (gsize size)
2088 * gpointer result = g_malloc (size);
2089 * free_list = g_list_prepend (free_list, result);
2094 * free_allocated_memory (void)
2097 * for (l = free_list; l; l = l->next);
2099 * g_list_free (free_list);
2107 * g_main_context_iteration (NULL, TRUE);
2108 * free_allocated_memory();
2112 * This works from an application, however, if you want to do the same
2113 * thing from a library, it gets more difficult, since you no longer
2114 * control the main loop. You might think you can simply use an idle
2115 * function to make the call to free_allocated_memory(), but that
2116 * doesn't work, since the idle function could be called from a
2117 * recursive callback. This can be fixed by using g_main_depth()
2121 * allocate_memory (gsize size)
2123 * FreeListBlock *block = g_new (FreeListBlock, 1);
2124 * block->mem = g_malloc (size);
2125 * block->depth = g_main_depth ();
2126 * free_list = g_list_prepend (free_list, block);
2127 * return block->mem;
2131 * free_allocated_memory (void)
2135 * int depth = g_main_depth ();
2136 * for (l = free_list; l; );
2138 * GList *next = l->next;
2139 * FreeListBlock *block = l->data;
2140 * if (block->depth > depth)
2142 * g_free (block->mem);
2144 * free_list = g_list_delete_link (free_list, l);
2152 * There is a temptation to use g_main_depth() to solve
2153 * problems with reentrancy. For instance, while waiting for data
2154 * to be received from the network in response to a menu item,
2155 * the menu item might be selected again. It might seem that
2156 * one could make the menu item's callback return immediately
2157 * and do nothing if g_main_depth() returns a value greater than 1.
2158 * However, this should be avoided since the user then sees selecting
2159 * the menu item do nothing. Furthermore, you'll find yourself adding
2160 * these checks all over your code, since there are doubtless many,
2161 * many things that the user could do. Instead, you can use the
2162 * following techniques:
2167 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
2168 * the user from interacting with elements while the main
2169 * loop is recursing.
2174 * Avoid main loop recursion in situations where you can't handle
2175 * arbitrary callbacks. Instead, structure your code so that you
2176 * simply return to the main loop and then get called again when
2177 * there is more work to do.
2182 * Return value: The main loop recursion level in the current thread
2187 GMainDispatch *dispatch = get_dispatch ();
2188 return dispatch->depth;
2192 * g_main_current_source:
2194 * Returns the currently firing source for this thread.
2196 * Return value: (transfer none): The currently firing source or %NULL.
2201 g_main_current_source (void)
2203 GMainDispatch *dispatch = get_dispatch ();
2204 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
2208 * g_source_is_destroyed:
2209 * @source: a #GSource
2211 * Returns whether @source has been destroyed.
2213 * This is important when you operate upon your objects
2214 * from within idle handlers, but may have freed the object
2215 * before the dispatch of your idle handler.
2219 * idle_callback (gpointer data)
2221 * SomeWidget *self = data;
2223 * GDK_THREADS_ENTER (<!-- -->);
2224 * /<!-- -->* do stuff with self *<!-- -->/
2225 * self->idle_id = 0;
2226 * GDK_THREADS_LEAVE (<!-- -->);
2232 * some_widget_do_stuff_later (SomeWidget *self)
2234 * self->idle_id = g_idle_add (idle_callback, self);
2238 * some_widget_finalize (GObject *object)
2240 * SomeWidget *self = SOME_WIDGET (object);
2242 * if (self->idle_id)
2243 * g_source_remove (self->idle_id);
2245 * G_OBJECT_CLASS (parent_class)->finalize (object);
2249 * This will fail in a multi-threaded application if the
2250 * widget is destroyed before the idle handler fires due
2251 * to the use after free in the callback. A solution, to
2252 * this particular problem, is to check to if the source
2253 * has already been destroy within the callback.
2257 * idle_callback (gpointer data)
2259 * SomeWidget *self = data;
2261 * GDK_THREADS_ENTER ();
2262 * if (!g_source_is_destroyed (g_main_current_source ()))
2264 * /<!-- -->* do stuff with self *<!-- -->/
2266 * GDK_THREADS_LEAVE ();
2272 * Return value: %TRUE if the source has been destroyed
2277 g_source_is_destroyed (GSource *source)
2279 return SOURCE_DESTROYED (source);
2282 /* Temporarily remove all this source's file descriptors from the
2283 * poll(), so that if data comes available for one of the file descriptors
2284 * we don't continually spin in the poll()
2286 /* HOLDS: source->context's lock */
2288 block_source (GSource *source)
2292 g_return_if_fail (!SOURCE_BLOCKED (source));
2294 tmp_list = source->poll_fds;
2297 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2298 tmp_list = tmp_list->next;
2302 /* HOLDS: source->context's lock */
2304 unblock_source (GSource *source)
2308 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
2309 g_return_if_fail (!SOURCE_DESTROYED (source));
2311 tmp_list = source->poll_fds;
2314 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2315 tmp_list = tmp_list->next;
2319 /* HOLDS: context's lock */
2321 g_main_dispatch (GMainContext *context)
2323 GMainDispatch *current = get_dispatch ();
2326 for (i = 0; i < context->pending_dispatches->len; i++)
2328 GSource *source = context->pending_dispatches->pdata[i];
2330 context->pending_dispatches->pdata[i] = NULL;
2333 source->flags &= ~G_SOURCE_READY;
2335 if (!SOURCE_DESTROYED (source))
2337 gboolean was_in_call;
2338 gpointer user_data = NULL;
2339 GSourceFunc callback = NULL;
2340 GSourceCallbackFuncs *cb_funcs;
2342 gboolean need_destroy;
2344 gboolean (*dispatch) (GSource *,
2347 GSList current_source_link;
2349 dispatch = source->source_funcs->dispatch;
2350 cb_funcs = source->callback_funcs;
2351 cb_data = source->callback_data;
2354 cb_funcs->ref (cb_data);
2356 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2357 block_source (source);
2359 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2360 source->flags |= G_HOOK_FLAG_IN_CALL;
2363 cb_funcs->get (cb_data, source, &callback, &user_data);
2365 UNLOCK_CONTEXT (context);
2368 /* The on-stack allocation of the GSList is unconventional, but
2369 * we know that the lifetime of the link is bounded to this
2370 * function as the link is kept in a thread specific list and
2371 * not manipulated outside of this function and its descendants.
2372 * Avoiding the overhead of a g_slist_alloc() is useful as many
2373 * applications do little more than dispatch events.
2375 * This is a performance hack - do not revert to g_slist_prepend()!
2377 current_source_link.data = source;
2378 current_source_link.next = current->dispatching_sources;
2379 current->dispatching_sources = ¤t_source_link;
2380 need_destroy = ! dispatch (source,
2383 g_assert (current->dispatching_sources == ¤t_source_link);
2384 current->dispatching_sources = current_source_link.next;
2388 cb_funcs->unref (cb_data);
2390 LOCK_CONTEXT (context);
2393 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2395 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2396 !SOURCE_DESTROYED (source))
2397 unblock_source (source);
2399 /* Note: this depends on the fact that we can't switch
2400 * sources from one main context to another
2402 if (need_destroy && !SOURCE_DESTROYED (source))
2404 g_assert (source->context == context);
2405 g_source_destroy_internal (source, context, TRUE);
2409 SOURCE_UNREF (source, context);
2412 g_ptr_array_set_size (context->pending_dispatches, 0);
2415 /* Holds context's lock */
2416 static inline GSource *
2417 next_valid_source (GMainContext *context,
2420 GSource *new_source = source ? source->next : context->source_list;
2424 if (!SOURCE_DESTROYED (new_source))
2426 new_source->ref_count++;
2430 new_source = new_source->next;
2434 SOURCE_UNREF (source, context);
2440 * g_main_context_acquire:
2441 * @context: a #GMainContext
2443 * Tries to become the owner of the specified context.
2444 * If some other thread is the owner of the context,
2445 * returns %FALSE immediately. Ownership is properly
2446 * recursive: the owner can require ownership again
2447 * and will release ownership when g_main_context_release()
2448 * is called as many times as g_main_context_acquire().
2450 * You must be the owner of a context before you
2451 * can call g_main_context_prepare(), g_main_context_query(),
2452 * g_main_context_check(), g_main_context_dispatch().
2454 * Return value: %TRUE if the operation succeeded, and
2455 * this thread is now the owner of @context.
2458 g_main_context_acquire (GMainContext *context)
2460 gboolean result = FALSE;
2461 GThread *self = G_THREAD_SELF;
2463 if (context == NULL)
2464 context = g_main_context_default ();
2466 LOCK_CONTEXT (context);
2468 if (!context->owner)
2470 context->owner = self;
2471 g_assert (context->owner_count == 0);
2474 if (context->owner == self)
2476 context->owner_count++;
2480 UNLOCK_CONTEXT (context);
2486 * g_main_context_release:
2487 * @context: a #GMainContext
2489 * Releases ownership of a context previously acquired by this thread
2490 * with g_main_context_acquire(). If the context was acquired multiple
2491 * times, the ownership will be released only when g_main_context_release()
2492 * is called as many times as it was acquired.
2495 g_main_context_release (GMainContext *context)
2497 if (context == NULL)
2498 context = g_main_context_default ();
2500 LOCK_CONTEXT (context);
2502 context->owner_count--;
2503 if (context->owner_count == 0)
2505 context->owner = NULL;
2507 if (context->waiters)
2509 GMainWaiter *waiter = context->waiters->data;
2510 gboolean loop_internal_waiter =
2511 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
2512 context->waiters = g_slist_delete_link (context->waiters,
2514 if (!loop_internal_waiter)
2515 g_mutex_lock (waiter->mutex);
2517 g_cond_signal (waiter->cond);
2519 if (!loop_internal_waiter)
2520 g_mutex_unlock (waiter->mutex);
2524 UNLOCK_CONTEXT (context);
2528 * g_main_context_wait:
2529 * @context: a #GMainContext
2530 * @cond: a condition variable
2531 * @mutex: a mutex, currently held
2533 * Tries to become the owner of the specified context,
2534 * as with g_main_context_acquire(). But if another thread
2535 * is the owner, atomically drop @mutex and wait on @cond until
2536 * that owner releases ownership or until @cond is signaled, then
2537 * try again (once) to become the owner.
2539 * Return value: %TRUE if the operation succeeded, and
2540 * this thread is now the owner of @context.
2543 g_main_context_wait (GMainContext *context,
2547 gboolean result = FALSE;
2548 GThread *self = G_THREAD_SELF;
2549 gboolean loop_internal_waiter;
2551 if (context == NULL)
2552 context = g_main_context_default ();
2554 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2556 if (!loop_internal_waiter)
2557 LOCK_CONTEXT (context);
2559 if (context->owner && context->owner != self)
2564 waiter.mutex = mutex;
2566 context->waiters = g_slist_append (context->waiters, &waiter);
2568 if (!loop_internal_waiter)
2569 UNLOCK_CONTEXT (context);
2570 g_cond_wait (cond, mutex);
2571 if (!loop_internal_waiter)
2572 LOCK_CONTEXT (context);
2574 context->waiters = g_slist_remove (context->waiters, &waiter);
2577 if (!context->owner)
2579 context->owner = self;
2580 g_assert (context->owner_count == 0);
2583 if (context->owner == self)
2585 context->owner_count++;
2589 if (!loop_internal_waiter)
2590 UNLOCK_CONTEXT (context);
2596 * g_main_context_prepare:
2597 * @context: a #GMainContext
2598 * @priority: location to store priority of highest priority
2599 * source already ready.
2601 * Prepares to poll sources within a main loop. The resulting information
2602 * for polling is determined by calling g_main_context_query ().
2604 * Return value: %TRUE if some source is ready to be dispatched
2608 g_main_context_prepare (GMainContext *context,
2613 gint current_priority = G_MAXINT;
2616 if (context == NULL)
2617 context = g_main_context_default ();
2619 LOCK_CONTEXT (context);
2621 context->time_is_fresh = FALSE;
2622 context->real_time_is_fresh = FALSE;
2624 if (context->in_check_or_prepare)
2626 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2627 "prepare() member.");
2628 UNLOCK_CONTEXT (context);
2632 if (context->poll_waiting)
2634 g_warning("g_main_context_prepare(): main loop already active in another thread");
2635 UNLOCK_CONTEXT (context);
2639 context->poll_waiting = TRUE;
2642 /* If recursing, finish up current dispatch, before starting over */
2643 if (context->pending_dispatches)
2646 g_main_dispatch (context, ¤t_time);
2648 UNLOCK_CONTEXT (context);
2653 /* If recursing, clear list of pending dispatches */
2655 for (i = 0; i < context->pending_dispatches->len; i++)
2657 if (context->pending_dispatches->pdata[i])
2658 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2660 g_ptr_array_set_size (context->pending_dispatches, 0);
2662 /* Prepare all sources */
2664 context->timeout = -1;
2666 source = next_valid_source (context, NULL);
2669 gint source_timeout = -1;
2671 if ((n_ready > 0) && (source->priority > current_priority))
2673 SOURCE_UNREF (source, context);
2676 if (SOURCE_BLOCKED (source))
2679 if (!(source->flags & G_SOURCE_READY))
2682 gboolean (*prepare) (GSource *source,
2685 prepare = source->source_funcs->prepare;
2686 context->in_check_or_prepare++;
2687 UNLOCK_CONTEXT (context);
2689 result = (*prepare) (source, &source_timeout);
2691 LOCK_CONTEXT (context);
2692 context->in_check_or_prepare--;
2696 GSource *ready_source = source;
2698 while (ready_source)
2700 ready_source->flags |= G_SOURCE_READY;
2701 ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2706 if (source->flags & G_SOURCE_READY)
2709 current_priority = source->priority;
2710 context->timeout = 0;
2713 if (source_timeout >= 0)
2715 if (context->timeout < 0)
2716 context->timeout = source_timeout;
2718 context->timeout = MIN (context->timeout, source_timeout);
2722 source = next_valid_source (context, source);
2725 UNLOCK_CONTEXT (context);
2728 *priority = current_priority;
2730 return (n_ready > 0);
2734 * g_main_context_query:
2735 * @context: a #GMainContext
2736 * @max_priority: maximum priority source to check
2737 * @timeout_: (out): location to store timeout to be used in polling
2738 * @fds: (out caller-allocates) (array length=n_fds): location to
2739 * store #GPollFD records that need to be polled.
2740 * @n_fds: length of @fds.
2742 * Determines information necessary to poll this main loop.
2744 * Return value: the number of records actually stored in @fds,
2745 * or, if more than @n_fds records need to be stored, the number
2746 * of records that need to be stored.
2749 g_main_context_query (GMainContext *context,
2758 LOCK_CONTEXT (context);
2760 pollrec = context->poll_records;
2762 while (pollrec && max_priority >= pollrec->priority)
2764 /* We need to include entries with fd->events == 0 in the array because
2765 * otherwise if the application changes fd->events behind our back and
2766 * makes it non-zero, we'll be out of sync when we check the fds[] array.
2767 * (Changing fd->events after adding an FD wasn't an anticipated use of
2768 * this API, but it occurs in practice.) */
2771 fds[n_poll].fd = pollrec->fd->fd;
2772 /* In direct contradiction to the Unix98 spec, IRIX runs into
2773 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2774 * flags in the events field of the pollfd while it should
2775 * just ignoring them. So we mask them out here.
2777 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2778 fds[n_poll].revents = 0;
2781 pollrec = pollrec->next;
2785 context->poll_changed = FALSE;
2789 *timeout = context->timeout;
2792 context->time_is_fresh = FALSE;
2793 context->real_time_is_fresh = FALSE;
2797 UNLOCK_CONTEXT (context);
2803 * g_main_context_check:
2804 * @context: a #GMainContext
2805 * @max_priority: the maximum numerical priority of sources to check
2806 * @fds: (array length=n_fds): array of #GPollFD's that was passed to
2807 * the last call to g_main_context_query()
2808 * @n_fds: return value of g_main_context_query()
2810 * Passes the results of polling back to the main loop.
2812 * Return value: %TRUE if some sources are ready to be dispatched.
2815 g_main_context_check (GMainContext *context,
2825 LOCK_CONTEXT (context);
2827 if (context->in_check_or_prepare)
2829 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2830 "prepare() member.");
2831 UNLOCK_CONTEXT (context);
2835 if (context->wake_up_rec.events)
2836 g_wakeup_acknowledge (context->wakeup);
2838 context->poll_waiting = FALSE;
2840 /* If the set of poll file descriptors changed, bail out
2841 * and let the main loop rerun
2843 if (context->poll_changed)
2845 UNLOCK_CONTEXT (context);
2849 pollrec = context->poll_records;
2853 if (pollrec->fd->events)
2854 pollrec->fd->revents = fds[i].revents;
2856 pollrec = pollrec->next;
2860 source = next_valid_source (context, NULL);
2863 if ((n_ready > 0) && (source->priority > max_priority))
2865 SOURCE_UNREF (source, context);
2868 if (SOURCE_BLOCKED (source))
2871 if (!(source->flags & G_SOURCE_READY))
2874 gboolean (*check) (GSource *source);
2876 check = source->source_funcs->check;
2878 context->in_check_or_prepare++;
2879 UNLOCK_CONTEXT (context);
2881 result = (*check) (source);
2883 LOCK_CONTEXT (context);
2884 context->in_check_or_prepare--;
2888 GSource *ready_source = source;
2890 while (ready_source)
2892 ready_source->flags |= G_SOURCE_READY;
2893 ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2898 if (source->flags & G_SOURCE_READY)
2900 source->ref_count++;
2901 g_ptr_array_add (context->pending_dispatches, source);
2905 /* never dispatch sources with less priority than the first
2906 * one we choose to dispatch
2908 max_priority = source->priority;
2912 source = next_valid_source (context, source);
2915 UNLOCK_CONTEXT (context);
2921 * g_main_context_dispatch:
2922 * @context: a #GMainContext
2924 * Dispatches all pending sources.
2927 g_main_context_dispatch (GMainContext *context)
2929 LOCK_CONTEXT (context);
2931 if (context->pending_dispatches->len > 0)
2933 g_main_dispatch (context);
2936 UNLOCK_CONTEXT (context);
2939 /* HOLDS context lock */
2941 g_main_context_iterate (GMainContext *context,
2948 gboolean some_ready;
2949 gint nfds, allocated_nfds;
2950 GPollFD *fds = NULL;
2952 UNLOCK_CONTEXT (context);
2954 if (!g_main_context_acquire (context))
2956 gboolean got_ownership;
2958 LOCK_CONTEXT (context);
2964 context->cond = g_cond_new ();
2966 got_ownership = g_main_context_wait (context,
2968 g_static_mutex_get_mutex (&context->mutex));
2974 LOCK_CONTEXT (context);
2976 if (!context->cached_poll_array)
2978 context->cached_poll_array_size = context->n_poll_records;
2979 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2982 allocated_nfds = context->cached_poll_array_size;
2983 fds = context->cached_poll_array;
2985 UNLOCK_CONTEXT (context);
2987 g_main_context_prepare (context, &max_priority);
2989 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
2990 allocated_nfds)) > allocated_nfds)
2992 LOCK_CONTEXT (context);
2994 context->cached_poll_array_size = allocated_nfds = nfds;
2995 context->cached_poll_array = fds = g_new (GPollFD, nfds);
2996 UNLOCK_CONTEXT (context);
3002 g_main_context_poll (context, timeout, max_priority, fds, nfds);
3004 some_ready = g_main_context_check (context, max_priority, fds, nfds);
3007 g_main_context_dispatch (context);
3009 g_main_context_release (context);
3011 LOCK_CONTEXT (context);
3017 * g_main_context_pending:
3018 * @context: a #GMainContext (if %NULL, the default context will be used)
3020 * Checks if any sources have pending events for the given context.
3022 * Return value: %TRUE if events are pending.
3025 g_main_context_pending (GMainContext *context)
3030 context = g_main_context_default();
3032 LOCK_CONTEXT (context);
3033 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3034 UNLOCK_CONTEXT (context);
3040 * g_main_context_iteration:
3041 * @context: a #GMainContext (if %NULL, the default context will be used)
3042 * @may_block: whether the call may block.
3044 * Runs a single iteration for the given main loop. This involves
3045 * checking to see if any event sources are ready to be processed,
3046 * then if no events sources are ready and @may_block is %TRUE, waiting
3047 * for a source to become ready, then dispatching the highest priority
3048 * events sources that are ready. Otherwise, if @may_block is %FALSE
3049 * sources are not waited to become ready, only those highest priority
3050 * events sources will be dispatched (if any), that are ready at this
3051 * given moment without further waiting.
3053 * Note that even when @may_block is %TRUE, it is still possible for
3054 * g_main_context_iteration() to return %FALSE, since the the wait may
3055 * be interrupted for other reasons than an event source becoming ready.
3057 * Return value: %TRUE if events were dispatched.
3060 g_main_context_iteration (GMainContext *context, gboolean may_block)
3065 context = g_main_context_default();
3067 LOCK_CONTEXT (context);
3068 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3069 UNLOCK_CONTEXT (context);
3076 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
3077 * @is_running: set to %TRUE to indicate that the loop is running. This
3078 * is not very important since calling g_main_loop_run() will set this to
3081 * Creates a new #GMainLoop structure.
3083 * Return value: a new #GMainLoop.
3086 g_main_loop_new (GMainContext *context,
3087 gboolean is_running)
3092 context = g_main_context_default();
3094 g_main_context_ref (context);
3096 loop = g_new0 (GMainLoop, 1);
3097 loop->context = context;
3098 loop->is_running = is_running != FALSE;
3099 loop->ref_count = 1;
3106 * @loop: a #GMainLoop
3108 * Increases the reference count on a #GMainLoop object by one.
3110 * Return value: @loop
3113 g_main_loop_ref (GMainLoop *loop)
3115 g_return_val_if_fail (loop != NULL, NULL);
3116 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3118 g_atomic_int_inc (&loop->ref_count);
3124 * g_main_loop_unref:
3125 * @loop: a #GMainLoop
3127 * Decreases the reference count on a #GMainLoop object by one. If
3128 * the result is zero, free the loop and free all associated memory.
3131 g_main_loop_unref (GMainLoop *loop)
3133 g_return_if_fail (loop != NULL);
3134 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3136 if (!g_atomic_int_dec_and_test (&loop->ref_count))
3139 g_main_context_unref (loop->context);
3145 * @loop: a #GMainLoop
3147 * Runs a main loop until g_main_loop_quit() is called on the loop.
3148 * If this is called for the thread of the loop's #GMainContext,
3149 * it will process events from the loop, otherwise it will
3153 g_main_loop_run (GMainLoop *loop)
3155 GThread *self = G_THREAD_SELF;
3157 g_return_if_fail (loop != NULL);
3158 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3160 if (!g_main_context_acquire (loop->context))
3162 gboolean got_ownership = FALSE;
3164 /* Another thread owns this context */
3165 LOCK_CONTEXT (loop->context);
3167 g_atomic_int_inc (&loop->ref_count);
3169 if (!loop->is_running)
3170 loop->is_running = TRUE;
3172 if (!loop->context->cond)
3173 loop->context->cond = g_cond_new ();
3175 while (loop->is_running && !got_ownership)
3176 got_ownership = g_main_context_wait (loop->context,
3177 loop->context->cond,
3178 g_static_mutex_get_mutex (&loop->context->mutex));
3180 if (!loop->is_running)
3182 UNLOCK_CONTEXT (loop->context);
3184 g_main_context_release (loop->context);
3185 g_main_loop_unref (loop);
3189 g_assert (got_ownership);
3192 LOCK_CONTEXT (loop->context);
3194 if (loop->context->in_check_or_prepare)
3196 g_warning ("g_main_loop_run(): called recursively from within a source's "
3197 "check() or prepare() member, iteration not possible.");
3201 g_atomic_int_inc (&loop->ref_count);
3202 loop->is_running = TRUE;
3203 while (loop->is_running)
3204 g_main_context_iterate (loop->context, TRUE, TRUE, self);
3206 UNLOCK_CONTEXT (loop->context);
3208 g_main_context_release (loop->context);
3210 g_main_loop_unref (loop);
3215 * @loop: a #GMainLoop
3217 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3218 * for the loop will return.
3220 * Note that sources that have already been dispatched when
3221 * g_main_loop_quit() is called will still be executed.
3224 g_main_loop_quit (GMainLoop *loop)
3226 g_return_if_fail (loop != NULL);
3227 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3229 LOCK_CONTEXT (loop->context);
3230 loop->is_running = FALSE;
3231 g_main_context_wakeup_unlocked (loop->context);
3233 if (loop->context->cond)
3234 g_cond_broadcast (loop->context->cond);
3236 UNLOCK_CONTEXT (loop->context);
3240 * g_main_loop_is_running:
3241 * @loop: a #GMainLoop.
3243 * Checks to see if the main loop is currently being run via g_main_loop_run().
3245 * Return value: %TRUE if the mainloop is currently being run.
3248 g_main_loop_is_running (GMainLoop *loop)
3250 g_return_val_if_fail (loop != NULL, FALSE);
3251 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3253 return loop->is_running;
3257 * g_main_loop_get_context:
3258 * @loop: a #GMainLoop.
3260 * Returns the #GMainContext of @loop.
3262 * Return value: (transfer none): the #GMainContext of @loop
3265 g_main_loop_get_context (GMainLoop *loop)
3267 g_return_val_if_fail (loop != NULL, NULL);
3268 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3270 return loop->context;
3273 /* HOLDS: context's lock */
3275 g_main_context_poll (GMainContext *context,
3281 #ifdef G_MAIN_POLL_DEBUG
3287 GPollFunc poll_func;
3289 if (n_fds || timeout != 0)
3291 #ifdef G_MAIN_POLL_DEBUG
3292 if (_g_main_poll_debug)
3294 g_print ("polling context=%p n=%d timeout=%d\n",
3295 context, n_fds, timeout);
3296 poll_timer = g_timer_new ();
3300 LOCK_CONTEXT (context);
3302 poll_func = context->poll_func;
3304 UNLOCK_CONTEXT (context);
3305 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3308 g_warning ("poll(2) failed due to: %s.",
3309 g_strerror (errno));
3311 /* If g_poll () returns -1, it has already called g_warning() */
3315 #ifdef G_MAIN_POLL_DEBUG
3316 if (_g_main_poll_debug)
3318 LOCK_CONTEXT (context);
3320 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3323 g_timer_elapsed (poll_timer, NULL));
3324 g_timer_destroy (poll_timer);
3325 pollrec = context->poll_records;
3327 while (pollrec != NULL)
3332 if (fds[i].fd == pollrec->fd->fd &&
3333 pollrec->fd->events &&
3336 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3337 if (fds[i].revents & G_IO_IN)
3339 if (fds[i].revents & G_IO_OUT)
3341 if (fds[i].revents & G_IO_PRI)
3343 if (fds[i].revents & G_IO_ERR)
3345 if (fds[i].revents & G_IO_HUP)
3347 if (fds[i].revents & G_IO_NVAL)
3353 pollrec = pollrec->next;
3357 UNLOCK_CONTEXT (context);
3360 } /* if (n_fds || timeout != 0) */
3364 * g_main_context_add_poll:
3365 * @context: a #GMainContext (or %NULL for the default context)
3366 * @fd: a #GPollFD structure holding information about a file
3367 * descriptor to watch.
3368 * @priority: the priority for this file descriptor which should be
3369 * the same as the priority used for g_source_attach() to ensure that the
3370 * file descriptor is polled whenever the results may be needed.
3372 * Adds a file descriptor to the set of file descriptors polled for
3373 * this context. This will very seldom be used directly. Instead
3374 * a typical event source will use g_source_add_poll() instead.
3377 g_main_context_add_poll (GMainContext *context,
3382 context = g_main_context_default ();
3384 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3385 g_return_if_fail (fd);
3387 LOCK_CONTEXT (context);
3388 g_main_context_add_poll_unlocked (context, priority, fd);
3389 UNLOCK_CONTEXT (context);
3392 /* HOLDS: main_loop_lock */
3394 g_main_context_add_poll_unlocked (GMainContext *context,
3398 GPollRec *prevrec, *nextrec;
3399 GPollRec *newrec = g_slice_new (GPollRec);
3401 /* This file descriptor may be checked before we ever poll */
3404 newrec->priority = priority;
3406 prevrec = context->poll_records_tail;
3408 while (prevrec && priority < prevrec->priority)
3411 prevrec = prevrec->prev;
3415 prevrec->next = newrec;
3417 context->poll_records = newrec;
3419 newrec->prev = prevrec;
3420 newrec->next = nextrec;
3423 nextrec->prev = newrec;
3425 context->poll_records_tail = newrec;
3427 context->n_poll_records++;
3429 context->poll_changed = TRUE;
3431 /* Now wake up the main loop if it is waiting in the poll() */
3432 g_main_context_wakeup_unlocked (context);
3436 * g_main_context_remove_poll:
3437 * @context:a #GMainContext
3438 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3440 * Removes file descriptor from the set of file descriptors to be
3441 * polled for a particular context.
3444 g_main_context_remove_poll (GMainContext *context,
3448 context = g_main_context_default ();
3450 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3451 g_return_if_fail (fd);
3453 LOCK_CONTEXT (context);
3454 g_main_context_remove_poll_unlocked (context, fd);
3455 UNLOCK_CONTEXT (context);
3459 g_main_context_remove_poll_unlocked (GMainContext *context,
3462 GPollRec *pollrec, *prevrec, *nextrec;
3465 pollrec = context->poll_records;
3469 nextrec = pollrec->next;
3470 if (pollrec->fd == fd)
3472 if (prevrec != NULL)
3473 prevrec->next = nextrec;
3475 context->poll_records = nextrec;
3477 if (nextrec != NULL)
3478 nextrec->prev = prevrec;
3480 context->poll_records_tail = prevrec;
3482 g_slice_free (GPollRec, pollrec);
3484 context->n_poll_records--;
3491 context->poll_changed = TRUE;
3493 /* Now wake up the main loop if it is waiting in the poll() */
3494 g_main_context_wakeup_unlocked (context);
3498 * g_source_get_current_time:
3499 * @source: a #GSource
3500 * @timeval: #GTimeVal structure in which to store current time.
3502 * Gets the "current time" to be used when checking
3503 * this source. The advantage of calling this function over
3504 * calling g_get_current_time() directly is that when
3505 * checking multiple sources, GLib can cache a single value
3506 * instead of having to repeatedly get the system time.
3508 * Deprecated: 2.28: use g_source_get_time() instead
3511 g_source_get_current_time (GSource *source,
3514 GMainContext *context;
3516 g_return_if_fail (source->context != NULL);
3518 context = source->context;
3520 LOCK_CONTEXT (context);
3522 if (!context->real_time_is_fresh)
3524 context->real_time = g_get_real_time ();
3525 context->real_time_is_fresh = TRUE;
3528 timeval->tv_sec = context->real_time / 1000000;
3529 timeval->tv_usec = context->real_time % 1000000;
3531 UNLOCK_CONTEXT (context);
3535 * g_source_get_time:
3536 * @source: a #GSource
3538 * Gets the time to be used when checking this source. The advantage of
3539 * calling this function over calling g_get_monotonic_time() directly is
3540 * that when checking multiple sources, GLib can cache a single value
3541 * instead of having to repeatedly get the system monotonic time.
3543 * The time here is the system monotonic time, if available, or some
3544 * other reasonable alternative otherwise. See g_get_monotonic_time().
3546 * Returns: the monotonic time in microseconds
3551 g_source_get_time (GSource *source)
3553 GMainContext *context;
3556 g_return_val_if_fail (source->context != NULL, 0);
3558 context = source->context;
3560 LOCK_CONTEXT (context);
3562 if (!context->time_is_fresh)
3564 context->time = g_get_monotonic_time ();
3565 context->time_is_fresh = TRUE;
3568 result = context->time;
3570 UNLOCK_CONTEXT (context);
3576 * g_main_context_set_poll_func:
3577 * @context: a #GMainContext
3578 * @func: the function to call to poll all file descriptors
3580 * Sets the function to use to handle polling of file descriptors. It
3581 * will be used instead of the poll() system call
3582 * (or GLib's replacement function, which is used where
3583 * poll() isn't available).
3585 * This function could possibly be used to integrate the GLib event
3586 * loop with an external event loop.
3589 g_main_context_set_poll_func (GMainContext *context,
3593 context = g_main_context_default ();
3595 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3597 LOCK_CONTEXT (context);
3600 context->poll_func = func;
3602 context->poll_func = g_poll;
3604 UNLOCK_CONTEXT (context);
3608 * g_main_context_get_poll_func:
3609 * @context: a #GMainContext
3611 * Gets the poll function set by g_main_context_set_poll_func().
3613 * Return value: the poll function
3616 g_main_context_get_poll_func (GMainContext *context)
3621 context = g_main_context_default ();
3623 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3625 LOCK_CONTEXT (context);
3626 result = context->poll_func;
3627 UNLOCK_CONTEXT (context);
3632 /* HOLDS: context's lock */
3633 /* Wake the main loop up from a poll() */
3635 g_main_context_wakeup_unlocked (GMainContext *context)
3637 if (context->poll_waiting)
3639 context->poll_waiting = FALSE;
3640 g_wakeup_signal (context->wakeup);
3645 * g_main_context_wakeup:
3646 * @context: a #GMainContext
3648 * If @context is currently waiting in a poll(), interrupt
3649 * the poll(), and continue the iteration process.
3652 g_main_context_wakeup (GMainContext *context)
3655 context = g_main_context_default ();
3657 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3659 LOCK_CONTEXT (context);
3660 g_main_context_wakeup_unlocked (context);
3661 UNLOCK_CONTEXT (context);
3665 * g_main_context_is_owner:
3666 * @context: a #GMainContext
3668 * Determines whether this thread holds the (recursive)
3669 * ownership of this #GMainContext. This is useful to
3670 * know before waiting on another thread that may be
3671 * blocking to get ownership of @context.
3673 * Returns: %TRUE if current thread is owner of @context.
3678 g_main_context_is_owner (GMainContext *context)
3683 context = g_main_context_default ();
3685 LOCK_CONTEXT (context);
3686 is_owner = context->owner == G_THREAD_SELF;
3687 UNLOCK_CONTEXT (context);
3695 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3696 gint64 current_time)
3698 timeout_source->expiration = current_time +
3699 (guint64) timeout_source->interval * 1000;
3701 if (timeout_source->seconds)
3704 static gint timer_perturb = -1;
3706 if (timer_perturb == -1)
3709 * we want a per machine/session unique 'random' value; try the dbus
3710 * address first, that has a UUID in it. If there is no dbus, use the
3711 * hostname for hashing.
3713 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3714 if (!session_bus_address)
3715 session_bus_address = g_getenv ("HOSTNAME");
3716 if (session_bus_address)
3717 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
3722 /* We want the microseconds part of the timeout to land on the
3723 * 'timer_perturb' mark, but we need to make sure we don't try to
3724 * set the timeout in the past. We do this by ensuring that we
3725 * always only *increase* the expiration time by adding a full
3726 * second in the case that the microsecond portion decreases.
3728 timeout_source->expiration -= timer_perturb;
3730 remainder = timeout_source->expiration % 1000000;
3731 if (remainder >= 1000000/4)
3732 timeout_source->expiration += 1000000;
3734 timeout_source->expiration -= remainder;
3735 timeout_source->expiration += timer_perturb;
3740 g_timeout_prepare (GSource *source,
3743 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3744 gint64 now = g_source_get_time (source);
3746 if (now < timeout_source->expiration)
3748 /* Round up to ensure that we don't try again too early */
3749 *timeout = (timeout_source->expiration - now + 999) / 1000;
3758 g_timeout_check (GSource *source)
3760 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3761 gint64 now = g_source_get_time (source);
3763 return timeout_source->expiration <= now;
3767 g_timeout_dispatch (GSource *source,
3768 GSourceFunc callback,
3771 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3776 g_warning ("Timeout source dispatched without callback\n"
3777 "You must call g_source_set_callback().");
3781 again = callback (user_data);
3784 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
3790 * g_timeout_source_new:
3791 * @interval: the timeout interval in milliseconds.
3793 * Creates a new timeout source.
3795 * The source will not initially be associated with any #GMainContext
3796 * and must be added to one with g_source_attach() before it will be
3799 * The interval given is in terms of monotonic time, not wall clock
3800 * time. See g_get_monotonic_time().
3802 * Return value: the newly-created timeout source
3805 g_timeout_source_new (guint interval)
3807 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3808 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3810 timeout_source->interval = interval;
3811 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3817 * g_timeout_source_new_seconds:
3818 * @interval: the timeout interval in seconds
3820 * Creates a new timeout source.
3822 * The source will not initially be associated with any #GMainContext
3823 * and must be added to one with g_source_attach() before it will be
3826 * The scheduling granularity/accuracy of this timeout source will be
3829 * The interval given in terms of monotonic time, not wall clock time.
3830 * See g_get_monotonic_time().
3832 * Return value: the newly-created timeout source
3837 g_timeout_source_new_seconds (guint interval)
3839 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3840 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3842 timeout_source->interval = 1000 * interval;
3843 timeout_source->seconds = TRUE;
3845 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3852 * g_timeout_add_full:
3853 * @priority: the priority of the timeout source. Typically this will be in
3854 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3855 * @interval: the time between calls to the function, in milliseconds
3856 * (1/1000ths of a second)
3857 * @function: function to call
3858 * @data: data to pass to @function
3859 * @notify: function to call when the timeout is removed, or %NULL
3861 * Sets a function to be called at regular intervals, with the given
3862 * priority. The function is called repeatedly until it returns
3863 * %FALSE, at which point the timeout is automatically destroyed and
3864 * the function will not be called again. The @notify function is
3865 * called when the timeout is destroyed. The first call to the
3866 * function will be at the end of the first @interval.
3868 * Note that timeout functions may be delayed, due to the processing of other
3869 * event sources. Thus they should not be relied on for precise timing.
3870 * After each call to the timeout function, the time of the next
3871 * timeout is recalculated based on the current time and the given interval
3872 * (it does not try to 'catch up' time lost in delays).
3874 * This internally creates a main loop source using g_timeout_source_new()
3875 * and attaches it to the main loop context using g_source_attach(). You can
3876 * do these steps manually if you need greater control.
3878 * The interval given in terms of monotonic time, not wall clock time.
3879 * See g_get_monotonic_time().
3881 * Return value: the ID (greater than 0) of the event source.
3882 * Rename to: g_timeout_add
3885 g_timeout_add_full (gint priority,
3887 GSourceFunc function,
3889 GDestroyNotify notify)
3894 g_return_val_if_fail (function != NULL, 0);
3896 source = g_timeout_source_new (interval);
3898 if (priority != G_PRIORITY_DEFAULT)
3899 g_source_set_priority (source, priority);
3901 g_source_set_callback (source, function, data, notify);
3902 id = g_source_attach (source, NULL);
3903 g_source_unref (source);
3910 * @interval: the time between calls to the function, in milliseconds
3911 * (1/1000ths of a second)
3912 * @function: function to call
3913 * @data: data to pass to @function
3915 * Sets a function to be called at regular intervals, with the default
3916 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
3917 * until it returns %FALSE, at which point the timeout is automatically
3918 * destroyed and the function will not be called again. The first call
3919 * to the function will be at the end of the first @interval.
3921 * Note that timeout functions may be delayed, due to the processing of other
3922 * event sources. Thus they should not be relied on for precise timing.
3923 * After each call to the timeout function, the time of the next
3924 * timeout is recalculated based on the current time and the given interval
3925 * (it does not try to 'catch up' time lost in delays).
3927 * If you want to have a timer in the "seconds" range and do not care
3928 * about the exact time of the first call of the timer, use the
3929 * g_timeout_add_seconds() function; this function allows for more
3930 * optimizations and more efficient system power usage.
3932 * This internally creates a main loop source using g_timeout_source_new()
3933 * and attaches it to the main loop context using g_source_attach(). You can
3934 * do these steps manually if you need greater control.
3936 * The interval given is in terms of monotonic time, not wall clock
3937 * time. See g_get_monotonic_time().
3939 * Return value: the ID (greater than 0) of the event source.
3942 g_timeout_add (guint32 interval,
3943 GSourceFunc function,
3946 return g_timeout_add_full (G_PRIORITY_DEFAULT,
3947 interval, function, data, NULL);
3951 * g_timeout_add_seconds_full:
3952 * @priority: the priority of the timeout source. Typically this will be in
3953 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3954 * @interval: the time between calls to the function, in seconds
3955 * @function: function to call
3956 * @data: data to pass to @function
3957 * @notify: function to call when the timeout is removed, or %NULL
3959 * Sets a function to be called at regular intervals, with @priority.
3960 * The function is called repeatedly until it returns %FALSE, at which
3961 * point the timeout is automatically destroyed and the function will
3962 * not be called again.
3964 * Unlike g_timeout_add(), this function operates at whole second granularity.
3965 * The initial starting point of the timer is determined by the implementation
3966 * and the implementation is expected to group multiple timers together so that
3967 * they fire all at the same time.
3968 * To allow this grouping, the @interval to the first timer is rounded
3969 * and can deviate up to one second from the specified interval.
3970 * Subsequent timer iterations will generally run at the specified interval.
3972 * Note that timeout functions may be delayed, due to the processing of other
3973 * event sources. Thus they should not be relied on for precise timing.
3974 * After each call to the timeout function, the time of the next
3975 * timeout is recalculated based on the current time and the given @interval
3977 * If you want timing more precise than whole seconds, use g_timeout_add()
3980 * The grouping of timers to fire at the same time results in a more power
3981 * and CPU efficient behavior so if your timer is in multiples of seconds
3982 * and you don't require the first timer exactly one second from now, the
3983 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
3985 * This internally creates a main loop source using
3986 * g_timeout_source_new_seconds() and attaches it to the main loop context
3987 * using g_source_attach(). You can do these steps manually if you need
3990 * The interval given is in terms of monotonic time, not wall clock
3991 * time. See g_get_monotonic_time().
3993 * Return value: the ID (greater than 0) of the event source.
3995 * Rename to: g_timeout_add_seconds
3999 g_timeout_add_seconds_full (gint priority,
4001 GSourceFunc function,
4003 GDestroyNotify notify)
4008 g_return_val_if_fail (function != NULL, 0);
4010 source = g_timeout_source_new_seconds (interval);
4012 if (priority != G_PRIORITY_DEFAULT)
4013 g_source_set_priority (source, priority);
4015 g_source_set_callback (source, function, data, notify);
4016 id = g_source_attach (source, NULL);
4017 g_source_unref (source);
4023 * g_timeout_add_seconds:
4024 * @interval: the time between calls to the function, in seconds
4025 * @function: function to call
4026 * @data: data to pass to @function
4028 * Sets a function to be called at regular intervals with the default
4029 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4030 * it returns %FALSE, at which point the timeout is automatically destroyed
4031 * and the function will not be called again.
4033 * This internally creates a main loop source using
4034 * g_timeout_source_new_seconds() and attaches it to the main loop context
4035 * using g_source_attach(). You can do these steps manually if you need
4036 * greater control. Also see g_timeout_add_seconds_full().
4038 * Note that the first call of the timer may not be precise for timeouts
4039 * of one second. If you need finer precision and have such a timeout,
4040 * you may want to use g_timeout_add() instead.
4042 * The interval given is in terms of monotonic time, not wall clock
4043 * time. See g_get_monotonic_time().
4045 * Return value: the ID (greater than 0) of the event source.
4050 g_timeout_add_seconds (guint interval,
4051 GSourceFunc function,
4054 g_return_val_if_fail (function != NULL, 0);
4056 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4059 /* Child watch functions */
4064 g_child_watch_prepare (GSource *source,
4073 g_child_watch_check (GSource *source)
4075 GChildWatchSource *child_watch_source;
4076 gboolean child_exited;
4078 child_watch_source = (GChildWatchSource *) source;
4080 child_exited = child_watch_source->poll.revents & G_IO_IN;
4087 * Note: We do _not_ check for the special value of STILL_ACTIVE
4088 * since we know that the process has exited and doing so runs into
4089 * problems if the child process "happens to return STILL_ACTIVE(259)"
4090 * as Microsoft's Platform SDK puts it.
4092 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4094 gchar *emsg = g_win32_error_message (GetLastError ());
4095 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4098 child_watch_source->child_status = -1;
4101 child_watch_source->child_status = child_status;
4104 return child_exited;
4107 #else /* G_OS_WIN32 */
4110 wake_source (GSource *source)
4112 GMainContext *context;
4114 /* This should be thread-safe:
4116 * - if the source is currently being added to a context, that
4117 * context will be woken up anyway
4119 * - if the source is currently being destroyed, we simply need not
4122 * - the memory for the source will remain valid until after the
4123 * source finalize function was called (which would remove the
4124 * source from the global list which we are currently holding the
4127 * - the GMainContext will either be NULL or point to a live
4130 * - the GMainContext will remain valid since we hold the
4131 * main_context_list lock
4133 * Since we are holding a lot of locks here, don't try to enter any
4134 * more GMainContext functions for fear of dealock -- just hit the
4135 * GWakeup and run. Even if that's safe now, it could easily become
4136 * unsafe with some very minor changes in the future, and signal
4137 * handling is not the most well-tested codepath.
4139 G_LOCK(main_context_list);
4140 context = source->context;
4142 g_wakeup_signal (context->wakeup);
4143 G_UNLOCK(main_context_list);
4147 dispatch_unix_signals (void)
4151 /* clear this first incase another one arrives while we're processing */
4152 any_unix_signal_pending = FALSE;
4154 G_LOCK(unix_signal_lock);
4156 /* handle GChildWatchSource instances */
4157 if (unix_signal_pending[SIGCHLD])
4159 unix_signal_pending[SIGCHLD] = FALSE;
4161 /* The only way we can do this is to scan all of the children.
4163 * The docs promise that we will not reap children that we are not
4164 * explicitly watching, so that ties our hands from calling
4165 * waitpid(-1). We also can't use siginfo's si_pid field since if
4166 * multiple SIGCHLD arrive at the same time, one of them can be
4167 * dropped (since a given UNIX signal can only be pending once).
4169 for (node = unix_child_watches; node; node = node->next)
4171 GChildWatchSource *source = node->data;
4173 if (!source->child_exited)
4175 if (waitpid (source->pid, &source->child_status, WNOHANG) > 0)
4177 source->child_exited = TRUE;
4179 wake_source ((GSource *) source);
4185 /* handle GUnixSignalWatchSource instances */
4186 for (node = unix_signal_watches; node; node = node->next)
4188 GUnixSignalWatchSource *source = node->data;
4190 if (!source->pending)
4192 if (unix_signal_pending[source->signum])
4194 unix_signal_pending[source->signum] = FALSE;
4195 source->pending = TRUE;
4197 wake_source ((GSource *) source);
4202 G_UNLOCK(unix_signal_lock);
4206 g_child_watch_prepare (GSource *source,
4209 GChildWatchSource *child_watch_source;
4211 child_watch_source = (GChildWatchSource *) source;
4213 return child_watch_source->child_exited;
4217 g_child_watch_check (GSource *source)
4219 GChildWatchSource *child_watch_source;
4221 child_watch_source = (GChildWatchSource *) source;
4223 return child_watch_source->child_exited;
4227 g_unix_signal_watch_prepare (GSource *source,
4230 GUnixSignalWatchSource *unix_signal_source;
4232 unix_signal_source = (GUnixSignalWatchSource *) source;
4234 return unix_signal_source->pending;
4238 g_unix_signal_watch_check (GSource *source)
4240 GUnixSignalWatchSource *unix_signal_source;
4242 unix_signal_source = (GUnixSignalWatchSource *) source;
4244 return unix_signal_source->pending;
4248 g_unix_signal_watch_dispatch (GSource *source,
4249 GSourceFunc callback,
4252 GUnixSignalWatchSource *unix_signal_source;
4254 unix_signal_source = (GUnixSignalWatchSource *) source;
4258 g_warning ("Unix signal source dispatched without callback\n"
4259 "You must call g_source_set_callback().");
4263 (callback) (user_data);
4265 unix_signal_source->pending = FALSE;
4271 ensure_unix_signal_handler_installed_unlocked (int signum)
4273 static sigset_t installed_signal_mask;
4274 static gboolean initialized;
4275 struct sigaction action;
4279 sigemptyset (&installed_signal_mask);
4280 glib_get_worker_context ();
4284 if (sigismember (&installed_signal_mask, signum))
4287 sigaddset (&installed_signal_mask, signum);
4289 action.sa_handler = g_unix_signal_handler;
4290 sigemptyset (&action.sa_mask);
4291 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4292 sigaction (signum, &action, NULL);
4296 _g_main_create_unix_signal_watch (int signum)
4299 GUnixSignalWatchSource *unix_signal_source;
4301 source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
4302 unix_signal_source = (GUnixSignalWatchSource *) source;
4304 unix_signal_source->signum = signum;
4305 unix_signal_source->pending = FALSE;
4307 G_LOCK (unix_signal_lock);
4308 ensure_unix_signal_handler_installed_unlocked (signum);
4309 unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
4310 if (unix_signal_pending[signum])
4311 unix_signal_source->pending = TRUE;
4312 unix_signal_pending[signum] = FALSE;
4313 G_UNLOCK (unix_signal_lock);
4319 g_unix_signal_watch_finalize (GSource *source)
4321 G_LOCK (unix_signal_lock);
4322 unix_signal_watches = g_slist_remove (unix_signal_watches, source);
4323 G_UNLOCK (unix_signal_lock);
4326 #endif /* G_OS_WIN32 */
4329 g_child_watch_finalize (GSource *source)
4331 G_LOCK (unix_signal_lock);
4332 unix_child_watches = g_slist_remove (unix_child_watches, source);
4333 G_UNLOCK (unix_signal_lock);
4337 g_child_watch_dispatch (GSource *source,
4338 GSourceFunc callback,
4341 GChildWatchSource *child_watch_source;
4342 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
4344 child_watch_source = (GChildWatchSource *) source;
4348 g_warning ("Child watch source dispatched without callback\n"
4349 "You must call g_source_set_callback().");
4353 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
4355 /* We never keep a child watch source around as the child is gone */
4362 g_unix_signal_handler (int signum)
4364 unix_signal_pending[signum] = TRUE;
4365 any_unix_signal_pending = TRUE;
4367 g_wakeup_signal (glib_worker_context->wakeup);
4370 #endif /* !G_OS_WIN32 */
4373 * g_child_watch_source_new:
4374 * @pid: process to watch. On POSIX the pid of a child process. On
4375 * Windows a handle for a process (which doesn't have to be a child).
4377 * Creates a new child_watch source.
4379 * The source will not initially be associated with any #GMainContext
4380 * and must be added to one with g_source_attach() before it will be
4383 * Note that child watch sources can only be used in conjunction with
4384 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4387 * Note that on platforms where #GPid must be explicitly closed
4388 * (see g_spawn_close_pid()) @pid must not be closed while the
4389 * source is still active. Typically, you will want to call
4390 * g_spawn_close_pid() in the callback function for the source.
4392 * Note further that using g_child_watch_source_new() is not
4393 * compatible with calling <literal>waitpid(-1)</literal> in
4394 * the application. Calling waitpid() for individual pids will
4397 * Return value: the newly-created child watch source
4402 g_child_watch_source_new (GPid pid)
4404 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4405 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4407 child_watch_source->pid = pid;
4410 child_watch_source->poll.fd = (gintptr) pid;
4411 child_watch_source->poll.events = G_IO_IN;
4413 g_source_add_poll (source, &child_watch_source->poll);
4414 #else /* G_OS_WIN32 */
4415 G_LOCK (unix_signal_lock);
4416 ensure_unix_signal_handler_installed_unlocked (SIGCHLD);
4417 unix_child_watches = g_slist_prepend (unix_child_watches, child_watch_source);
4418 if (waitpid (pid, &child_watch_source->child_status, WNOHANG) > 0)
4419 child_watch_source->child_exited = TRUE;
4420 G_UNLOCK (unix_signal_lock);
4421 #endif /* G_OS_WIN32 */
4427 * g_child_watch_add_full:
4428 * @priority: the priority of the idle source. Typically this will be in the
4429 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4430 * @pid: process to watch. On POSIX the pid of a child process. On
4431 * Windows a handle for a process (which doesn't have to be a child).
4432 * @function: function to call
4433 * @data: data to pass to @function
4434 * @notify: function to call when the idle is removed, or %NULL
4436 * Sets a function to be called when the child indicated by @pid
4437 * exits, at the priority @priority.
4439 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4440 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4441 * the spawn function for the child watching to work.
4443 * Note that on platforms where #GPid must be explicitly closed
4444 * (see g_spawn_close_pid()) @pid must not be closed while the
4445 * source is still active. Typically, you will want to call
4446 * g_spawn_close_pid() in the callback function for the source.
4448 * GLib supports only a single callback per process id.
4450 * This internally creates a main loop source using
4451 * g_child_watch_source_new() and attaches it to the main loop context
4452 * using g_source_attach(). You can do these steps manually if you
4453 * need greater control.
4455 * Return value: the ID (greater than 0) of the event source.
4457 * Rename to: g_child_watch_add
4461 g_child_watch_add_full (gint priority,
4463 GChildWatchFunc function,
4465 GDestroyNotify notify)
4470 g_return_val_if_fail (function != NULL, 0);
4472 source = g_child_watch_source_new (pid);
4474 if (priority != G_PRIORITY_DEFAULT)
4475 g_source_set_priority (source, priority);
4477 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4478 id = g_source_attach (source, NULL);
4479 g_source_unref (source);
4485 * g_child_watch_add:
4486 * @pid: process id to watch. On POSIX the pid of a child process. On
4487 * Windows a handle for a process (which doesn't have to be a child).
4488 * @function: function to call
4489 * @data: data to pass to @function
4491 * Sets a function to be called when the child indicated by @pid
4492 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4494 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4495 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4496 * the spawn function for the child watching to work.
4498 * Note that on platforms where #GPid must be explicitly closed
4499 * (see g_spawn_close_pid()) @pid must not be closed while the
4500 * source is still active. Typically, you will want to call
4501 * g_spawn_close_pid() in the callback function for the source.
4503 * GLib supports only a single callback per process id.
4505 * This internally creates a main loop source using
4506 * g_child_watch_source_new() and attaches it to the main loop context
4507 * using g_source_attach(). You can do these steps manually if you
4508 * need greater control.
4510 * Return value: the ID (greater than 0) of the event source.
4515 g_child_watch_add (GPid pid,
4516 GChildWatchFunc function,
4519 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4523 /* Idle functions */
4526 g_idle_prepare (GSource *source,
4535 g_idle_check (GSource *source)
4541 g_idle_dispatch (GSource *source,
4542 GSourceFunc callback,
4547 g_warning ("Idle source dispatched without callback\n"
4548 "You must call g_source_set_callback().");
4552 return callback (user_data);
4556 * g_idle_source_new:
4558 * Creates a new idle source.
4560 * The source will not initially be associated with any #GMainContext
4561 * and must be added to one with g_source_attach() before it will be
4562 * executed. Note that the default priority for idle sources is
4563 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4564 * have a default priority of %G_PRIORITY_DEFAULT.
4566 * Return value: the newly-created idle source
4569 g_idle_source_new (void)
4573 source = g_source_new (&g_idle_funcs, sizeof (GSource));
4574 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4581 * @priority: the priority of the idle source. Typically this will be in the
4582 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4583 * @function: function to call
4584 * @data: data to pass to @function
4585 * @notify: function to call when the idle is removed, or %NULL
4587 * Adds a function to be called whenever there are no higher priority
4588 * events pending. If the function returns %FALSE it is automatically
4589 * removed from the list of event sources and will not be called again.
4591 * This internally creates a main loop source using g_idle_source_new()
4592 * and attaches it to the main loop context using g_source_attach().
4593 * You can do these steps manually if you need greater control.
4595 * Return value: the ID (greater than 0) of the event source.
4596 * Rename to: g_idle_add
4599 g_idle_add_full (gint priority,
4600 GSourceFunc function,
4602 GDestroyNotify notify)
4607 g_return_val_if_fail (function != NULL, 0);
4609 source = g_idle_source_new ();
4611 if (priority != G_PRIORITY_DEFAULT_IDLE)
4612 g_source_set_priority (source, priority);
4614 g_source_set_callback (source, function, data, notify);
4615 id = g_source_attach (source, NULL);
4616 g_source_unref (source);
4623 * @function: function to call
4624 * @data: data to pass to @function.
4626 * Adds a function to be called whenever there are no higher priority
4627 * events pending to the default main loop. The function is given the
4628 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4629 * returns %FALSE it is automatically removed from the list of event
4630 * sources and will not be called again.
4632 * This internally creates a main loop source using g_idle_source_new()
4633 * and attaches it to the main loop context using g_source_attach().
4634 * You can do these steps manually if you need greater control.
4636 * Return value: the ID (greater than 0) of the event source.
4639 g_idle_add (GSourceFunc function,
4642 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4646 * g_idle_remove_by_data:
4647 * @data: the data for the idle source's callback.
4649 * Removes the idle function with the given data.
4651 * Return value: %TRUE if an idle source was found and removed.
4654 g_idle_remove_by_data (gpointer data)
4656 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4660 * g_main_context_invoke:
4661 * @context: (allow-none): a #GMainContext, or %NULL
4662 * @function: function to call
4663 * @data: data to pass to @function
4665 * Invokes a function in such a way that @context is owned during the
4666 * invocation of @function.
4668 * If @context is %NULL then the global default main context — as
4669 * returned by g_main_context_default() — is used.
4671 * If @context is owned by the current thread, @function is called
4672 * directly. Otherwise, if @context is the thread-default main context
4673 * of the current thread and g_main_context_acquire() succeeds, then
4674 * @function is called and g_main_context_release() is called
4677 * In any other case, an idle source is created to call @function and
4678 * that source is attached to @context (presumably to be run in another
4679 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
4680 * priority. If you want a different priority, use
4681 * g_main_context_invoke_full().
4683 * Note that, as with normal idle functions, @function should probably
4684 * return %FALSE. If it returns %TRUE, it will be continuously run in a
4685 * loop (and may prevent this call from returning).
4690 g_main_context_invoke (GMainContext *context,
4691 GSourceFunc function,
4694 g_main_context_invoke_full (context,
4696 function, data, NULL);
4700 * g_main_context_invoke_full:
4701 * @context: (allow-none): a #GMainContext, or %NULL
4702 * @priority: the priority at which to run @function
4703 * @function: function to call
4704 * @data: data to pass to @function
4705 * @notify: a function to call when @data is no longer in use, or %NULL.
4707 * Invokes a function in such a way that @context is owned during the
4708 * invocation of @function.
4710 * This function is the same as g_main_context_invoke() except that it
4711 * lets you specify the priority incase @function ends up being
4712 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
4714 * @notify should not assume that it is called from any particular
4715 * thread or with any particular context acquired.
4720 g_main_context_invoke_full (GMainContext *context,
4722 GSourceFunc function,
4724 GDestroyNotify notify)
4726 g_return_if_fail (function != NULL);
4729 context = g_main_context_default ();
4731 if (g_main_context_is_owner (context))
4733 while (function (data));
4740 GMainContext *thread_default;
4742 thread_default = g_main_context_get_thread_default ();
4744 if (!thread_default)
4745 thread_default = g_main_context_default ();
4747 if (thread_default == context && g_main_context_acquire (context))
4749 while (function (data));
4751 g_main_context_release (context);
4760 source = g_idle_source_new ();
4761 g_source_set_priority (source, priority);
4762 g_source_set_callback (source, function, data, notify);
4763 g_source_attach (source, context);
4764 g_source_unref (source);
4770 glib_worker_main (gpointer data)
4774 g_main_context_iteration (glib_worker_context, TRUE);
4776 if (any_unix_signal_pending)
4777 dispatch_unix_signals ();
4780 return NULL; /* worst GCC warning message ever... */
4784 glib_get_worker_context (void)
4786 static gsize initialised;
4788 g_thread_init_glib ();
4790 if (g_once_init_enter (&initialised))
4792 GError *error = NULL;
4794 glib_worker_context = g_main_context_new ();
4795 if (g_thread_create (glib_worker_main, NULL, FALSE, &error) == NULL)
4796 g_error ("Creating GLib worker thread failed: %s\n", error->message);
4798 g_once_init_leave (&initialised, TRUE);
4801 return glib_worker_context;