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"
54 #include <sys/eventfd.h>
59 #include <sys/types.h>
62 #ifdef HAVE_SYS_TIME_H
64 #endif /* HAVE_SYS_TIME_H */
67 #endif /* HAVE_UNISTD_H */
74 #endif /* G_OS_WIN32 */
77 #include <sys/socket.h>
79 #endif /* G_OS_BEOS */
84 #include "giochannel.h"
88 #include "gstrfuncs.h"
89 #include "gtestutils.h"
95 #ifdef G_MAIN_POLL_DEBUG
101 #include "glib-private.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>
178 * On Unix, the GLib mainloop is incompatible with fork(). Any program
179 * using the mainloop must either exec() or exit() from the child
180 * without returning to the mainloop.
185 typedef struct _GTimeoutSource GTimeoutSource
;
186 typedef struct _GChildWatchSource GChildWatchSource
;
187 typedef struct _GUnixSignalWatchSource GUnixSignalWatchSource
;
188 typedef struct _GPollRec GPollRec
;
189 typedef struct _GSourceCallback GSourceCallback
;
193 G_SOURCE_READY
= 1 << G_HOOK_FLAG_USER_SHIFT
,
194 G_SOURCE_CAN_RECURSE
= 1 << (G_HOOK_FLAG_USER_SHIFT
+ 1)
197 typedef struct _GMainWaiter GMainWaiter
;
205 typedef struct _GMainDispatch GMainDispatch
;
207 struct _GMainDispatch
210 GSList
*dispatching_sources
; /* stack of current sources */
213 #ifdef G_MAIN_POLL_DEBUG
214 gboolean _g_main_poll_debug
= FALSE
;
219 /* The following lock is used for both the list of sources
220 * and the list of poll records
230 GPtrArray
*pending_dispatches
;
231 gint timeout
; /* Timeout for current iteration */
234 GSource
*source_list
;
235 gint in_check_or_prepare
;
237 GPollRec
*poll_records
, *poll_records_tail
;
238 guint n_poll_records
;
239 GPollFD
*cached_poll_array
;
240 guint cached_poll_array_size
;
246 /* Flag indicating whether the set of fd's changed during a poll */
247 gboolean poll_changed
;
252 gboolean time_is_fresh
;
255 struct _GSourceCallback
260 GDestroyNotify notify
;
265 GMainContext
*context
;
270 struct _GTimeoutSource
278 struct _GChildWatchSource
285 #else /* G_OS_WIN32 */
286 gboolean child_exited
;
287 #endif /* G_OS_WIN32 */
290 struct _GUnixSignalWatchSource
305 struct _GSourcePrivate
307 GSList
*child_sources
;
308 GSource
*parent_source
;
311 #define LOCK_CONTEXT(context) g_mutex_lock (&context->mutex)
312 #define UNLOCK_CONTEXT(context) g_mutex_unlock (&context->mutex)
313 #define G_THREAD_SELF g_thread_self ()
315 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
316 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
317 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
319 #define SOURCE_UNREF(source, context) \
321 if ((source)->ref_count > 1) \
322 (source)->ref_count--; \
324 g_source_unref_internal ((source), (context), TRUE); \
328 /* Forward declarations */
330 static void g_source_unref_internal (GSource
*source
,
331 GMainContext
*context
,
333 static void g_source_destroy_internal (GSource
*source
,
334 GMainContext
*context
,
336 static void g_source_set_priority_unlocked (GSource
*source
,
337 GMainContext
*context
,
339 static void g_main_context_poll (GMainContext
*context
,
344 static void g_main_context_add_poll_unlocked (GMainContext
*context
,
347 static void g_main_context_remove_poll_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
;
381 static gboolean g_main_context_fork_detected
;
383 G_LOCK_DEFINE_STATIC (main_loop
);
384 static GMainContext
*default_main_context
;
389 /* UNIX signals work by marking one of these variables then waking the
390 * worker context to check on them and dispatch accordingly.
392 static volatile gchar unix_signal_pending
[NSIG
];
393 static volatile gboolean any_unix_signal_pending
;
395 /* Guards all the data below */
396 G_LOCK_DEFINE_STATIC (unix_signal_lock
);
397 static GSList
*unix_signal_watches
;
398 static GSList
*unix_child_watches
;
400 static GSourceFuncs g_unix_signal_funcs
=
402 g_unix_signal_watch_prepare
,
403 g_unix_signal_watch_check
,
404 g_unix_signal_watch_dispatch
,
405 g_unix_signal_watch_finalize
407 #endif /* !G_OS_WIN32 */
408 G_LOCK_DEFINE_STATIC (main_context_list
);
409 static GSList
*main_context_list
= NULL
;
411 GSourceFuncs g_timeout_funcs
=
419 GSourceFuncs g_child_watch_funcs
=
421 g_child_watch_prepare
,
423 g_child_watch_dispatch
,
424 g_child_watch_finalize
427 GSourceFuncs g_idle_funcs
=
436 * g_main_context_ref:
437 * @context: a #GMainContext
439 * Increases the reference count on a #GMainContext object by one.
441 * Returns: the @context that was passed in (since 2.6)
444 g_main_context_ref (GMainContext
*context
)
446 g_return_val_if_fail (context
!= NULL
, NULL
);
447 g_return_val_if_fail (g_atomic_int_get (&context
->ref_count
) > 0, NULL
);
449 g_atomic_int_inc (&context
->ref_count
);
455 poll_rec_list_free (GMainContext
*context
,
458 g_slice_free_chain (GPollRec
, list
, next
);
462 * g_main_context_unref:
463 * @context: a #GMainContext
465 * Decreases the reference count on a #GMainContext object by one. If
466 * the result is zero, free the context and free all associated memory.
469 g_main_context_unref (GMainContext
*context
)
472 g_return_if_fail (context
!= NULL
);
473 g_return_if_fail (g_atomic_int_get (&context
->ref_count
) > 0);
475 if (!g_atomic_int_dec_and_test (&context
->ref_count
))
478 G_LOCK (main_context_list
);
479 main_context_list
= g_slist_remove (main_context_list
, context
);
480 G_UNLOCK (main_context_list
);
482 source
= context
->source_list
;
485 GSource
*next
= source
->next
;
486 g_source_destroy_internal (source
, context
, FALSE
);
490 g_mutex_clear (&context
->mutex
);
492 g_ptr_array_free (context
->pending_dispatches
, TRUE
);
493 g_free (context
->cached_poll_array
);
495 poll_rec_list_free (context
, context
->poll_records
);
497 g_wakeup_free (context
->wakeup
);
498 g_cond_clear (&context
->cond
);
505 g_main_context_forked (void)
507 g_main_context_fork_detected
= TRUE
;
512 * g_main_context_new:
514 * Creates a new #GMainContext structure.
516 * Return value: the new #GMainContext
519 g_main_context_new (void)
521 static gsize initialised
;
522 GMainContext
*context
;
524 if (g_once_init_enter (&initialised
))
526 #ifdef G_MAIN_POLL_DEBUG
527 if (getenv ("G_MAIN_POLL_DEBUG") != NULL
)
528 _g_main_poll_debug
= TRUE
;
532 pthread_atfork (NULL
, NULL
, g_main_context_forked
);
535 g_once_init_leave (&initialised
, TRUE
);
538 context
= g_new0 (GMainContext
, 1);
540 g_mutex_init (&context
->mutex
);
541 g_cond_init (&context
->cond
);
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
;
561 context
->wakeup
= g_wakeup_new ();
562 g_wakeup_get_pollfd (context
->wakeup
, &context
->wake_up_rec
);
563 g_main_context_add_poll_unlocked (context
, 0, &context
->wake_up_rec
);
565 G_LOCK (main_context_list
);
566 main_context_list
= g_slist_append (main_context_list
, context
);
568 #ifdef G_MAIN_POLL_DEBUG
569 if (_g_main_poll_debug
)
570 g_print ("created context=%p\n", context
);
573 G_UNLOCK (main_context_list
);
579 * g_main_context_default:
581 * Returns the global default main context. This is the main context
582 * used for main loop functions when a main loop is not explicitly
583 * specified, and corresponds to the "main" main loop. See also
584 * g_main_context_get_thread_default().
586 * Return value: (transfer none): the global default main context.
589 g_main_context_default (void)
595 if (!default_main_context
)
597 default_main_context
= g_main_context_new ();
598 #ifdef G_MAIN_POLL_DEBUG
599 if (_g_main_poll_debug
)
600 g_print ("default context=%p\n", default_main_context
);
604 G_UNLOCK (main_loop
);
606 return default_main_context
;
610 free_context_stack (gpointer data
)
612 GQueue
*stack
= data
;
613 GMainContext
*context
;
615 while (!g_queue_is_empty (stack
))
617 context
= g_queue_pop_head (stack
);
618 g_main_context_release (context
);
620 g_main_context_unref (context
);
622 g_queue_free (stack
);
625 static GPrivate thread_context_stack
= G_PRIVATE_INIT (free_context_stack
);
628 * g_main_context_push_thread_default:
629 * @context: a #GMainContext, or %NULL for the global default context
631 * Acquires @context and sets it as the thread-default context for the
632 * current thread. This will cause certain asynchronous operations
633 * (such as most <link linkend="gio">gio</link>-based I/O) which are
634 * started in this thread to run under @context and deliver their
635 * results to its main loop, rather than running under the global
636 * default context in the main thread. Note that calling this function
637 * changes the context returned by
638 * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
639 * one returned by g_main_context_default(), so it does not affect the
640 * context used by functions like g_idle_add().
642 * Normally you would call this function shortly after creating a new
643 * thread, passing it a #GMainContext which will be run by a
644 * #GMainLoop in that thread, to set a new default context for all
645 * async operations in that thread. (In this case, you don't need to
646 * ever call g_main_context_pop_thread_default().) In some cases
647 * however, you may want to schedule a single operation in a
648 * non-default context, or temporarily use a non-default context in
649 * the main thread. In that case, you can wrap the call to the
650 * asynchronous operation inside a
651 * g_main_context_push_thread_default() /
652 * g_main_context_pop_thread_default() pair, but it is up to you to
653 * ensure that no other asynchronous operations accidentally get
654 * started while the non-default context is active.
656 * Beware that libraries that predate this function may not correctly
657 * handle being used from a thread with a thread-default context. Eg,
658 * see g_file_supports_thread_contexts().
663 g_main_context_push_thread_default (GMainContext
*context
)
666 gboolean acquired_context
;
668 acquired_context
= g_main_context_acquire (context
);
669 g_return_if_fail (acquired_context
);
671 if (context
== g_main_context_default ())
674 g_main_context_ref (context
);
676 stack
= g_private_get (&thread_context_stack
);
679 stack
= g_queue_new ();
680 g_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_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 or
721 * g_main_context_ref_thread_default() to get a #GMainContext to add
722 * their #GSource<!-- -->s to. (Note that even in single-threaded
723 * programs applications may sometimes want to temporarily push a
724 * non-default context, so it is not safe to assume that this will
725 * always return %NULL if you are running in the default thread.)
727 * If you need to hold a reference on the context, use
728 * g_main_context_ref_thread_default() instead.
730 * Returns: (transfer none): the thread-default #GMainContext, or
731 * %NULL if the thread-default context is the global default context.
736 g_main_context_get_thread_default (void)
740 stack
= g_private_get (&thread_context_stack
);
742 return g_queue_peek_head (stack
);
748 * g_main_context_ref_thread_default:
750 * Gets the thread-default #GMainContext for this thread, as with
751 * g_main_context_get_thread_default(), but also adds a reference to
752 * it with g_main_context_ref(). In addition, unlike
753 * g_main_context_get_thread_default(), if the thread-default context
754 * is the global default context, this will return that #GMainContext
755 * (with a ref added to it) rather than returning %NULL.
757 * Returns: (transfer full): the thread-default #GMainContext. Unref
758 * with g_main_context_unref() when you are done with it.
763 g_main_context_ref_thread_default (void)
765 GMainContext
*context
;
767 context
= g_main_context_get_thread_default ();
769 context
= g_main_context_default ();
770 return g_main_context_ref (context
);
773 /* Hooks for adding to the main loop */
777 * @source_funcs: structure containing functions that implement
778 * the sources behavior.
779 * @struct_size: size of the #GSource structure to create.
781 * Creates a new #GSource structure. The size is specified to
782 * allow creating structures derived from #GSource that contain
783 * additional data. The size passed in must be at least
784 * <literal>sizeof (GSource)</literal>.
786 * The source will not initially be associated with any #GMainContext
787 * and must be added to one with g_source_attach() before it will be
790 * Return value: the newly-created #GSource.
793 g_source_new (GSourceFuncs
*source_funcs
,
798 g_return_val_if_fail (source_funcs
!= NULL
, NULL
);
799 g_return_val_if_fail (struct_size
>= sizeof (GSource
), NULL
);
801 source
= (GSource
*) g_malloc0 (struct_size
);
803 source
->source_funcs
= source_funcs
;
804 source
->ref_count
= 1;
806 source
->priority
= G_PRIORITY_DEFAULT
;
808 source
->flags
= G_HOOK_FLAG_ACTIVE
;
810 /* NULL/0 initialization for all other fields */
815 /* Holds context's lock
818 g_source_list_add (GSource
*source
,
819 GMainContext
*context
)
821 GSource
*tmp_source
, *last_source
;
823 if (source
->priv
&& source
->priv
->parent_source
)
825 /* Put the source immediately before its parent */
826 tmp_source
= source
->priv
->parent_source
;
827 last_source
= source
->priv
->parent_source
->prev
;
832 tmp_source
= context
->source_list
;
833 while (tmp_source
&& tmp_source
->priority
<= source
->priority
)
835 last_source
= tmp_source
;
836 tmp_source
= tmp_source
->next
;
840 source
->next
= tmp_source
;
842 tmp_source
->prev
= source
;
844 source
->prev
= last_source
;
846 last_source
->next
= source
;
848 context
->source_list
= source
;
851 /* Holds context's lock
854 g_source_list_remove (GSource
*source
,
855 GMainContext
*context
)
858 source
->prev
->next
= source
->next
;
860 context
->source_list
= source
->next
;
863 source
->next
->prev
= source
->prev
;
870 g_source_attach_unlocked (GSource
*source
,
871 GMainContext
*context
)
876 source
->context
= context
;
877 result
= source
->source_id
= context
->next_id
++;
880 g_source_list_add (source
, context
);
882 tmp_list
= source
->poll_fds
;
885 g_main_context_add_poll_unlocked (context
, source
->priority
, tmp_list
->data
);
886 tmp_list
= tmp_list
->next
;
891 tmp_list
= source
->priv
->child_sources
;
894 g_source_attach_unlocked (tmp_list
->data
, context
);
895 tmp_list
= tmp_list
->next
;
904 * @source: a #GSource
905 * @context: a #GMainContext (if %NULL, the default context will be used)
907 * Adds a #GSource to a @context so that it will be executed within
908 * that context. Remove it by calling g_source_destroy().
910 * Return value: the ID (greater than 0) for the source within the
914 g_source_attach (GSource
*source
,
915 GMainContext
*context
)
919 g_return_val_if_fail (source
->context
== NULL
, 0);
920 g_return_val_if_fail (!SOURCE_DESTROYED (source
), 0);
923 context
= g_main_context_default ();
925 LOCK_CONTEXT (context
);
927 result
= g_source_attach_unlocked (source
, context
);
929 /* If another thread has acquired the context, wake it up since it
930 * might be in poll() right now.
932 if (context
->owner
&& context
->owner
!= G_THREAD_SELF
)
933 g_wakeup_signal (context
->wakeup
);
935 UNLOCK_CONTEXT (context
);
941 g_source_destroy_internal (GSource
*source
,
942 GMainContext
*context
,
946 LOCK_CONTEXT (context
);
948 if (!SOURCE_DESTROYED (source
))
951 gpointer old_cb_data
;
952 GSourceCallbackFuncs
*old_cb_funcs
;
954 source
->flags
&= ~G_HOOK_FLAG_ACTIVE
;
956 old_cb_data
= source
->callback_data
;
957 old_cb_funcs
= source
->callback_funcs
;
959 source
->callback_data
= NULL
;
960 source
->callback_funcs
= NULL
;
964 UNLOCK_CONTEXT (context
);
965 old_cb_funcs
->unref (old_cb_data
);
966 LOCK_CONTEXT (context
);
969 if (!SOURCE_BLOCKED (source
))
971 tmp_list
= source
->poll_fds
;
974 g_main_context_remove_poll_unlocked (context
, tmp_list
->data
);
975 tmp_list
= tmp_list
->next
;
979 if (source
->priv
&& source
->priv
->child_sources
)
981 /* This is safe because even if a child_source finalizer or
982 * closure notify tried to modify source->priv->child_sources
983 * from outside the lock, it would fail since
984 * SOURCE_DESTROYED(source) is now TRUE.
986 tmp_list
= source
->priv
->child_sources
;
989 g_source_destroy_internal (tmp_list
->data
, context
, TRUE
);
990 g_source_unref_internal (tmp_list
->data
, context
, TRUE
);
991 tmp_list
= tmp_list
->next
;
993 g_slist_free (source
->priv
->child_sources
);
994 source
->priv
->child_sources
= NULL
;
997 g_source_unref_internal (source
, context
, TRUE
);
1001 UNLOCK_CONTEXT (context
);
1006 * @source: a #GSource
1008 * Removes a source from its #GMainContext, if any, and mark it as
1009 * destroyed. The source cannot be subsequently added to another
1013 g_source_destroy (GSource
*source
)
1015 GMainContext
*context
;
1017 g_return_if_fail (source
!= NULL
);
1019 context
= source
->context
;
1022 g_source_destroy_internal (source
, context
, FALSE
);
1024 source
->flags
&= ~G_HOOK_FLAG_ACTIVE
;
1029 * @source: a #GSource
1031 * Returns the numeric ID for a particular source. The ID of a source
1032 * is a positive integer which is unique within a particular main loop
1033 * context. The reverse
1034 * mapping from ID to source is done by g_main_context_find_source_by_id().
1036 * Return value: the ID (greater than 0) for the source
1039 g_source_get_id (GSource
*source
)
1043 g_return_val_if_fail (source
!= NULL
, 0);
1044 g_return_val_if_fail (source
->context
!= NULL
, 0);
1046 LOCK_CONTEXT (source
->context
);
1047 result
= source
->source_id
;
1048 UNLOCK_CONTEXT (source
->context
);
1054 * g_source_get_context:
1055 * @source: a #GSource
1057 * Gets the #GMainContext with which the source is associated.
1058 * Calling this function on a destroyed source is an error.
1060 * Return value: (transfer none): the #GMainContext with which the
1061 * source is associated, or %NULL if the context has not
1062 * yet been added to a source.
1065 g_source_get_context (GSource
*source
)
1067 g_return_val_if_fail (!SOURCE_DESTROYED (source
), NULL
);
1069 return source
->context
;
1073 * g_source_add_poll:
1074 * @source:a #GSource
1075 * @fd: a #GPollFD structure holding information about a file
1076 * descriptor to watch.
1078 * Adds a file descriptor to the set of file descriptors polled for
1079 * this source. This is usually combined with g_source_new() to add an
1080 * event source. The event source's check function will typically test
1081 * the @revents field in the #GPollFD struct and return %TRUE if events need
1085 g_source_add_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_prepend (source
->poll_fds
, fd
);
1103 if (!SOURCE_BLOCKED (source
))
1104 g_main_context_add_poll_unlocked (context
, source
->priority
, fd
);
1105 UNLOCK_CONTEXT (context
);
1110 * g_source_remove_poll:
1111 * @source:a #GSource
1112 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1114 * Removes a file descriptor from the set of file descriptors polled for
1118 g_source_remove_poll (GSource
*source
,
1121 GMainContext
*context
;
1123 g_return_if_fail (source
!= NULL
);
1124 g_return_if_fail (fd
!= NULL
);
1125 g_return_if_fail (!SOURCE_DESTROYED (source
));
1127 context
= source
->context
;
1130 LOCK_CONTEXT (context
);
1132 source
->poll_fds
= g_slist_remove (source
->poll_fds
, fd
);
1136 if (!SOURCE_BLOCKED (source
))
1137 g_main_context_remove_poll_unlocked (context
, fd
);
1138 UNLOCK_CONTEXT (context
);
1143 * g_source_add_child_source:
1144 * @source:a #GSource
1145 * @child_source: a second #GSource that @source should "poll"
1147 * Adds @child_source to @source as a "polled" source; when @source is
1148 * added to a #GMainContext, @child_source will be automatically added
1149 * with the same priority, when @child_source is triggered, it will
1150 * cause @source to dispatch (in addition to calling its own
1151 * callback), and when @source is destroyed, it will destroy
1152 * @child_source as well. (@source will also still be dispatched if
1153 * its own prepare/check functions indicate that it is ready.)
1155 * If you don't need @child_source to do anything on its own when it
1156 * triggers, you can call g_source_set_dummy_callback() on it to set a
1157 * callback that does nothing (except return %TRUE if appropriate).
1159 * @source will hold a reference on @child_source while @child_source
1160 * is attached to it.
1165 g_source_add_child_source (GSource
*source
,
1166 GSource
*child_source
)
1168 GMainContext
*context
;
1170 g_return_if_fail (source
!= NULL
);
1171 g_return_if_fail (child_source
!= NULL
);
1172 g_return_if_fail (!SOURCE_DESTROYED (source
));
1173 g_return_if_fail (!SOURCE_DESTROYED (child_source
));
1174 g_return_if_fail (child_source
->context
== NULL
);
1175 g_return_if_fail (child_source
->priv
== NULL
|| child_source
->priv
->parent_source
== NULL
);
1177 context
= source
->context
;
1180 LOCK_CONTEXT (context
);
1183 source
->priv
= g_slice_new0 (GSourcePrivate
);
1184 if (!child_source
->priv
)
1185 child_source
->priv
= g_slice_new0 (GSourcePrivate
);
1187 source
->priv
->child_sources
= g_slist_prepend (source
->priv
->child_sources
,
1188 g_source_ref (child_source
));
1189 child_source
->priv
->parent_source
= source
;
1190 g_source_set_priority_unlocked (child_source
, context
, source
->priority
);
1194 UNLOCK_CONTEXT (context
);
1195 g_source_attach (child_source
, context
);
1200 * g_source_remove_child_source:
1201 * @source:a #GSource
1202 * @child_source: a #GSource previously passed to
1203 * g_source_add_child_source().
1205 * Detaches @child_source from @source and destroys it.
1210 g_source_remove_child_source (GSource
*source
,
1211 GSource
*child_source
)
1213 GMainContext
*context
;
1215 g_return_if_fail (source
!= NULL
);
1216 g_return_if_fail (child_source
!= NULL
);
1217 g_return_if_fail (child_source
->priv
!= NULL
&& child_source
->priv
->parent_source
== source
);
1218 g_return_if_fail (!SOURCE_DESTROYED (source
));
1219 g_return_if_fail (!SOURCE_DESTROYED (child_source
));
1221 context
= source
->context
;
1224 LOCK_CONTEXT (context
);
1226 source
->priv
->child_sources
= g_slist_remove (source
->priv
->child_sources
, child_source
);
1227 g_source_destroy_internal (child_source
, context
, TRUE
);
1228 g_source_unref_internal (child_source
, context
, TRUE
);
1231 UNLOCK_CONTEXT (context
);
1235 * g_source_set_callback_indirect:
1236 * @source: the source
1237 * @callback_data: pointer to callback data "object"
1238 * @callback_funcs: functions for reference counting @callback_data
1239 * and getting the callback and data
1241 * Sets the callback function storing the data as a refcounted callback
1242 * "object". This is used internally. Note that calling
1243 * g_source_set_callback_indirect() assumes
1244 * an initial reference count on @callback_data, and thus
1245 * @callback_funcs->unref will eventually be called once more
1246 * than @callback_funcs->ref.
1249 g_source_set_callback_indirect (GSource
*source
,
1250 gpointer callback_data
,
1251 GSourceCallbackFuncs
*callback_funcs
)
1253 GMainContext
*context
;
1254 gpointer old_cb_data
;
1255 GSourceCallbackFuncs
*old_cb_funcs
;
1257 g_return_if_fail (source
!= NULL
);
1258 g_return_if_fail (callback_funcs
!= NULL
|| callback_data
== NULL
);
1260 context
= source
->context
;
1263 LOCK_CONTEXT (context
);
1265 old_cb_data
= source
->callback_data
;
1266 old_cb_funcs
= source
->callback_funcs
;
1268 source
->callback_data
= callback_data
;
1269 source
->callback_funcs
= callback_funcs
;
1272 UNLOCK_CONTEXT (context
);
1275 old_cb_funcs
->unref (old_cb_data
);
1279 g_source_callback_ref (gpointer cb_data
)
1281 GSourceCallback
*callback
= cb_data
;
1283 callback
->ref_count
++;
1288 g_source_callback_unref (gpointer cb_data
)
1290 GSourceCallback
*callback
= cb_data
;
1292 callback
->ref_count
--;
1293 if (callback
->ref_count
== 0)
1295 if (callback
->notify
)
1296 callback
->notify (callback
->data
);
1302 g_source_callback_get (gpointer cb_data
,
1307 GSourceCallback
*callback
= cb_data
;
1309 *func
= callback
->func
;
1310 *data
= callback
->data
;
1313 static GSourceCallbackFuncs g_source_callback_funcs
= {
1314 g_source_callback_ref
,
1315 g_source_callback_unref
,
1316 g_source_callback_get
,
1320 * g_source_set_callback:
1321 * @source: the source
1322 * @func: a callback function
1323 * @data: the data to pass to callback function
1324 * @notify: a function to call when @data is no longer in use, or %NULL.
1326 * Sets the callback function for a source. The callback for a source is
1327 * called from the source's dispatch function.
1329 * The exact type of @func depends on the type of source; ie. you
1330 * should not count on @func being called with @data as its first
1333 * Typically, you won't use this function. Instead use functions specific
1334 * to the type of source you are using.
1337 g_source_set_callback (GSource
*source
,
1340 GDestroyNotify notify
)
1342 GSourceCallback
*new_callback
;
1344 g_return_if_fail (source
!= NULL
);
1346 new_callback
= g_new (GSourceCallback
, 1);
1348 new_callback
->ref_count
= 1;
1349 new_callback
->func
= func
;
1350 new_callback
->data
= data
;
1351 new_callback
->notify
= notify
;
1353 g_source_set_callback_indirect (source
, new_callback
, &g_source_callback_funcs
);
1358 * g_source_set_funcs:
1359 * @source: a #GSource
1360 * @funcs: the new #GSourceFuncs
1362 * Sets the source functions (can be used to override
1363 * default implementations) of an unattached source.
1368 g_source_set_funcs (GSource
*source
,
1369 GSourceFuncs
*funcs
)
1371 g_return_if_fail (source
!= NULL
);
1372 g_return_if_fail (source
->context
== NULL
);
1373 g_return_if_fail (source
->ref_count
> 0);
1374 g_return_if_fail (funcs
!= NULL
);
1376 source
->source_funcs
= funcs
;
1380 g_source_set_priority_unlocked (GSource
*source
,
1381 GMainContext
*context
,
1386 source
->priority
= priority
;
1390 /* Remove the source from the context's source and then
1391 * add it back so it is sorted in the correct place
1393 g_source_list_remove (source
, source
->context
);
1394 g_source_list_add (source
, source
->context
);
1396 if (!SOURCE_BLOCKED (source
))
1398 tmp_list
= source
->poll_fds
;
1401 g_main_context_remove_poll_unlocked (context
, tmp_list
->data
);
1402 g_main_context_add_poll_unlocked (context
, priority
, tmp_list
->data
);
1404 tmp_list
= tmp_list
->next
;
1409 if (source
->priv
&& source
->priv
->child_sources
)
1411 tmp_list
= source
->priv
->child_sources
;
1414 g_source_set_priority_unlocked (tmp_list
->data
, context
, priority
);
1415 tmp_list
= tmp_list
->next
;
1421 * g_source_set_priority:
1422 * @source: a #GSource
1423 * @priority: the new priority.
1425 * Sets the priority of a source. While the main loop is being run, a
1426 * source will be dispatched if it is ready to be dispatched and no
1427 * sources at a higher (numerically smaller) priority are ready to be
1431 g_source_set_priority (GSource
*source
,
1434 GMainContext
*context
;
1436 g_return_if_fail (source
!= NULL
);
1438 context
= source
->context
;
1441 LOCK_CONTEXT (context
);
1442 g_source_set_priority_unlocked (source
, context
, priority
);
1444 UNLOCK_CONTEXT (source
->context
);
1448 * g_source_get_priority:
1449 * @source: a #GSource
1451 * Gets the priority of a source.
1453 * Return value: the priority of the source
1456 g_source_get_priority (GSource
*source
)
1458 g_return_val_if_fail (source
!= NULL
, 0);
1460 return source
->priority
;
1464 * g_source_set_can_recurse:
1465 * @source: a #GSource
1466 * @can_recurse: whether recursion is allowed for this source
1468 * Sets whether a source can be called recursively. If @can_recurse is
1469 * %TRUE, then while the source is being dispatched then this source
1470 * will be processed normally. Otherwise, all processing of this
1471 * source is blocked until the dispatch function returns.
1474 g_source_set_can_recurse (GSource
*source
,
1475 gboolean can_recurse
)
1477 GMainContext
*context
;
1479 g_return_if_fail (source
!= NULL
);
1481 context
= source
->context
;
1484 LOCK_CONTEXT (context
);
1487 source
->flags
|= G_SOURCE_CAN_RECURSE
;
1489 source
->flags
&= ~G_SOURCE_CAN_RECURSE
;
1492 UNLOCK_CONTEXT (context
);
1496 * g_source_get_can_recurse:
1497 * @source: a #GSource
1499 * Checks whether a source is allowed to be called recursively.
1500 * see g_source_set_can_recurse().
1502 * Return value: whether recursion is allowed.
1505 g_source_get_can_recurse (GSource
*source
)
1507 g_return_val_if_fail (source
!= NULL
, FALSE
);
1509 return (source
->flags
& G_SOURCE_CAN_RECURSE
) != 0;
1514 * g_source_set_name:
1515 * @source: a #GSource
1516 * @name: debug name for the source
1518 * Sets a name for the source, used in debugging and profiling.
1519 * The name defaults to #NULL.
1521 * The source name should describe in a human-readable way
1522 * what the source does. For example, "X11 event queue"
1523 * or "GTK+ repaint idle handler" or whatever it is.
1525 * It is permitted to call this function multiple times, but is not
1526 * recommended due to the potential performance impact. For example,
1527 * one could change the name in the "check" function of a #GSourceFuncs
1528 * to include details like the event type in the source name.
1533 g_source_set_name (GSource
*source
,
1536 g_return_if_fail (source
!= NULL
);
1538 /* setting back to NULL is allowed, just because it's
1539 * weird if get_name can return NULL but you can't
1543 g_free (source
->name
);
1544 source
->name
= g_strdup (name
);
1548 * g_source_get_name:
1549 * @source: a #GSource
1551 * Gets a name for the source, used in debugging and profiling.
1552 * The name may be #NULL if it has never been set with
1553 * g_source_set_name().
1555 * Return value: the name of the source
1559 g_source_get_name (GSource
*source
)
1561 g_return_val_if_fail (source
!= NULL
, NULL
);
1563 return source
->name
;
1567 * g_source_set_name_by_id:
1568 * @tag: a #GSource ID
1569 * @name: debug name for the source
1571 * Sets the name of a source using its ID.
1573 * This is a convenience utility to set source names from the return
1574 * value of g_idle_add(), g_timeout_add(), etc.
1579 g_source_set_name_by_id (guint tag
,
1584 g_return_if_fail (tag
> 0);
1586 source
= g_main_context_find_source_by_id (NULL
, tag
);
1590 g_source_set_name (source
, name
);
1596 * @source: a #GSource
1598 * Increases the reference count on a source by one.
1600 * Return value: @source
1603 g_source_ref (GSource
*source
)
1605 GMainContext
*context
;
1607 g_return_val_if_fail (source
!= NULL
, NULL
);
1609 context
= source
->context
;
1612 LOCK_CONTEXT (context
);
1614 source
->ref_count
++;
1617 UNLOCK_CONTEXT (context
);
1622 /* g_source_unref() but possible to call within context lock
1625 g_source_unref_internal (GSource
*source
,
1626 GMainContext
*context
,
1629 gpointer old_cb_data
= NULL
;
1630 GSourceCallbackFuncs
*old_cb_funcs
= NULL
;
1632 g_return_if_fail (source
!= NULL
);
1634 if (!have_lock
&& context
)
1635 LOCK_CONTEXT (context
);
1637 source
->ref_count
--;
1638 if (source
->ref_count
== 0)
1640 old_cb_data
= source
->callback_data
;
1641 old_cb_funcs
= source
->callback_funcs
;
1643 source
->callback_data
= NULL
;
1644 source
->callback_funcs
= NULL
;
1648 if (!SOURCE_DESTROYED (source
))
1649 g_warning (G_STRLOC
": ref_count == 0, but source was still attached to a context!");
1650 g_source_list_remove (source
, context
);
1653 if (source
->source_funcs
->finalize
)
1656 UNLOCK_CONTEXT (context
);
1657 source
->source_funcs
->finalize (source
);
1659 LOCK_CONTEXT (context
);
1662 g_free (source
->name
);
1663 source
->name
= NULL
;
1665 g_slist_free (source
->poll_fds
);
1666 source
->poll_fds
= NULL
;
1670 g_slice_free (GSourcePrivate
, source
->priv
);
1671 source
->priv
= NULL
;
1677 if (!have_lock
&& context
)
1678 UNLOCK_CONTEXT (context
);
1683 UNLOCK_CONTEXT (context
);
1685 old_cb_funcs
->unref (old_cb_data
);
1688 LOCK_CONTEXT (context
);
1694 * @source: a #GSource
1696 * Decreases the reference count of a source by one. If the
1697 * resulting reference count is zero the source and associated
1698 * memory will be destroyed.
1701 g_source_unref (GSource
*source
)
1703 g_return_if_fail (source
!= NULL
);
1705 g_source_unref_internal (source
, source
->context
, FALSE
);
1709 * g_main_context_find_source_by_id:
1710 * @context: a #GMainContext (if %NULL, the default context will be used)
1711 * @source_id: the source ID, as returned by g_source_get_id().
1713 * Finds a #GSource given a pair of context and ID.
1715 * Return value: (transfer none): the #GSource if found, otherwise, %NULL
1718 g_main_context_find_source_by_id (GMainContext
*context
,
1723 g_return_val_if_fail (source_id
> 0, NULL
);
1725 if (context
== NULL
)
1726 context
= g_main_context_default ();
1728 LOCK_CONTEXT (context
);
1730 source
= context
->source_list
;
1733 if (!SOURCE_DESTROYED (source
) &&
1734 source
->source_id
== source_id
)
1736 source
= source
->next
;
1739 UNLOCK_CONTEXT (context
);
1745 * g_main_context_find_source_by_funcs_user_data:
1746 * @context: a #GMainContext (if %NULL, the default context will be used).
1747 * @funcs: the @source_funcs passed to g_source_new().
1748 * @user_data: the user data from the callback.
1750 * Finds a source with the given source functions and user data. If
1751 * multiple sources exist with the same source function and user data,
1752 * the first one found will be returned.
1754 * Return value: (transfer none): the source, if one was found, otherwise %NULL
1757 g_main_context_find_source_by_funcs_user_data (GMainContext
*context
,
1758 GSourceFuncs
*funcs
,
1763 g_return_val_if_fail (funcs
!= NULL
, NULL
);
1765 if (context
== NULL
)
1766 context
= g_main_context_default ();
1768 LOCK_CONTEXT (context
);
1770 source
= context
->source_list
;
1773 if (!SOURCE_DESTROYED (source
) &&
1774 source
->source_funcs
== funcs
&&
1775 source
->callback_funcs
)
1777 GSourceFunc callback
;
1778 gpointer callback_data
;
1780 source
->callback_funcs
->get (source
->callback_data
, source
, &callback
, &callback_data
);
1782 if (callback_data
== user_data
)
1785 source
= source
->next
;
1788 UNLOCK_CONTEXT (context
);
1794 * g_main_context_find_source_by_user_data:
1795 * @context: a #GMainContext
1796 * @user_data: the user_data for the callback.
1798 * Finds a source with the given user data for the callback. If
1799 * multiple sources exist with the same user data, the first
1800 * one found will be returned.
1802 * Return value: (transfer none): the source, if one was found, otherwise %NULL
1805 g_main_context_find_source_by_user_data (GMainContext
*context
,
1810 if (context
== NULL
)
1811 context
= g_main_context_default ();
1813 LOCK_CONTEXT (context
);
1815 source
= context
->source_list
;
1818 if (!SOURCE_DESTROYED (source
) &&
1819 source
->callback_funcs
)
1821 GSourceFunc callback
;
1822 gpointer callback_data
= NULL
;
1824 source
->callback_funcs
->get (source
->callback_data
, source
, &callback
, &callback_data
);
1826 if (callback_data
== user_data
)
1829 source
= source
->next
;
1832 UNLOCK_CONTEXT (context
);
1839 * @tag: the ID of the source to remove.
1841 * Removes the source with the given id from the default main context.
1843 * a #GSource is given by g_source_get_id(), or will be returned by the
1844 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1845 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1846 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1848 * See also g_source_destroy(). You must use g_source_destroy() for sources
1849 * added to a non-default main context.
1851 * Return value: %TRUE if the source was found and removed.
1854 g_source_remove (guint tag
)
1858 g_return_val_if_fail (tag
> 0, FALSE
);
1860 source
= g_main_context_find_source_by_id (NULL
, tag
);
1862 g_source_destroy (source
);
1864 return source
!= NULL
;
1868 * g_source_remove_by_user_data:
1869 * @user_data: the user_data for the callback.
1871 * Removes a source from the default main loop context given the user
1872 * data for the callback. If multiple sources exist with the same user
1873 * data, only one will be destroyed.
1875 * Return value: %TRUE if a source was found and removed.
1878 g_source_remove_by_user_data (gpointer user_data
)
1882 source
= g_main_context_find_source_by_user_data (NULL
, user_data
);
1885 g_source_destroy (source
);
1893 * g_source_remove_by_funcs_user_data:
1894 * @funcs: The @source_funcs passed to g_source_new()
1895 * @user_data: the user data for the callback
1897 * Removes a source from the default main loop context given the
1898 * source functions and user data. If multiple sources exist with the
1899 * same source functions and user data, only one will be destroyed.
1901 * Return value: %TRUE if a source was found and removed.
1904 g_source_remove_by_funcs_user_data (GSourceFuncs
*funcs
,
1909 g_return_val_if_fail (funcs
!= NULL
, FALSE
);
1911 source
= g_main_context_find_source_by_funcs_user_data (NULL
, funcs
, user_data
);
1914 g_source_destroy (source
);
1922 * g_get_current_time:
1923 * @result: #GTimeVal structure in which to store current time.
1925 * Equivalent to the UNIX gettimeofday() function, but portable.
1927 * You may find g_get_real_time() to be more convenient.
1930 g_get_current_time (GTimeVal
*result
)
1935 g_return_if_fail (result
!= NULL
);
1937 /*this is required on alpha, there the timeval structs are int's
1938 not longs and a cast only would fail horribly*/
1939 gettimeofday (&r
, NULL
);
1940 result
->tv_sec
= r
.tv_sec
;
1941 result
->tv_usec
= r
.tv_usec
;
1946 g_return_if_fail (result
!= NULL
);
1948 GetSystemTimeAsFileTime (&ft
);
1949 memmove (&time64
, &ft
, sizeof (FILETIME
));
1951 /* Convert from 100s of nanoseconds since 1601-01-01
1952 * to Unix epoch. Yes, this is Y2038 unsafe.
1954 time64
-= G_GINT64_CONSTANT (116444736000000000);
1957 result
->tv_sec
= time64
/ 1000000;
1958 result
->tv_usec
= time64
% 1000000;
1965 * Queries the system wall-clock time.
1967 * This call is functionally equivalent to g_get_current_time() except
1968 * that the return value is often more convenient than dealing with a
1971 * You should only use this call if you are actually interested in the real
1972 * wall-clock time. g_get_monotonic_time() is probably more useful for
1973 * measuring intervals.
1975 * Returns: the number of microseconds since January 1, 1970 UTC.
1980 g_get_real_time (void)
1984 g_get_current_time (&tv
);
1986 return (((gint64
) tv
.tv_sec
) * 1000000) + tv
.tv_usec
;
1990 * g_get_monotonic_time:
1992 * Queries the system monotonic time, if available.
1994 * On POSIX systems with clock_gettime() and %CLOCK_MONOTONIC this call
1995 * is a very shallow wrapper for that. Otherwise, we make a best effort
1996 * that probably involves returning the wall clock time (with at least
1997 * microsecond accuracy, subject to the limitations of the OS kernel).
1999 * It's important to note that POSIX %CLOCK_MONOTONIC does not count
2000 * time spent while the machine is suspended.
2002 * On Windows, "limitations of the OS kernel" is a rather substantial
2003 * statement. Depending on the configuration of the system, the wall
2004 * clock time is updated as infrequently as 64 times a second (which
2005 * is approximately every 16ms).
2007 * Returns: the monotonic time, in microseconds
2012 g_get_monotonic_time (void)
2014 #ifdef HAVE_CLOCK_GETTIME
2015 /* librt clock_gettime() is our first choice */
2018 #ifdef CLOCK_MONOTONIC
2019 clock_gettime (CLOCK_MONOTONIC
, &ts
);
2021 clock_gettime (CLOCK_REALTIME
, &ts
);
2024 /* In theory monotonic time can have any epoch.
2026 * glib presently assumes the following:
2028 * 1) The epoch comes some time after the birth of Jesus of Nazareth, but
2029 * not more than 10000 years later.
2031 * 2) The current time also falls sometime within this range.
2033 * These two reasonable assumptions leave us with a maximum deviation from
2034 * the epoch of 10000 years, or 315569520000000000 seconds.
2036 * If we restrict ourselves to this range then the number of microseconds
2037 * will always fit well inside the constraints of a int64 (by a factor of
2040 * If you actually hit the following assertion, probably you should file a
2041 * bug against your operating system for being excessively silly.
2043 g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts
.tv_sec
&&
2044 ts
.tv_sec
< G_GINT64_CONSTANT (315569520000000000));
2046 return (((gint64
) ts
.tv_sec
) * 1000000) + (ts
.tv_nsec
/ 1000);
2048 #else /* !HAVE_CLOCK_GETTIME */
2050 /* It may look like we are discarding accuracy on Windows (since its
2051 * current time is expressed in 100s of nanoseconds) but according to
2052 * many sources, the time is only updated 64 times per second, so
2053 * microsecond accuracy is more than enough.
2057 g_get_current_time (&tv
);
2059 return (((gint64
) tv
.tv_sec
) * 1000000) + tv
.tv_usec
;
2064 g_main_dispatch_free (gpointer dispatch
)
2066 g_slice_free (GMainDispatch
, dispatch
);
2069 /* Running the main loop */
2071 static GMainDispatch
*
2074 static GPrivate depth_private
= G_PRIVATE_INIT (g_main_dispatch_free
);
2075 GMainDispatch
*dispatch
;
2077 dispatch
= g_private_get (&depth_private
);
2081 dispatch
= g_slice_new0 (GMainDispatch
);
2082 g_private_set (&depth_private
, dispatch
);
2091 * Returns the depth of the stack of calls to
2092 * g_main_context_dispatch() on any #GMainContext in the current thread.
2093 * That is, when called from the toplevel, it gives 0. When
2094 * called from within a callback from g_main_context_iteration()
2095 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2096 * a callback to a recursive call to g_main_context_iteration(),
2097 * it returns 2. And so forth.
2099 * This function is useful in a situation like the following:
2100 * Imagine an extremely simple "garbage collected" system.
2103 * static GList *free_list;
2106 * allocate_memory (gsize size)
2108 * gpointer result = g_malloc (size);
2109 * free_list = g_list_prepend (free_list, result);
2114 * free_allocated_memory (void)
2117 * for (l = free_list; l; l = l->next);
2119 * g_list_free (free_list);
2127 * g_main_context_iteration (NULL, TRUE);
2128 * free_allocated_memory();
2132 * This works from an application, however, if you want to do the same
2133 * thing from a library, it gets more difficult, since you no longer
2134 * control the main loop. You might think you can simply use an idle
2135 * function to make the call to free_allocated_memory(), but that
2136 * doesn't work, since the idle function could be called from a
2137 * recursive callback. This can be fixed by using g_main_depth()
2141 * allocate_memory (gsize size)
2143 * FreeListBlock *block = g_new (FreeListBlock, 1);
2144 * block->mem = g_malloc (size);
2145 * block->depth = g_main_depth ();
2146 * free_list = g_list_prepend (free_list, block);
2147 * return block->mem;
2151 * free_allocated_memory (void)
2155 * int depth = g_main_depth ();
2156 * for (l = free_list; l; );
2158 * GList *next = l->next;
2159 * FreeListBlock *block = l->data;
2160 * if (block->depth > depth)
2162 * g_free (block->mem);
2164 * free_list = g_list_delete_link (free_list, l);
2172 * There is a temptation to use g_main_depth() to solve
2173 * problems with reentrancy. For instance, while waiting for data
2174 * to be received from the network in response to a menu item,
2175 * the menu item might be selected again. It might seem that
2176 * one could make the menu item's callback return immediately
2177 * and do nothing if g_main_depth() returns a value greater than 1.
2178 * However, this should be avoided since the user then sees selecting
2179 * the menu item do nothing. Furthermore, you'll find yourself adding
2180 * these checks all over your code, since there are doubtless many,
2181 * many things that the user could do. Instead, you can use the
2182 * following techniques:
2187 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
2188 * the user from interacting with elements while the main
2189 * loop is recursing.
2194 * Avoid main loop recursion in situations where you can't handle
2195 * arbitrary callbacks. Instead, structure your code so that you
2196 * simply return to the main loop and then get called again when
2197 * there is more work to do.
2202 * Return value: The main loop recursion level in the current thread
2207 GMainDispatch
*dispatch
= get_dispatch ();
2208 return dispatch
->depth
;
2212 * g_main_current_source:
2214 * Returns the currently firing source for this thread.
2216 * Return value: (transfer none): The currently firing source or %NULL.
2221 g_main_current_source (void)
2223 GMainDispatch
*dispatch
= get_dispatch ();
2224 return dispatch
->dispatching_sources
? dispatch
->dispatching_sources
->data
: NULL
;
2228 * g_source_is_destroyed:
2229 * @source: a #GSource
2231 * Returns whether @source has been destroyed.
2233 * This is important when you operate upon your objects
2234 * from within idle handlers, but may have freed the object
2235 * before the dispatch of your idle handler.
2239 * idle_callback (gpointer data)
2241 * SomeWidget *self = data;
2243 * GDK_THREADS_ENTER (<!-- -->);
2244 * /<!-- -->* do stuff with self *<!-- -->/
2245 * self->idle_id = 0;
2246 * GDK_THREADS_LEAVE (<!-- -->);
2252 * some_widget_do_stuff_later (SomeWidget *self)
2254 * self->idle_id = g_idle_add (idle_callback, self);
2258 * some_widget_finalize (GObject *object)
2260 * SomeWidget *self = SOME_WIDGET (object);
2262 * if (self->idle_id)
2263 * g_source_remove (self->idle_id);
2265 * G_OBJECT_CLASS (parent_class)->finalize (object);
2269 * This will fail in a multi-threaded application if the
2270 * widget is destroyed before the idle handler fires due
2271 * to the use after free in the callback. A solution, to
2272 * this particular problem, is to check to if the source
2273 * has already been destroy within the callback.
2277 * idle_callback (gpointer data)
2279 * SomeWidget *self = data;
2281 * GDK_THREADS_ENTER ();
2282 * if (!g_source_is_destroyed (g_main_current_source ()))
2284 * /<!-- -->* do stuff with self *<!-- -->/
2286 * GDK_THREADS_LEAVE ();
2292 * Return value: %TRUE if the source has been destroyed
2297 g_source_is_destroyed (GSource
*source
)
2299 return SOURCE_DESTROYED (source
);
2302 /* Temporarily remove all this source's file descriptors from the
2303 * poll(), so that if data comes available for one of the file descriptors
2304 * we don't continually spin in the poll()
2306 /* HOLDS: source->context's lock */
2308 block_source (GSource
*source
)
2312 g_return_if_fail (!SOURCE_BLOCKED (source
));
2314 tmp_list
= source
->poll_fds
;
2317 g_main_context_remove_poll_unlocked (source
->context
, tmp_list
->data
);
2318 tmp_list
= tmp_list
->next
;
2322 /* HOLDS: source->context's lock */
2324 unblock_source (GSource
*source
)
2328 g_return_if_fail (!SOURCE_BLOCKED (source
)); /* Source already unblocked */
2329 g_return_if_fail (!SOURCE_DESTROYED (source
));
2331 tmp_list
= source
->poll_fds
;
2334 g_main_context_add_poll_unlocked (source
->context
, source
->priority
, tmp_list
->data
);
2335 tmp_list
= tmp_list
->next
;
2339 /* HOLDS: context's lock */
2341 g_main_dispatch (GMainContext
*context
)
2343 GMainDispatch
*current
= get_dispatch ();
2346 for (i
= 0; i
< context
->pending_dispatches
->len
; i
++)
2348 GSource
*source
= context
->pending_dispatches
->pdata
[i
];
2350 context
->pending_dispatches
->pdata
[i
] = NULL
;
2353 source
->flags
&= ~G_SOURCE_READY
;
2355 if (!SOURCE_DESTROYED (source
))
2357 gboolean was_in_call
;
2358 gpointer user_data
= NULL
;
2359 GSourceFunc callback
= NULL
;
2360 GSourceCallbackFuncs
*cb_funcs
;
2362 gboolean need_destroy
;
2364 gboolean (*dispatch
) (GSource
*,
2367 GSList current_source_link
;
2369 dispatch
= source
->source_funcs
->dispatch
;
2370 cb_funcs
= source
->callback_funcs
;
2371 cb_data
= source
->callback_data
;
2374 cb_funcs
->ref (cb_data
);
2376 if ((source
->flags
& G_SOURCE_CAN_RECURSE
) == 0)
2377 block_source (source
);
2379 was_in_call
= source
->flags
& G_HOOK_FLAG_IN_CALL
;
2380 source
->flags
|= G_HOOK_FLAG_IN_CALL
;
2383 cb_funcs
->get (cb_data
, source
, &callback
, &user_data
);
2385 UNLOCK_CONTEXT (context
);
2388 /* The on-stack allocation of the GSList is unconventional, but
2389 * we know that the lifetime of the link is bounded to this
2390 * function as the link is kept in a thread specific list and
2391 * not manipulated outside of this function and its descendants.
2392 * Avoiding the overhead of a g_slist_alloc() is useful as many
2393 * applications do little more than dispatch events.
2395 * This is a performance hack - do not revert to g_slist_prepend()!
2397 current_source_link
.data
= source
;
2398 current_source_link
.next
= current
->dispatching_sources
;
2399 current
->dispatching_sources
= ¤t_source_link
;
2400 need_destroy
= ! dispatch (source
,
2403 g_assert (current
->dispatching_sources
== ¤t_source_link
);
2404 current
->dispatching_sources
= current_source_link
.next
;
2408 cb_funcs
->unref (cb_data
);
2410 LOCK_CONTEXT (context
);
2413 source
->flags
&= ~G_HOOK_FLAG_IN_CALL
;
2415 if ((source
->flags
& G_SOURCE_CAN_RECURSE
) == 0 &&
2416 !SOURCE_DESTROYED (source
))
2417 unblock_source (source
);
2419 /* Note: this depends on the fact that we can't switch
2420 * sources from one main context to another
2422 if (need_destroy
&& !SOURCE_DESTROYED (source
))
2424 g_assert (source
->context
== context
);
2425 g_source_destroy_internal (source
, context
, TRUE
);
2429 SOURCE_UNREF (source
, context
);
2432 g_ptr_array_set_size (context
->pending_dispatches
, 0);
2435 /* Holds context's lock */
2436 static inline GSource
*
2437 next_valid_source (GMainContext
*context
,
2440 GSource
*new_source
= source
? source
->next
: context
->source_list
;
2444 if (!SOURCE_DESTROYED (new_source
))
2446 new_source
->ref_count
++;
2450 new_source
= new_source
->next
;
2454 SOURCE_UNREF (source
, context
);
2460 * g_main_context_acquire:
2461 * @context: a #GMainContext
2463 * Tries to become the owner of the specified context.
2464 * If some other thread is the owner of the context,
2465 * returns %FALSE immediately. Ownership is properly
2466 * recursive: the owner can require ownership again
2467 * and will release ownership when g_main_context_release()
2468 * is called as many times as g_main_context_acquire().
2470 * You must be the owner of a context before you
2471 * can call g_main_context_prepare(), g_main_context_query(),
2472 * g_main_context_check(), g_main_context_dispatch().
2474 * Return value: %TRUE if the operation succeeded, and
2475 * this thread is now the owner of @context.
2478 g_main_context_acquire (GMainContext
*context
)
2480 gboolean result
= FALSE
;
2481 GThread
*self
= G_THREAD_SELF
;
2483 if (context
== NULL
)
2484 context
= g_main_context_default ();
2486 LOCK_CONTEXT (context
);
2488 if (!context
->owner
)
2490 context
->owner
= self
;
2491 g_assert (context
->owner_count
== 0);
2494 if (context
->owner
== self
)
2496 context
->owner_count
++;
2500 UNLOCK_CONTEXT (context
);
2506 * g_main_context_release:
2507 * @context: a #GMainContext
2509 * Releases ownership of a context previously acquired by this thread
2510 * with g_main_context_acquire(). If the context was acquired multiple
2511 * times, the ownership will be released only when g_main_context_release()
2512 * is called as many times as it was acquired.
2515 g_main_context_release (GMainContext
*context
)
2517 if (context
== NULL
)
2518 context
= g_main_context_default ();
2520 LOCK_CONTEXT (context
);
2522 context
->owner_count
--;
2523 if (context
->owner_count
== 0)
2525 context
->owner
= NULL
;
2527 if (context
->waiters
)
2529 GMainWaiter
*waiter
= context
->waiters
->data
;
2530 gboolean loop_internal_waiter
= (waiter
->mutex
== &context
->mutex
);
2531 context
->waiters
= g_slist_delete_link (context
->waiters
,
2533 if (!loop_internal_waiter
)
2534 g_mutex_lock (waiter
->mutex
);
2536 g_cond_signal (waiter
->cond
);
2538 if (!loop_internal_waiter
)
2539 g_mutex_unlock (waiter
->mutex
);
2543 UNLOCK_CONTEXT (context
);
2547 * g_main_context_wait:
2548 * @context: a #GMainContext
2549 * @cond: a condition variable
2550 * @mutex: a mutex, currently held
2552 * Tries to become the owner of the specified context,
2553 * as with g_main_context_acquire(). But if another thread
2554 * is the owner, atomically drop @mutex and wait on @cond until
2555 * that owner releases ownership or until @cond is signaled, then
2556 * try again (once) to become the owner.
2558 * Return value: %TRUE if the operation succeeded, and
2559 * this thread is now the owner of @context.
2562 g_main_context_wait (GMainContext
*context
,
2566 gboolean result
= FALSE
;
2567 GThread
*self
= G_THREAD_SELF
;
2568 gboolean loop_internal_waiter
;
2570 if (context
== NULL
)
2571 context
= g_main_context_default ();
2573 loop_internal_waiter
= (mutex
== &context
->mutex
);
2575 if (!loop_internal_waiter
)
2576 LOCK_CONTEXT (context
);
2578 if (context
->owner
&& context
->owner
!= self
)
2583 waiter
.mutex
= mutex
;
2585 context
->waiters
= g_slist_append (context
->waiters
, &waiter
);
2587 if (!loop_internal_waiter
)
2588 UNLOCK_CONTEXT (context
);
2589 g_cond_wait (cond
, mutex
);
2590 if (!loop_internal_waiter
)
2591 LOCK_CONTEXT (context
);
2593 context
->waiters
= g_slist_remove (context
->waiters
, &waiter
);
2596 if (!context
->owner
)
2598 context
->owner
= self
;
2599 g_assert (context
->owner_count
== 0);
2602 if (context
->owner
== self
)
2604 context
->owner_count
++;
2608 if (!loop_internal_waiter
)
2609 UNLOCK_CONTEXT (context
);
2615 * g_main_context_prepare:
2616 * @context: a #GMainContext
2617 * @priority: location to store priority of highest priority
2618 * source already ready.
2620 * Prepares to poll sources within a main loop. The resulting information
2621 * for polling is determined by calling g_main_context_query ().
2623 * Return value: %TRUE if some source is ready to be dispatched
2627 g_main_context_prepare (GMainContext
*context
,
2632 gint current_priority
= G_MAXINT
;
2635 if (context
== NULL
)
2636 context
= g_main_context_default ();
2638 LOCK_CONTEXT (context
);
2640 context
->time_is_fresh
= FALSE
;
2642 if (context
->in_check_or_prepare
)
2644 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2645 "prepare() member.");
2646 UNLOCK_CONTEXT (context
);
2651 /* If recursing, finish up current dispatch, before starting over */
2652 if (context
->pending_dispatches
)
2655 g_main_dispatch (context
, ¤t_time
);
2657 UNLOCK_CONTEXT (context
);
2662 /* If recursing, clear list of pending dispatches */
2664 for (i
= 0; i
< context
->pending_dispatches
->len
; i
++)
2666 if (context
->pending_dispatches
->pdata
[i
])
2667 SOURCE_UNREF ((GSource
*)context
->pending_dispatches
->pdata
[i
], context
);
2669 g_ptr_array_set_size (context
->pending_dispatches
, 0);
2671 /* Prepare all sources */
2673 context
->timeout
= -1;
2675 source
= next_valid_source (context
, NULL
);
2678 gint source_timeout
= -1;
2680 if ((n_ready
> 0) && (source
->priority
> current_priority
))
2682 SOURCE_UNREF (source
, context
);
2685 if (SOURCE_BLOCKED (source
))
2688 if (!(source
->flags
& G_SOURCE_READY
))
2691 gboolean (*prepare
) (GSource
*source
,
2694 prepare
= source
->source_funcs
->prepare
;
2695 context
->in_check_or_prepare
++;
2696 UNLOCK_CONTEXT (context
);
2698 result
= (*prepare
) (source
, &source_timeout
);
2700 LOCK_CONTEXT (context
);
2701 context
->in_check_or_prepare
--;
2705 GSource
*ready_source
= source
;
2707 while (ready_source
)
2709 ready_source
->flags
|= G_SOURCE_READY
;
2710 ready_source
= ready_source
->priv
? ready_source
->priv
->parent_source
: NULL
;
2715 if (source
->flags
& G_SOURCE_READY
)
2718 current_priority
= source
->priority
;
2719 context
->timeout
= 0;
2722 if (source_timeout
>= 0)
2724 if (context
->timeout
< 0)
2725 context
->timeout
= source_timeout
;
2727 context
->timeout
= MIN (context
->timeout
, source_timeout
);
2731 source
= next_valid_source (context
, source
);
2734 UNLOCK_CONTEXT (context
);
2737 *priority
= current_priority
;
2739 return (n_ready
> 0);
2743 * g_main_context_query:
2744 * @context: a #GMainContext
2745 * @max_priority: maximum priority source to check
2746 * @timeout_: (out): location to store timeout to be used in polling
2747 * @fds: (out caller-allocates) (array length=n_fds): location to
2748 * store #GPollFD records that need to be polled.
2749 * @n_fds: length of @fds.
2751 * Determines information necessary to poll this main loop.
2753 * Return value: the number of records actually stored in @fds,
2754 * or, if more than @n_fds records need to be stored, the number
2755 * of records that need to be stored.
2758 g_main_context_query (GMainContext
*context
,
2767 LOCK_CONTEXT (context
);
2769 pollrec
= context
->poll_records
;
2771 while (pollrec
&& max_priority
>= pollrec
->priority
)
2773 /* We need to include entries with fd->events == 0 in the array because
2774 * otherwise if the application changes fd->events behind our back and
2775 * makes it non-zero, we'll be out of sync when we check the fds[] array.
2776 * (Changing fd->events after adding an FD wasn't an anticipated use of
2777 * this API, but it occurs in practice.) */
2780 fds
[n_poll
].fd
= pollrec
->fd
->fd
;
2781 /* In direct contradiction to the Unix98 spec, IRIX runs into
2782 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2783 * flags in the events field of the pollfd while it should
2784 * just ignoring them. So we mask them out here.
2786 fds
[n_poll
].events
= pollrec
->fd
->events
& ~(G_IO_ERR
|G_IO_HUP
|G_IO_NVAL
);
2787 fds
[n_poll
].revents
= 0;
2790 pollrec
= pollrec
->next
;
2794 context
->poll_changed
= FALSE
;
2798 *timeout
= context
->timeout
;
2800 context
->time_is_fresh
= FALSE
;
2803 UNLOCK_CONTEXT (context
);
2809 * g_main_context_check:
2810 * @context: a #GMainContext
2811 * @max_priority: the maximum numerical priority of sources to check
2812 * @fds: (array length=n_fds): array of #GPollFD's that was passed to
2813 * the last call to g_main_context_query()
2814 * @n_fds: return value of g_main_context_query()
2816 * Passes the results of polling back to the main loop.
2818 * Return value: %TRUE if some sources are ready to be dispatched.
2821 g_main_context_check (GMainContext
*context
,
2831 LOCK_CONTEXT (context
);
2833 if (context
->in_check_or_prepare
)
2835 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2836 "prepare() member.");
2837 UNLOCK_CONTEXT (context
);
2841 if (context
->wake_up_rec
.events
)
2842 g_wakeup_acknowledge (context
->wakeup
);
2844 /* If the set of poll file descriptors changed, bail out
2845 * and let the main loop rerun
2847 if (context
->poll_changed
)
2849 UNLOCK_CONTEXT (context
);
2853 pollrec
= context
->poll_records
;
2857 if (pollrec
->fd
->events
)
2858 pollrec
->fd
->revents
= fds
[i
].revents
;
2860 pollrec
= pollrec
->next
;
2864 source
= next_valid_source (context
, NULL
);
2867 if ((n_ready
> 0) && (source
->priority
> max_priority
))
2869 SOURCE_UNREF (source
, context
);
2872 if (SOURCE_BLOCKED (source
))
2875 if (!(source
->flags
& G_SOURCE_READY
))
2878 gboolean (*check
) (GSource
*source
);
2880 check
= source
->source_funcs
->check
;
2882 context
->in_check_or_prepare
++;
2883 UNLOCK_CONTEXT (context
);
2885 result
= (*check
) (source
);
2887 LOCK_CONTEXT (context
);
2888 context
->in_check_or_prepare
--;
2892 GSource
*ready_source
= source
;
2894 while (ready_source
)
2896 ready_source
->flags
|= G_SOURCE_READY
;
2897 ready_source
= ready_source
->priv
? ready_source
->priv
->parent_source
: NULL
;
2902 if (source
->flags
& G_SOURCE_READY
)
2904 source
->ref_count
++;
2905 g_ptr_array_add (context
->pending_dispatches
, source
);
2909 /* never dispatch sources with less priority than the first
2910 * one we choose to dispatch
2912 max_priority
= source
->priority
;
2916 source
= next_valid_source (context
, source
);
2919 UNLOCK_CONTEXT (context
);
2925 * g_main_context_dispatch:
2926 * @context: a #GMainContext
2928 * Dispatches all pending sources.
2931 g_main_context_dispatch (GMainContext
*context
)
2933 LOCK_CONTEXT (context
);
2935 if (context
->pending_dispatches
->len
> 0)
2937 g_main_dispatch (context
);
2940 UNLOCK_CONTEXT (context
);
2943 /* HOLDS context lock */
2945 g_main_context_iterate (GMainContext
*context
,
2952 gboolean some_ready
;
2953 gint nfds
, allocated_nfds
;
2954 GPollFD
*fds
= NULL
;
2956 UNLOCK_CONTEXT (context
);
2958 if (!g_main_context_acquire (context
))
2960 gboolean got_ownership
;
2962 LOCK_CONTEXT (context
);
2967 got_ownership
= g_main_context_wait (context
,
2975 LOCK_CONTEXT (context
);
2977 if (!context
->cached_poll_array
)
2979 context
->cached_poll_array_size
= context
->n_poll_records
;
2980 context
->cached_poll_array
= g_new (GPollFD
, context
->n_poll_records
);
2983 allocated_nfds
= context
->cached_poll_array_size
;
2984 fds
= context
->cached_poll_array
;
2986 UNLOCK_CONTEXT (context
);
2988 g_main_context_prepare (context
, &max_priority
);
2990 while ((nfds
= g_main_context_query (context
, max_priority
, &timeout
, fds
,
2991 allocated_nfds
)) > allocated_nfds
)
2993 LOCK_CONTEXT (context
);
2995 context
->cached_poll_array_size
= allocated_nfds
= nfds
;
2996 context
->cached_poll_array
= fds
= g_new (GPollFD
, nfds
);
2997 UNLOCK_CONTEXT (context
);
3003 g_assert (!g_main_context_fork_detected
);
3004 g_main_context_poll (context
, timeout
, max_priority
, fds
, nfds
);
3006 some_ready
= g_main_context_check (context
, max_priority
, fds
, nfds
);
3009 g_main_context_dispatch (context
);
3011 g_main_context_release (context
);
3013 LOCK_CONTEXT (context
);
3019 * g_main_context_pending:
3020 * @context: a #GMainContext (if %NULL, the default context will be used)
3022 * Checks if any sources have pending events for the given context.
3024 * Return value: %TRUE if events are pending.
3027 g_main_context_pending (GMainContext
*context
)
3032 context
= g_main_context_default();
3034 LOCK_CONTEXT (context
);
3035 retval
= g_main_context_iterate (context
, FALSE
, FALSE
, G_THREAD_SELF
);
3036 UNLOCK_CONTEXT (context
);
3042 * g_main_context_iteration:
3043 * @context: a #GMainContext (if %NULL, the default context will be used)
3044 * @may_block: whether the call may block.
3046 * Runs a single iteration for the given main loop. This involves
3047 * checking to see if any event sources are ready to be processed,
3048 * then if no events sources are ready and @may_block is %TRUE, waiting
3049 * for a source to become ready, then dispatching the highest priority
3050 * events sources that are ready. Otherwise, if @may_block is %FALSE
3051 * sources are not waited to become ready, only those highest priority
3052 * events sources will be dispatched (if any), that are ready at this
3053 * given moment without further waiting.
3055 * Note that even when @may_block is %TRUE, it is still possible for
3056 * g_main_context_iteration() to return %FALSE, since the the wait may
3057 * be interrupted for other reasons than an event source becoming ready.
3059 * Return value: %TRUE if events were dispatched.
3062 g_main_context_iteration (GMainContext
*context
, gboolean may_block
)
3067 context
= g_main_context_default();
3069 LOCK_CONTEXT (context
);
3070 retval
= g_main_context_iterate (context
, may_block
, TRUE
, G_THREAD_SELF
);
3071 UNLOCK_CONTEXT (context
);
3078 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
3079 * @is_running: set to %TRUE to indicate that the loop is running. This
3080 * is not very important since calling g_main_loop_run() will set this to
3083 * Creates a new #GMainLoop structure.
3085 * Return value: a new #GMainLoop.
3088 g_main_loop_new (GMainContext
*context
,
3089 gboolean is_running
)
3094 context
= g_main_context_default();
3096 g_main_context_ref (context
);
3098 loop
= g_new0 (GMainLoop
, 1);
3099 loop
->context
= context
;
3100 loop
->is_running
= is_running
!= FALSE
;
3101 loop
->ref_count
= 1;
3108 * @loop: a #GMainLoop
3110 * Increases the reference count on a #GMainLoop object by one.
3112 * Return value: @loop
3115 g_main_loop_ref (GMainLoop
*loop
)
3117 g_return_val_if_fail (loop
!= NULL
, NULL
);
3118 g_return_val_if_fail (g_atomic_int_get (&loop
->ref_count
) > 0, NULL
);
3120 g_atomic_int_inc (&loop
->ref_count
);
3126 * g_main_loop_unref:
3127 * @loop: a #GMainLoop
3129 * Decreases the reference count on a #GMainLoop object by one. If
3130 * the result is zero, free the loop and free all associated memory.
3133 g_main_loop_unref (GMainLoop
*loop
)
3135 g_return_if_fail (loop
!= NULL
);
3136 g_return_if_fail (g_atomic_int_get (&loop
->ref_count
) > 0);
3138 if (!g_atomic_int_dec_and_test (&loop
->ref_count
))
3141 g_main_context_unref (loop
->context
);
3147 * @loop: a #GMainLoop
3149 * Runs a main loop until g_main_loop_quit() is called on the loop.
3150 * If this is called for the thread of the loop's #GMainContext,
3151 * it will process events from the loop, otherwise it will
3155 g_main_loop_run (GMainLoop
*loop
)
3157 GThread
*self
= G_THREAD_SELF
;
3159 g_return_if_fail (loop
!= NULL
);
3160 g_return_if_fail (g_atomic_int_get (&loop
->ref_count
) > 0);
3162 if (!g_main_context_acquire (loop
->context
))
3164 gboolean got_ownership
= FALSE
;
3166 /* Another thread owns this context */
3167 LOCK_CONTEXT (loop
->context
);
3169 g_atomic_int_inc (&loop
->ref_count
);
3171 if (!loop
->is_running
)
3172 loop
->is_running
= TRUE
;
3174 while (loop
->is_running
&& !got_ownership
)
3175 got_ownership
= g_main_context_wait (loop
->context
,
3176 &loop
->context
->cond
,
3177 &loop
->context
->mutex
);
3179 if (!loop
->is_running
)
3181 UNLOCK_CONTEXT (loop
->context
);
3183 g_main_context_release (loop
->context
);
3184 g_main_loop_unref (loop
);
3188 g_assert (got_ownership
);
3191 LOCK_CONTEXT (loop
->context
);
3193 if (loop
->context
->in_check_or_prepare
)
3195 g_warning ("g_main_loop_run(): called recursively from within a source's "
3196 "check() or prepare() member, iteration not possible.");
3200 g_atomic_int_inc (&loop
->ref_count
);
3201 loop
->is_running
= TRUE
;
3202 while (loop
->is_running
)
3203 g_main_context_iterate (loop
->context
, TRUE
, TRUE
, self
);
3205 UNLOCK_CONTEXT (loop
->context
);
3207 g_main_context_release (loop
->context
);
3209 g_main_loop_unref (loop
);
3214 * @loop: a #GMainLoop
3216 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3217 * for the loop will return.
3219 * Note that sources that have already been dispatched when
3220 * g_main_loop_quit() is called will still be executed.
3223 g_main_loop_quit (GMainLoop
*loop
)
3225 g_return_if_fail (loop
!= NULL
);
3226 g_return_if_fail (g_atomic_int_get (&loop
->ref_count
) > 0);
3228 LOCK_CONTEXT (loop
->context
);
3229 loop
->is_running
= FALSE
;
3230 g_wakeup_signal (loop
->context
->wakeup
);
3232 g_cond_broadcast (&loop
->context
->cond
);
3234 UNLOCK_CONTEXT (loop
->context
);
3238 * g_main_loop_is_running:
3239 * @loop: a #GMainLoop.
3241 * Checks to see if the main loop is currently being run via g_main_loop_run().
3243 * Return value: %TRUE if the mainloop is currently being run.
3246 g_main_loop_is_running (GMainLoop
*loop
)
3248 g_return_val_if_fail (loop
!= NULL
, FALSE
);
3249 g_return_val_if_fail (g_atomic_int_get (&loop
->ref_count
) > 0, FALSE
);
3251 return loop
->is_running
;
3255 * g_main_loop_get_context:
3256 * @loop: a #GMainLoop.
3258 * Returns the #GMainContext of @loop.
3260 * Return value: (transfer none): the #GMainContext of @loop
3263 g_main_loop_get_context (GMainLoop
*loop
)
3265 g_return_val_if_fail (loop
!= NULL
, NULL
);
3266 g_return_val_if_fail (g_atomic_int_get (&loop
->ref_count
) > 0, NULL
);
3268 return loop
->context
;
3271 /* HOLDS: context's lock */
3273 g_main_context_poll (GMainContext
*context
,
3279 #ifdef G_MAIN_POLL_DEBUG
3285 GPollFunc poll_func
;
3287 if (n_fds
|| timeout
!= 0)
3289 #ifdef G_MAIN_POLL_DEBUG
3290 if (_g_main_poll_debug
)
3292 g_print ("polling context=%p n=%d timeout=%d\n",
3293 context
, n_fds
, timeout
);
3294 poll_timer
= g_timer_new ();
3298 LOCK_CONTEXT (context
);
3300 poll_func
= context
->poll_func
;
3302 UNLOCK_CONTEXT (context
);
3303 if ((*poll_func
) (fds
, n_fds
, timeout
) < 0 && errno
!= EINTR
)
3306 g_warning ("poll(2) failed due to: %s.",
3307 g_strerror (errno
));
3309 /* If g_poll () returns -1, it has already called g_warning() */
3313 #ifdef G_MAIN_POLL_DEBUG
3314 if (_g_main_poll_debug
)
3316 LOCK_CONTEXT (context
);
3318 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3321 g_timer_elapsed (poll_timer
, NULL
));
3322 g_timer_destroy (poll_timer
);
3323 pollrec
= context
->poll_records
;
3325 while (pollrec
!= NULL
)
3330 if (fds
[i
].fd
== pollrec
->fd
->fd
&&
3331 pollrec
->fd
->events
&&
3334 g_print (" [" G_POLLFD_FORMAT
" :", fds
[i
].fd
);
3335 if (fds
[i
].revents
& G_IO_IN
)
3337 if (fds
[i
].revents
& G_IO_OUT
)
3339 if (fds
[i
].revents
& G_IO_PRI
)
3341 if (fds
[i
].revents
& G_IO_ERR
)
3343 if (fds
[i
].revents
& G_IO_HUP
)
3345 if (fds
[i
].revents
& G_IO_NVAL
)
3351 pollrec
= pollrec
->next
;
3355 UNLOCK_CONTEXT (context
);
3358 } /* if (n_fds || timeout != 0) */
3362 * g_main_context_add_poll:
3363 * @context: a #GMainContext (or %NULL for the default context)
3364 * @fd: a #GPollFD structure holding information about a file
3365 * descriptor to watch.
3366 * @priority: the priority for this file descriptor which should be
3367 * the same as the priority used for g_source_attach() to ensure that the
3368 * file descriptor is polled whenever the results may be needed.
3370 * Adds a file descriptor to the set of file descriptors polled for
3371 * this context. This will very seldom be used directly. Instead
3372 * a typical event source will use g_source_add_poll() instead.
3375 g_main_context_add_poll (GMainContext
*context
,
3380 context
= g_main_context_default ();
3382 g_return_if_fail (g_atomic_int_get (&context
->ref_count
) > 0);
3383 g_return_if_fail (fd
);
3385 LOCK_CONTEXT (context
);
3386 g_main_context_add_poll_unlocked (context
, priority
, fd
);
3387 UNLOCK_CONTEXT (context
);
3390 /* HOLDS: main_loop_lock */
3392 g_main_context_add_poll_unlocked (GMainContext
*context
,
3396 GPollRec
*prevrec
, *nextrec
;
3397 GPollRec
*newrec
= g_slice_new (GPollRec
);
3399 /* This file descriptor may be checked before we ever poll */
3402 newrec
->priority
= priority
;
3404 prevrec
= context
->poll_records_tail
;
3406 while (prevrec
&& priority
< prevrec
->priority
)
3409 prevrec
= prevrec
->prev
;
3413 prevrec
->next
= newrec
;
3415 context
->poll_records
= newrec
;
3417 newrec
->prev
= prevrec
;
3418 newrec
->next
= nextrec
;
3421 nextrec
->prev
= newrec
;
3423 context
->poll_records_tail
= newrec
;
3425 context
->n_poll_records
++;
3427 context
->poll_changed
= TRUE
;
3429 /* Now wake up the main loop if it is waiting in the poll() */
3430 g_wakeup_signal (context
->wakeup
);
3434 * g_main_context_remove_poll:
3435 * @context:a #GMainContext
3436 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3438 * Removes file descriptor from the set of file descriptors to be
3439 * polled for a particular context.
3442 g_main_context_remove_poll (GMainContext
*context
,
3446 context
= g_main_context_default ();
3448 g_return_if_fail (g_atomic_int_get (&context
->ref_count
) > 0);
3449 g_return_if_fail (fd
);
3451 LOCK_CONTEXT (context
);
3452 g_main_context_remove_poll_unlocked (context
, fd
);
3453 UNLOCK_CONTEXT (context
);
3457 g_main_context_remove_poll_unlocked (GMainContext
*context
,
3460 GPollRec
*pollrec
, *prevrec
, *nextrec
;
3463 pollrec
= context
->poll_records
;
3467 nextrec
= pollrec
->next
;
3468 if (pollrec
->fd
== fd
)
3470 if (prevrec
!= NULL
)
3471 prevrec
->next
= nextrec
;
3473 context
->poll_records
= nextrec
;
3475 if (nextrec
!= NULL
)
3476 nextrec
->prev
= prevrec
;
3478 context
->poll_records_tail
= prevrec
;
3480 g_slice_free (GPollRec
, pollrec
);
3482 context
->n_poll_records
--;
3489 context
->poll_changed
= TRUE
;
3491 /* Now wake up the main loop if it is waiting in the poll() */
3492 g_wakeup_signal (context
->wakeup
);
3496 * g_source_get_current_time:
3497 * @source: a #GSource
3498 * @timeval: #GTimeVal structure in which to store current time.
3500 * This function ignores @source and is otherwise the same as
3501 * g_get_current_time().
3503 * Deprecated: 2.28: use g_source_get_time() instead
3506 g_source_get_current_time (GSource
*source
,
3509 g_get_current_time (timeval
);
3513 * g_source_get_time:
3514 * @source: a #GSource
3516 * Gets the time to be used when checking this source. The advantage of
3517 * calling this function over calling g_get_monotonic_time() directly is
3518 * that when checking multiple sources, GLib can cache a single value
3519 * instead of having to repeatedly get the system monotonic time.
3521 * The time here is the system monotonic time, if available, or some
3522 * other reasonable alternative otherwise. See g_get_monotonic_time().
3524 * Returns: the monotonic time in microseconds
3529 g_source_get_time (GSource
*source
)
3531 GMainContext
*context
;
3534 g_return_val_if_fail (source
->context
!= NULL
, 0);
3536 context
= source
->context
;
3538 LOCK_CONTEXT (context
);
3540 if (!context
->time_is_fresh
)
3542 context
->time
= g_get_monotonic_time ();
3543 context
->time_is_fresh
= TRUE
;
3546 result
= context
->time
;
3548 UNLOCK_CONTEXT (context
);
3554 * g_main_context_set_poll_func:
3555 * @context: a #GMainContext
3556 * @func: the function to call to poll all file descriptors
3558 * Sets the function to use to handle polling of file descriptors. It
3559 * will be used instead of the poll() system call
3560 * (or GLib's replacement function, which is used where
3561 * poll() isn't available).
3563 * This function could possibly be used to integrate the GLib event
3564 * loop with an external event loop.
3567 g_main_context_set_poll_func (GMainContext
*context
,
3571 context
= g_main_context_default ();
3573 g_return_if_fail (g_atomic_int_get (&context
->ref_count
) > 0);
3575 LOCK_CONTEXT (context
);
3578 context
->poll_func
= func
;
3580 context
->poll_func
= g_poll
;
3582 UNLOCK_CONTEXT (context
);
3586 * g_main_context_get_poll_func:
3587 * @context: a #GMainContext
3589 * Gets the poll function set by g_main_context_set_poll_func().
3591 * Return value: the poll function
3594 g_main_context_get_poll_func (GMainContext
*context
)
3599 context
= g_main_context_default ();
3601 g_return_val_if_fail (g_atomic_int_get (&context
->ref_count
) > 0, NULL
);
3603 LOCK_CONTEXT (context
);
3604 result
= context
->poll_func
;
3605 UNLOCK_CONTEXT (context
);
3611 * g_main_context_wakeup:
3612 * @context: a #GMainContext
3614 * If @context is currently waiting in a poll(), interrupt
3615 * the poll(), and continue the iteration process.
3618 g_main_context_wakeup (GMainContext
*context
)
3621 context
= g_main_context_default ();
3623 g_return_if_fail (g_atomic_int_get (&context
->ref_count
) > 0);
3625 g_wakeup_signal (context
->wakeup
);
3629 * g_main_context_is_owner:
3630 * @context: a #GMainContext
3632 * Determines whether this thread holds the (recursive)
3633 * ownership of this #GMainContext. This is useful to
3634 * know before waiting on another thread that may be
3635 * blocking to get ownership of @context.
3637 * Returns: %TRUE if current thread is owner of @context.
3642 g_main_context_is_owner (GMainContext
*context
)
3647 context
= g_main_context_default ();
3649 LOCK_CONTEXT (context
);
3650 is_owner
= context
->owner
== G_THREAD_SELF
;
3651 UNLOCK_CONTEXT (context
);
3659 g_timeout_set_expiration (GTimeoutSource
*timeout_source
,
3660 gint64 current_time
)
3662 timeout_source
->expiration
= current_time
+
3663 (guint64
) timeout_source
->interval
* 1000;
3665 if (timeout_source
->seconds
)
3668 static gint timer_perturb
= -1;
3670 if (timer_perturb
== -1)
3673 * we want a per machine/session unique 'random' value; try the dbus
3674 * address first, that has a UUID in it. If there is no dbus, use the
3675 * hostname for hashing.
3677 const char *session_bus_address
= g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3678 if (!session_bus_address
)
3679 session_bus_address
= g_getenv ("HOSTNAME");
3680 if (session_bus_address
)
3681 timer_perturb
= ABS ((gint
) g_str_hash (session_bus_address
)) % 1000000;
3686 /* We want the microseconds part of the timeout to land on the
3687 * 'timer_perturb' mark, but we need to make sure we don't try to
3688 * set the timeout in the past. We do this by ensuring that we
3689 * always only *increase* the expiration time by adding a full
3690 * second in the case that the microsecond portion decreases.
3692 timeout_source
->expiration
-= timer_perturb
;
3694 remainder
= timeout_source
->expiration
% 1000000;
3695 if (remainder
>= 1000000/4)
3696 timeout_source
->expiration
+= 1000000;
3698 timeout_source
->expiration
-= remainder
;
3699 timeout_source
->expiration
+= timer_perturb
;
3704 g_timeout_prepare (GSource
*source
,
3707 GTimeoutSource
*timeout_source
= (GTimeoutSource
*) source
;
3708 gint64 now
= g_source_get_time (source
);
3710 if (now
< timeout_source
->expiration
)
3712 /* Round up to ensure that we don't try again too early */
3713 *timeout
= (timeout_source
->expiration
- now
+ 999) / 1000;
3722 g_timeout_check (GSource
*source
)
3724 GTimeoutSource
*timeout_source
= (GTimeoutSource
*) source
;
3725 gint64 now
= g_source_get_time (source
);
3727 return timeout_source
->expiration
<= now
;
3731 g_timeout_dispatch (GSource
*source
,
3732 GSourceFunc callback
,
3735 GTimeoutSource
*timeout_source
= (GTimeoutSource
*)source
;
3740 g_warning ("Timeout source dispatched without callback\n"
3741 "You must call g_source_set_callback().");
3745 again
= callback (user_data
);
3748 g_timeout_set_expiration (timeout_source
, g_source_get_time (source
));
3754 * g_timeout_source_new:
3755 * @interval: the timeout interval in milliseconds.
3757 * Creates a new timeout source.
3759 * The source will not initially be associated with any #GMainContext
3760 * and must be added to one with g_source_attach() before it will be
3763 * The interval given is in terms of monotonic time, not wall clock
3764 * time. See g_get_monotonic_time().
3766 * Return value: the newly-created timeout source
3769 g_timeout_source_new (guint interval
)
3771 GSource
*source
= g_source_new (&g_timeout_funcs
, sizeof (GTimeoutSource
));
3772 GTimeoutSource
*timeout_source
= (GTimeoutSource
*)source
;
3774 timeout_source
->interval
= interval
;
3775 g_timeout_set_expiration (timeout_source
, g_get_monotonic_time ());
3781 * g_timeout_source_new_seconds:
3782 * @interval: the timeout interval in seconds
3784 * Creates a new timeout source.
3786 * The source will not initially be associated with any #GMainContext
3787 * and must be added to one with g_source_attach() before it will be
3790 * The scheduling granularity/accuracy of this timeout source will be
3793 * The interval given in terms of monotonic time, not wall clock time.
3794 * See g_get_monotonic_time().
3796 * Return value: the newly-created timeout source
3801 g_timeout_source_new_seconds (guint interval
)
3803 GSource
*source
= g_source_new (&g_timeout_funcs
, sizeof (GTimeoutSource
));
3804 GTimeoutSource
*timeout_source
= (GTimeoutSource
*)source
;
3806 timeout_source
->interval
= 1000 * interval
;
3807 timeout_source
->seconds
= TRUE
;
3809 g_timeout_set_expiration (timeout_source
, g_get_monotonic_time ());
3816 * g_timeout_add_full:
3817 * @priority: the priority of the timeout source. Typically this will be in
3818 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3819 * @interval: the time between calls to the function, in milliseconds
3820 * (1/1000ths of a second)
3821 * @function: function to call
3822 * @data: data to pass to @function
3823 * @notify: function to call when the timeout is removed, or %NULL
3825 * Sets a function to be called at regular intervals, with the given
3826 * priority. The function is called repeatedly until it returns
3827 * %FALSE, at which point the timeout is automatically destroyed and
3828 * the function will not be called again. The @notify function is
3829 * called when the timeout is destroyed. The first call to the
3830 * function will be at the end of the first @interval.
3832 * Note that timeout functions may be delayed, due to the processing of other
3833 * event sources. Thus they should not be relied on for precise timing.
3834 * After each call to the timeout function, the time of the next
3835 * timeout is recalculated based on the current time and the given interval
3836 * (it does not try to 'catch up' time lost in delays).
3838 * This internally creates a main loop source using g_timeout_source_new()
3839 * and attaches it to the main loop context using g_source_attach(). You can
3840 * do these steps manually if you need greater control.
3842 * The interval given in terms of monotonic time, not wall clock time.
3843 * See g_get_monotonic_time().
3845 * Return value: the ID (greater than 0) of the event source.
3846 * Rename to: g_timeout_add
3849 g_timeout_add_full (gint priority
,
3851 GSourceFunc function
,
3853 GDestroyNotify notify
)
3858 g_return_val_if_fail (function
!= NULL
, 0);
3860 source
= g_timeout_source_new (interval
);
3862 if (priority
!= G_PRIORITY_DEFAULT
)
3863 g_source_set_priority (source
, priority
);
3865 g_source_set_callback (source
, function
, data
, notify
);
3866 id
= g_source_attach (source
, NULL
);
3867 g_source_unref (source
);
3874 * @interval: the time between calls to the function, in milliseconds
3875 * (1/1000ths of a second)
3876 * @function: function to call
3877 * @data: data to pass to @function
3879 * Sets a function to be called at regular intervals, with the default
3880 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
3881 * until it returns %FALSE, at which point the timeout is automatically
3882 * destroyed and the function will not be called again. The first call
3883 * to the function will be at the end of the first @interval.
3885 * Note that timeout functions may be delayed, due to the processing of other
3886 * event sources. Thus they should not be relied on for precise timing.
3887 * After each call to the timeout function, the time of the next
3888 * timeout is recalculated based on the current time and the given interval
3889 * (it does not try to 'catch up' time lost in delays).
3891 * If you want to have a timer in the "seconds" range and do not care
3892 * about the exact time of the first call of the timer, use the
3893 * g_timeout_add_seconds() function; this function allows for more
3894 * optimizations and more efficient system power usage.
3896 * This internally creates a main loop source using g_timeout_source_new()
3897 * and attaches it to the main loop context using g_source_attach(). You can
3898 * do these steps manually if you need greater control.
3900 * The interval given is in terms of monotonic time, not wall clock
3901 * time. See g_get_monotonic_time().
3903 * Return value: the ID (greater than 0) of the event source.
3906 g_timeout_add (guint32 interval
,
3907 GSourceFunc function
,
3910 return g_timeout_add_full (G_PRIORITY_DEFAULT
,
3911 interval
, function
, data
, NULL
);
3915 * g_timeout_add_seconds_full:
3916 * @priority: the priority of the timeout source. Typically this will be in
3917 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3918 * @interval: the time between calls to the function, in seconds
3919 * @function: function to call
3920 * @data: data to pass to @function
3921 * @notify: function to call when the timeout is removed, or %NULL
3923 * Sets a function to be called at regular intervals, with @priority.
3924 * The function is called repeatedly until it returns %FALSE, at which
3925 * point the timeout is automatically destroyed and the function will
3926 * not be called again.
3928 * Unlike g_timeout_add(), this function operates at whole second granularity.
3929 * The initial starting point of the timer is determined by the implementation
3930 * and the implementation is expected to group multiple timers together so that
3931 * they fire all at the same time.
3932 * To allow this grouping, the @interval to the first timer is rounded
3933 * and can deviate up to one second from the specified interval.
3934 * Subsequent timer iterations will generally run at the specified interval.
3936 * Note that timeout functions may be delayed, due to the processing of other
3937 * event sources. Thus they should not be relied on for precise timing.
3938 * After each call to the timeout function, the time of the next
3939 * timeout is recalculated based on the current time and the given @interval
3941 * If you want timing more precise than whole seconds, use g_timeout_add()
3944 * The grouping of timers to fire at the same time results in a more power
3945 * and CPU efficient behavior so if your timer is in multiples of seconds
3946 * and you don't require the first timer exactly one second from now, the
3947 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
3949 * This internally creates a main loop source using
3950 * g_timeout_source_new_seconds() and attaches it to the main loop context
3951 * using g_source_attach(). You can do these steps manually if you need
3954 * The interval given is in terms of monotonic time, not wall clock
3955 * time. See g_get_monotonic_time().
3957 * Return value: the ID (greater than 0) of the event source.
3959 * Rename to: g_timeout_add_seconds
3963 g_timeout_add_seconds_full (gint priority
,
3965 GSourceFunc function
,
3967 GDestroyNotify notify
)
3972 g_return_val_if_fail (function
!= NULL
, 0);
3974 source
= g_timeout_source_new_seconds (interval
);
3976 if (priority
!= G_PRIORITY_DEFAULT
)
3977 g_source_set_priority (source
, priority
);
3979 g_source_set_callback (source
, function
, data
, notify
);
3980 id
= g_source_attach (source
, NULL
);
3981 g_source_unref (source
);
3987 * g_timeout_add_seconds:
3988 * @interval: the time between calls to the function, in seconds
3989 * @function: function to call
3990 * @data: data to pass to @function
3992 * Sets a function to be called at regular intervals with the default
3993 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
3994 * it returns %FALSE, at which point the timeout is automatically destroyed
3995 * and the function will not be called again.
3997 * This internally creates a main loop source using
3998 * g_timeout_source_new_seconds() and attaches it to the main loop context
3999 * using g_source_attach(). You can do these steps manually if you need
4000 * greater control. Also see g_timeout_add_seconds_full().
4002 * Note that the first call of the timer may not be precise for timeouts
4003 * of one second. If you need finer precision and have such a timeout,
4004 * you may want to use g_timeout_add() instead.
4006 * The interval given is in terms of monotonic time, not wall clock
4007 * time. See g_get_monotonic_time().
4009 * Return value: the ID (greater than 0) of the event source.
4014 g_timeout_add_seconds (guint interval
,
4015 GSourceFunc function
,
4018 g_return_val_if_fail (function
!= NULL
, 0);
4020 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT
, interval
, function
, data
, NULL
);
4023 /* Child watch functions */
4028 g_child_watch_prepare (GSource
*source
,
4036 g_child_watch_check (GSource
*source
)
4038 GChildWatchSource
*child_watch_source
;
4039 gboolean child_exited
;
4041 child_watch_source
= (GChildWatchSource
*) source
;
4043 child_exited
= child_watch_source
->poll
.revents
& G_IO_IN
;
4050 * Note: We do _not_ check for the special value of STILL_ACTIVE
4051 * since we know that the process has exited and doing so runs into
4052 * problems if the child process "happens to return STILL_ACTIVE(259)"
4053 * as Microsoft's Platform SDK puts it.
4055 if (!GetExitCodeProcess (child_watch_source
->pid
, &child_status
))
4057 gchar
*emsg
= g_win32_error_message (GetLastError ());
4058 g_warning (G_STRLOC
": GetExitCodeProcess() failed: %s", emsg
);
4061 child_watch_source
->child_status
= -1;
4064 child_watch_source
->child_status
= child_status
;
4067 return child_exited
;
4071 g_child_watch_finalize (GSource
*source
)
4075 #else /* G_OS_WIN32 */
4078 wake_source (GSource
*source
)
4080 GMainContext
*context
;
4082 /* This should be thread-safe:
4084 * - if the source is currently being added to a context, that
4085 * context will be woken up anyway
4087 * - if the source is currently being destroyed, we simply need not
4090 * - the memory for the source will remain valid until after the
4091 * source finalize function was called (which would remove the
4092 * source from the global list which we are currently holding the
4095 * - the GMainContext will either be NULL or point to a live
4098 * - the GMainContext will remain valid since we hold the
4099 * main_context_list lock
4101 * Since we are holding a lot of locks here, don't try to enter any
4102 * more GMainContext functions for fear of dealock -- just hit the
4103 * GWakeup and run. Even if that's safe now, it could easily become
4104 * unsafe with some very minor changes in the future, and signal
4105 * handling is not the most well-tested codepath.
4107 G_LOCK(main_context_list
);
4108 context
= source
->context
;
4110 g_wakeup_signal (context
->wakeup
);
4111 G_UNLOCK(main_context_list
);
4115 dispatch_unix_signals (void)
4119 /* clear this first incase another one arrives while we're processing */
4120 any_unix_signal_pending
= FALSE
;
4122 G_LOCK(unix_signal_lock
);
4124 /* handle GChildWatchSource instances */
4125 if (unix_signal_pending
[SIGCHLD
])
4127 unix_signal_pending
[SIGCHLD
] = FALSE
;
4129 /* The only way we can do this is to scan all of the children.
4131 * The docs promise that we will not reap children that we are not
4132 * explicitly watching, so that ties our hands from calling
4133 * waitpid(-1). We also can't use siginfo's si_pid field since if
4134 * multiple SIGCHLD arrive at the same time, one of them can be
4135 * dropped (since a given UNIX signal can only be pending once).
4137 for (node
= unix_child_watches
; node
; node
= node
->next
)
4139 GChildWatchSource
*source
= node
->data
;
4141 if (!source
->child_exited
)
4143 if (waitpid (source
->pid
, &source
->child_status
, WNOHANG
) > 0)
4145 source
->child_exited
= TRUE
;
4147 wake_source ((GSource
*) source
);
4153 /* handle GUnixSignalWatchSource instances */
4154 for (node
= unix_signal_watches
; node
; node
= node
->next
)
4156 GUnixSignalWatchSource
*source
= node
->data
;
4158 if (!source
->pending
)
4160 if (unix_signal_pending
[source
->signum
])
4162 unix_signal_pending
[source
->signum
] = FALSE
;
4163 source
->pending
= TRUE
;
4165 wake_source ((GSource
*) source
);
4170 G_UNLOCK(unix_signal_lock
);
4174 g_child_watch_prepare (GSource
*source
,
4177 GChildWatchSource
*child_watch_source
;
4179 child_watch_source
= (GChildWatchSource
*) source
;
4181 return child_watch_source
->child_exited
;
4185 g_child_watch_check (GSource
*source
)
4187 GChildWatchSource
*child_watch_source
;
4189 child_watch_source
= (GChildWatchSource
*) source
;
4191 return child_watch_source
->child_exited
;
4195 g_unix_signal_watch_prepare (GSource
*source
,
4198 GUnixSignalWatchSource
*unix_signal_source
;
4200 unix_signal_source
= (GUnixSignalWatchSource
*) source
;
4202 return unix_signal_source
->pending
;
4206 g_unix_signal_watch_check (GSource
*source
)
4208 GUnixSignalWatchSource
*unix_signal_source
;
4210 unix_signal_source
= (GUnixSignalWatchSource
*) source
;
4212 return unix_signal_source
->pending
;
4216 g_unix_signal_watch_dispatch (GSource
*source
,
4217 GSourceFunc callback
,
4220 GUnixSignalWatchSource
*unix_signal_source
;
4222 unix_signal_source
= (GUnixSignalWatchSource
*) source
;
4226 g_warning ("Unix signal source dispatched without callback\n"
4227 "You must call g_source_set_callback().");
4231 (callback
) (user_data
);
4233 unix_signal_source
->pending
= FALSE
;
4239 ensure_unix_signal_handler_installed_unlocked (int signum
)
4241 static sigset_t installed_signal_mask
;
4242 static gboolean initialized
;
4243 struct sigaction action
;
4247 sigemptyset (&installed_signal_mask
);
4248 g_get_worker_context ();
4252 if (sigismember (&installed_signal_mask
, signum
))
4255 sigaddset (&installed_signal_mask
, signum
);
4257 action
.sa_handler
= g_unix_signal_handler
;
4258 sigemptyset (&action
.sa_mask
);
4259 action
.sa_flags
= SA_RESTART
| SA_NOCLDSTOP
;
4260 sigaction (signum
, &action
, NULL
);
4264 _g_main_create_unix_signal_watch (int signum
)
4267 GUnixSignalWatchSource
*unix_signal_source
;
4269 source
= g_source_new (&g_unix_signal_funcs
, sizeof (GUnixSignalWatchSource
));
4270 unix_signal_source
= (GUnixSignalWatchSource
*) source
;
4272 unix_signal_source
->signum
= signum
;
4273 unix_signal_source
->pending
= FALSE
;
4275 G_LOCK (unix_signal_lock
);
4276 ensure_unix_signal_handler_installed_unlocked (signum
);
4277 unix_signal_watches
= g_slist_prepend (unix_signal_watches
, unix_signal_source
);
4278 if (unix_signal_pending
[signum
])
4279 unix_signal_source
->pending
= TRUE
;
4280 unix_signal_pending
[signum
] = FALSE
;
4281 G_UNLOCK (unix_signal_lock
);
4287 g_unix_signal_watch_finalize (GSource
*source
)
4289 G_LOCK (unix_signal_lock
);
4290 unix_signal_watches
= g_slist_remove (unix_signal_watches
, source
);
4291 G_UNLOCK (unix_signal_lock
);
4295 g_child_watch_finalize (GSource
*source
)
4297 G_LOCK (unix_signal_lock
);
4298 unix_child_watches
= g_slist_remove (unix_child_watches
, source
);
4299 G_UNLOCK (unix_signal_lock
);
4302 #endif /* G_OS_WIN32 */
4305 g_child_watch_dispatch (GSource
*source
,
4306 GSourceFunc callback
,
4309 GChildWatchSource
*child_watch_source
;
4310 GChildWatchFunc child_watch_callback
= (GChildWatchFunc
) callback
;
4312 child_watch_source
= (GChildWatchSource
*) source
;
4316 g_warning ("Child watch source dispatched without callback\n"
4317 "You must call g_source_set_callback().");
4321 (child_watch_callback
) (child_watch_source
->pid
, child_watch_source
->child_status
, user_data
);
4323 /* We never keep a child watch source around as the child is gone */
4330 g_unix_signal_handler (int signum
)
4332 unix_signal_pending
[signum
] = TRUE
;
4333 any_unix_signal_pending
= TRUE
;
4335 g_wakeup_signal (glib_worker_context
->wakeup
);
4338 #endif /* !G_OS_WIN32 */
4341 * g_child_watch_source_new:
4342 * @pid: process to watch. On POSIX the pid of a child process. On
4343 * Windows a handle for a process (which doesn't have to be a child).
4345 * Creates a new child_watch source.
4347 * The source will not initially be associated with any #GMainContext
4348 * and must be added to one with g_source_attach() before it will be
4351 * Note that child watch sources can only be used in conjunction with
4352 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4355 * Note that on platforms where #GPid must be explicitly closed
4356 * (see g_spawn_close_pid()) @pid must not be closed while the
4357 * source is still active. Typically, you will want to call
4358 * g_spawn_close_pid() in the callback function for the source.
4360 * Note further that using g_child_watch_source_new() is not
4361 * compatible with calling <literal>waitpid(-1)</literal> in
4362 * the application. Calling waitpid() for individual pids will
4365 * Return value: the newly-created child watch source
4370 g_child_watch_source_new (GPid pid
)
4372 GSource
*source
= g_source_new (&g_child_watch_funcs
, sizeof (GChildWatchSource
));
4373 GChildWatchSource
*child_watch_source
= (GChildWatchSource
*)source
;
4375 child_watch_source
->pid
= pid
;
4378 child_watch_source
->poll
.fd
= (gintptr
) pid
;
4379 child_watch_source
->poll
.events
= G_IO_IN
;
4381 g_source_add_poll (source
, &child_watch_source
->poll
);
4382 #else /* G_OS_WIN32 */
4383 G_LOCK (unix_signal_lock
);
4384 ensure_unix_signal_handler_installed_unlocked (SIGCHLD
);
4385 unix_child_watches
= g_slist_prepend (unix_child_watches
, child_watch_source
);
4386 if (waitpid (pid
, &child_watch_source
->child_status
, WNOHANG
) > 0)
4387 child_watch_source
->child_exited
= TRUE
;
4388 G_UNLOCK (unix_signal_lock
);
4389 #endif /* G_OS_WIN32 */
4395 * g_child_watch_add_full:
4396 * @priority: the priority of the idle source. Typically this will be in the
4397 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4398 * @pid: process to watch. On POSIX the pid of a child process. On
4399 * Windows a handle for a process (which doesn't have to be a child).
4400 * @function: function to call
4401 * @data: data to pass to @function
4402 * @notify: function to call when the idle is removed, or %NULL
4404 * Sets a function to be called when the child indicated by @pid
4405 * exits, at the priority @priority.
4407 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4408 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4409 * the spawn function for the child watching to work.
4411 * Note that on platforms where #GPid must be explicitly closed
4412 * (see g_spawn_close_pid()) @pid must not be closed while the
4413 * source is still active. Typically, you will want to call
4414 * g_spawn_close_pid() in the callback function for the source.
4416 * GLib supports only a single callback per process id.
4418 * This internally creates a main loop source using
4419 * g_child_watch_source_new() and attaches it to the main loop context
4420 * using g_source_attach(). You can do these steps manually if you
4421 * need greater control.
4423 * Return value: the ID (greater than 0) of the event source.
4425 * Rename to: g_child_watch_add
4429 g_child_watch_add_full (gint priority
,
4431 GChildWatchFunc function
,
4433 GDestroyNotify notify
)
4438 g_return_val_if_fail (function
!= NULL
, 0);
4440 source
= g_child_watch_source_new (pid
);
4442 if (priority
!= G_PRIORITY_DEFAULT
)
4443 g_source_set_priority (source
, priority
);
4445 g_source_set_callback (source
, (GSourceFunc
) function
, data
, notify
);
4446 id
= g_source_attach (source
, NULL
);
4447 g_source_unref (source
);
4453 * g_child_watch_add:
4454 * @pid: process id to watch. On POSIX the pid of a child process. On
4455 * Windows a handle for a process (which doesn't have to be a child).
4456 * @function: function to call
4457 * @data: data to pass to @function
4459 * Sets a function to be called when the child indicated by @pid
4460 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4462 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4463 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4464 * the spawn function for the child watching to work.
4466 * Note that on platforms where #GPid must be explicitly closed
4467 * (see g_spawn_close_pid()) @pid must not be closed while the
4468 * source is still active. Typically, you will want to call
4469 * g_spawn_close_pid() in the callback function for the source.
4471 * GLib supports only a single callback per process id.
4473 * This internally creates a main loop source using
4474 * g_child_watch_source_new() and attaches it to the main loop context
4475 * using g_source_attach(). You can do these steps manually if you
4476 * need greater control.
4478 * Return value: the ID (greater than 0) of the event source.
4483 g_child_watch_add (GPid pid
,
4484 GChildWatchFunc function
,
4487 return g_child_watch_add_full (G_PRIORITY_DEFAULT
, pid
, function
, data
, NULL
);
4491 /* Idle functions */
4494 g_idle_prepare (GSource
*source
,
4503 g_idle_check (GSource
*source
)
4509 g_idle_dispatch (GSource
*source
,
4510 GSourceFunc callback
,
4515 g_warning ("Idle source dispatched without callback\n"
4516 "You must call g_source_set_callback().");
4520 return callback (user_data
);
4524 * g_idle_source_new:
4526 * Creates a new idle source.
4528 * The source will not initially be associated with any #GMainContext
4529 * and must be added to one with g_source_attach() before it will be
4530 * executed. Note that the default priority for idle sources is
4531 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4532 * have a default priority of %G_PRIORITY_DEFAULT.
4534 * Return value: the newly-created idle source
4537 g_idle_source_new (void)
4541 source
= g_source_new (&g_idle_funcs
, sizeof (GSource
));
4542 g_source_set_priority (source
, G_PRIORITY_DEFAULT_IDLE
);
4549 * @priority: the priority of the idle source. Typically this will be in the
4550 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4551 * @function: function to call
4552 * @data: data to pass to @function
4553 * @notify: function to call when the idle is removed, or %NULL
4555 * Adds a function to be called whenever there are no higher priority
4556 * events pending. If the function returns %FALSE it is automatically
4557 * removed from the list of event sources and will not be called again.
4559 * This internally creates a main loop source using g_idle_source_new()
4560 * and attaches it to the main loop context using g_source_attach().
4561 * You can do these steps manually if you need greater control.
4563 * Return value: the ID (greater than 0) of the event source.
4564 * Rename to: g_idle_add
4567 g_idle_add_full (gint priority
,
4568 GSourceFunc function
,
4570 GDestroyNotify notify
)
4575 g_return_val_if_fail (function
!= NULL
, 0);
4577 source
= g_idle_source_new ();
4579 if (priority
!= G_PRIORITY_DEFAULT_IDLE
)
4580 g_source_set_priority (source
, priority
);
4582 g_source_set_callback (source
, function
, data
, notify
);
4583 id
= g_source_attach (source
, NULL
);
4584 g_source_unref (source
);
4591 * @function: function to call
4592 * @data: data to pass to @function.
4594 * Adds a function to be called whenever there are no higher priority
4595 * events pending to the default main loop. The function is given the
4596 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4597 * returns %FALSE it is automatically removed from the list of event
4598 * sources and will not be called again.
4600 * This internally creates a main loop source using g_idle_source_new()
4601 * and attaches it to the main loop context using g_source_attach().
4602 * You can do these steps manually if you need greater control.
4604 * Return value: the ID (greater than 0) of the event source.
4607 g_idle_add (GSourceFunc function
,
4610 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE
, function
, data
, NULL
);
4614 * g_idle_remove_by_data:
4615 * @data: the data for the idle source's callback.
4617 * Removes the idle function with the given data.
4619 * Return value: %TRUE if an idle source was found and removed.
4622 g_idle_remove_by_data (gpointer data
)
4624 return g_source_remove_by_funcs_user_data (&g_idle_funcs
, data
);
4628 * g_main_context_invoke:
4629 * @context: (allow-none): a #GMainContext, or %NULL
4630 * @function: function to call
4631 * @data: data to pass to @function
4633 * Invokes a function in such a way that @context is owned during the
4634 * invocation of @function.
4636 * If @context is %NULL then the global default main context — as
4637 * returned by g_main_context_default() — is used.
4639 * If @context is owned by the current thread, @function is called
4640 * directly. Otherwise, if @context is the thread-default main context
4641 * of the current thread and g_main_context_acquire() succeeds, then
4642 * @function is called and g_main_context_release() is called
4645 * In any other case, an idle source is created to call @function and
4646 * that source is attached to @context (presumably to be run in another
4647 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
4648 * priority. If you want a different priority, use
4649 * g_main_context_invoke_full().
4651 * Note that, as with normal idle functions, @function should probably
4652 * return %FALSE. If it returns %TRUE, it will be continuously run in a
4653 * loop (and may prevent this call from returning).
4658 g_main_context_invoke (GMainContext
*context
,
4659 GSourceFunc function
,
4662 g_main_context_invoke_full (context
,
4664 function
, data
, NULL
);
4668 * g_main_context_invoke_full:
4669 * @context: (allow-none): a #GMainContext, or %NULL
4670 * @priority: the priority at which to run @function
4671 * @function: function to call
4672 * @data: data to pass to @function
4673 * @notify: a function to call when @data is no longer in use, or %NULL.
4675 * Invokes a function in such a way that @context is owned during the
4676 * invocation of @function.
4678 * This function is the same as g_main_context_invoke() except that it
4679 * lets you specify the priority incase @function ends up being
4680 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
4682 * @notify should not assume that it is called from any particular
4683 * thread or with any particular context acquired.
4688 g_main_context_invoke_full (GMainContext
*context
,
4690 GSourceFunc function
,
4692 GDestroyNotify notify
)
4694 g_return_if_fail (function
!= NULL
);
4697 context
= g_main_context_default ();
4699 if (g_main_context_is_owner (context
))
4701 while (function (data
));
4708 GMainContext
*thread_default
;
4710 thread_default
= g_main_context_get_thread_default ();
4712 if (!thread_default
)
4713 thread_default
= g_main_context_default ();
4715 if (thread_default
== context
&& g_main_context_acquire (context
))
4717 while (function (data
));
4719 g_main_context_release (context
);
4728 source
= g_idle_source_new ();
4729 g_source_set_priority (source
, priority
);
4730 g_source_set_callback (source
, function
, data
, notify
);
4731 g_source_attach (source
, context
);
4732 g_source_unref (source
);
4738 glib_worker_main (gpointer data
)
4742 g_main_context_iteration (glib_worker_context
, TRUE
);
4745 if (any_unix_signal_pending
)
4746 dispatch_unix_signals ();
4750 return NULL
; /* worst GCC warning message ever... */
4754 g_get_worker_context (void)
4756 static gsize initialised
;
4758 if (g_once_init_enter (&initialised
))
4760 /* mask all signals in the worker thread */
4766 pthread_sigmask (SIG_SETMASK
, &all
, &prev_mask
);
4768 glib_worker_context
= g_main_context_new ();
4769 g_thread_new ("gmain", glib_worker_main
, NULL
);
4771 pthread_sigmask (SIG_SETMASK
, &prev_mask
, NULL
);
4773 g_once_init_leave (&initialised
, TRUE
);
4776 return glib_worker_context
;