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
100 #include "gmain-internal.h"
101 #include "glib-init.h"
102 #include "glib-private.h"
106 * @title: The Main Event Loop
107 * @short_description: manages all available sources of events
109 * The main event loop manages all the available sources of events for
110 * GLib and GTK+ applications. These events can come from any number of
111 * different types of sources such as file descriptors (plain files,
112 * pipes or sockets) and timeouts. New types of event sources can also
113 * be added using g_source_attach().
115 * To allow multiple independent sets of sources to be handled in
116 * different threads, each source is associated with a #GMainContext.
117 * A GMainContext can only be running in a single thread, but
118 * sources can be added to it and removed from it from other threads.
120 * Each event source is assigned a priority. The default priority,
121 * #G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
122 * Values greater than 0 denote lower priorities. Events from high priority
123 * sources are always processed before events from lower priority sources.
125 * Idle functions can also be added, and assigned a priority. These will
126 * be run whenever no events with a higher priority are ready to be processed.
128 * The #GMainLoop data type represents a main event loop. A GMainLoop is
129 * created with g_main_loop_new(). After adding the initial event sources,
130 * g_main_loop_run() is called. This continuously checks for new events from
131 * each of the event sources and dispatches them. Finally, the processing of
132 * an event from one of the sources leads to a call to g_main_loop_quit() to
133 * exit the main loop, and g_main_loop_run() returns.
135 * It is possible to create new instances of #GMainLoop recursively.
136 * This is often used in GTK+ applications when showing modal dialog
137 * boxes. Note that event sources are associated with a particular
138 * #GMainContext, and will be checked and dispatched for all main
139 * loops associated with that GMainContext.
141 * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
142 * gtk_main_quit() and gtk_events_pending().
144 * <refsect2><title>Creating new source types</title>
145 * <para>One of the unusual features of the #GMainLoop functionality
146 * is that new types of event source can be created and used in
147 * addition to the builtin type of event source. A new event source
148 * type is used for handling GDK events. A new source type is created
149 * by <firstterm>deriving</firstterm> from the #GSource structure.
150 * The derived type of source is represented by a structure that has
151 * the #GSource structure as a first element, and other elements specific
152 * to the new source type. To create an instance of the new source type,
153 * call g_source_new() passing in the size of the derived structure and
154 * a table of functions. These #GSourceFuncs determine the behavior of
155 * the new source type.</para>
156 * <para>New source types basically interact with the main context
157 * in two ways. Their prepare function in #GSourceFuncs can set a timeout
158 * to determine the maximum amount of time that the main loop will sleep
159 * before checking the source again. In addition, or as well, the source
160 * can add file descriptors to the set that the main context checks using
161 * g_source_add_poll().</para>
163 * <refsect2><title>Customizing the main loop iteration</title>
164 * <para>Single iterations of a #GMainContext can be run with
165 * g_main_context_iteration(). In some cases, more detailed control
166 * of exactly how the details of the main loop work is desired, for
167 * instance, when integrating the #GMainLoop with an external main loop.
168 * In such cases, you can call the component functions of
169 * g_main_context_iteration() directly. These functions are
170 * g_main_context_prepare(), g_main_context_query(),
171 * g_main_context_check() and g_main_context_dispatch().</para>
172 * <para>The operation of these functions can best be seen in terms
173 * of a state diagram, as shown in <xref linkend="mainloop-states"/>.</para>
174 * <figure id="mainloop-states"><title>States of a Main Context</title>
175 * <graphic fileref="mainloop-states.gif" format="GIF"></graphic>
179 * On Unix, the GLib mainloop is incompatible with fork(). Any program
180 * using the mainloop must either exec() or exit() from the child
181 * without returning to the mainloop.
186 typedef struct _GTimeoutSource GTimeoutSource
;
187 typedef struct _GChildWatchSource GChildWatchSource
;
188 typedef struct _GUnixSignalWatchSource GUnixSignalWatchSource
;
189 typedef struct _GPollRec GPollRec
;
190 typedef struct _GSourceCallback GSourceCallback
;
194 G_SOURCE_READY
= 1 << G_HOOK_FLAG_USER_SHIFT
,
195 G_SOURCE_CAN_RECURSE
= 1 << (G_HOOK_FLAG_USER_SHIFT
+ 1),
196 G_SOURCE_BLOCKED
= 1 << (G_HOOK_FLAG_USER_SHIFT
+ 2)
199 typedef struct _GSourceList GSourceList
;
203 GSource
*head
, *tail
;
207 typedef struct _GMainWaiter GMainWaiter
;
215 typedef struct _GMainDispatch GMainDispatch
;
217 struct _GMainDispatch
220 GSList
*dispatching_sources
; /* stack of current sources */
223 #ifdef G_MAIN_POLL_DEBUG
224 gboolean _g_main_poll_debug
= FALSE
;
229 /* The following lock is used for both the list of sources
230 * and the list of poll records
240 GPtrArray
*pending_dispatches
;
241 gint timeout
; /* Timeout for current iteration */
244 GHashTable
*overflow_used_source_ids
; /* set<guint> */
246 gint in_check_or_prepare
;
248 GPollRec
*poll_records
, *poll_records_tail
;
249 guint n_poll_records
;
250 GPollFD
*cached_poll_array
;
251 guint cached_poll_array_size
;
257 /* Flag indicating whether the set of fd's changed during a poll */
258 gboolean poll_changed
;
263 gboolean time_is_fresh
;
266 struct _GSourceCallback
271 GDestroyNotify notify
;
276 GMainContext
*context
;
281 struct _GTimeoutSource
288 struct _GChildWatchSource
295 #else /* G_OS_WIN32 */
296 gboolean child_exited
;
297 #endif /* G_OS_WIN32 */
300 struct _GUnixSignalWatchSource
315 struct _GSourcePrivate
317 GSList
*child_sources
;
318 GSource
*parent_source
;
322 /* This is currently only used on UNIX, but we always declare it (and
323 * let it remain empty on Windows) to avoid #ifdef all over the place.
328 typedef struct _GSourceIter
330 GMainContext
*context
;
336 #define LOCK_CONTEXT(context) g_mutex_lock (&context->mutex)
337 #define UNLOCK_CONTEXT(context) g_mutex_unlock (&context->mutex)
338 #define G_THREAD_SELF g_thread_self ()
340 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
341 #define SOURCE_BLOCKED(source) (((source)->flags & G_SOURCE_BLOCKED) != 0)
343 #define SOURCE_UNREF(source, context) \
345 if ((source)->ref_count > 1) \
346 (source)->ref_count--; \
348 g_source_unref_internal ((source), (context), TRUE); \
352 /* Forward declarations */
354 static void g_source_unref_internal (GSource
*source
,
355 GMainContext
*context
,
357 static void g_source_destroy_internal (GSource
*source
,
358 GMainContext
*context
,
360 static void g_source_set_priority_unlocked (GSource
*source
,
361 GMainContext
*context
,
363 static void g_child_source_remove_internal (GSource
*child_source
,
364 GMainContext
*context
);
366 static void g_main_context_poll (GMainContext
*context
,
371 static void g_main_context_add_poll_unlocked (GMainContext
*context
,
374 static void g_main_context_remove_poll_unlocked (GMainContext
*context
,
377 static void g_source_iter_init (GSourceIter
*iter
,
378 GMainContext
*context
,
379 gboolean may_modify
);
380 static gboolean
g_source_iter_next (GSourceIter
*iter
,
382 static void g_source_iter_clear (GSourceIter
*iter
);
384 static gboolean
g_timeout_dispatch (GSource
*source
,
385 GSourceFunc callback
,
387 static gboolean
g_child_watch_prepare (GSource
*source
,
389 static gboolean
g_child_watch_check (GSource
*source
);
390 static gboolean
g_child_watch_dispatch (GSource
*source
,
391 GSourceFunc callback
,
393 static void g_child_watch_finalize (GSource
*source
);
395 static void g_unix_signal_handler (int signum
);
396 static gboolean
g_unix_signal_watch_prepare (GSource
*source
,
398 static gboolean
g_unix_signal_watch_check (GSource
*source
);
399 static gboolean
g_unix_signal_watch_dispatch (GSource
*source
,
400 GSourceFunc callback
,
402 static void g_unix_signal_watch_finalize (GSource
*source
);
404 static gboolean
g_idle_prepare (GSource
*source
,
406 static gboolean
g_idle_check (GSource
*source
);
407 static gboolean
g_idle_dispatch (GSource
*source
,
408 GSourceFunc callback
,
411 static void block_source (GSource
*source
);
413 static GMainContext
*glib_worker_context
;
415 G_LOCK_DEFINE_STATIC (main_loop
);
416 static GMainContext
*default_main_context
;
421 /* UNIX signals work by marking one of these variables then waking the
422 * worker context to check on them and dispatch accordingly.
424 #ifdef HAVE_SIG_ATOMIC_T
425 static volatile sig_atomic_t unix_signal_pending
[NSIG
];
426 static volatile sig_atomic_t any_unix_signal_pending
;
428 static volatile int unix_signal_pending
[NSIG
];
429 static volatile int any_unix_signal_pending
;
432 /* Guards all the data below */
433 G_LOCK_DEFINE_STATIC (unix_signal_lock
);
434 static GSList
*unix_signal_watches
;
435 static GSList
*unix_child_watches
;
437 static GSourceFuncs g_unix_signal_funcs
=
439 g_unix_signal_watch_prepare
,
440 g_unix_signal_watch_check
,
441 g_unix_signal_watch_dispatch
,
442 g_unix_signal_watch_finalize
444 #endif /* !G_OS_WIN32 */
445 G_LOCK_DEFINE_STATIC (main_context_list
);
446 static GSList
*main_context_list
= NULL
;
448 GSourceFuncs g_timeout_funcs
=
456 GSourceFuncs g_child_watch_funcs
=
458 g_child_watch_prepare
,
460 g_child_watch_dispatch
,
461 g_child_watch_finalize
464 GSourceFuncs g_idle_funcs
=
473 * g_main_context_ref:
474 * @context: a #GMainContext
476 * Increases the reference count on a #GMainContext object by one.
478 * Returns: the @context that was passed in (since 2.6)
481 g_main_context_ref (GMainContext
*context
)
483 g_return_val_if_fail (context
!= NULL
, NULL
);
484 g_return_val_if_fail (g_atomic_int_get (&context
->ref_count
) > 0, NULL
);
486 g_atomic_int_inc (&context
->ref_count
);
492 poll_rec_list_free (GMainContext
*context
,
495 g_slice_free_chain (GPollRec
, list
, next
);
499 * g_main_context_unref:
500 * @context: a #GMainContext
502 * Decreases the reference count on a #GMainContext object by one. If
503 * the result is zero, free the context and free all associated memory.
506 g_main_context_unref (GMainContext
*context
)
513 g_return_if_fail (context
!= NULL
);
514 g_return_if_fail (g_atomic_int_get (&context
->ref_count
) > 0);
516 if (!g_atomic_int_dec_and_test (&context
->ref_count
))
519 G_LOCK (main_context_list
);
520 main_context_list
= g_slist_remove (main_context_list
, context
);
521 G_UNLOCK (main_context_list
);
523 /* g_source_iter_next() assumes the context is locked. */
524 LOCK_CONTEXT (context
);
525 g_source_iter_init (&iter
, context
, TRUE
);
526 while (g_source_iter_next (&iter
, &source
))
528 source
->context
= NULL
;
529 g_source_destroy_internal (source
, context
, TRUE
);
531 UNLOCK_CONTEXT (context
);
533 for (sl_iter
= context
->source_lists
; sl_iter
; sl_iter
= sl_iter
->next
)
535 list
= sl_iter
->data
;
536 g_slice_free (GSourceList
, list
);
538 g_list_free (context
->source_lists
);
540 if (context
->overflow_used_source_ids
)
541 g_hash_table_destroy (context
->overflow_used_source_ids
);
543 g_mutex_clear (&context
->mutex
);
545 g_ptr_array_free (context
->pending_dispatches
, TRUE
);
546 g_free (context
->cached_poll_array
);
548 poll_rec_list_free (context
, context
->poll_records
);
550 g_wakeup_free (context
->wakeup
);
551 g_cond_clear (&context
->cond
);
556 /* Helper function used by mainloop/overflow test.
559 g_main_context_new_with_next_id (guint next_id
)
561 GMainContext
*ret
= g_main_context_new ();
563 ret
->next_id
= next_id
;
569 * g_main_context_new:
571 * Creates a new #GMainContext structure.
573 * Return value: the new #GMainContext
576 g_main_context_new (void)
578 static gsize initialised
;
579 GMainContext
*context
;
581 if (g_once_init_enter (&initialised
))
583 #ifdef G_MAIN_POLL_DEBUG
584 if (getenv ("G_MAIN_POLL_DEBUG") != NULL
)
585 _g_main_poll_debug
= TRUE
;
588 g_once_init_leave (&initialised
, TRUE
);
591 context
= g_new0 (GMainContext
, 1);
593 g_mutex_init (&context
->mutex
);
594 g_cond_init (&context
->cond
);
596 context
->owner
= NULL
;
597 context
->waiters
= NULL
;
599 context
->ref_count
= 1;
601 context
->next_id
= 1;
603 context
->source_lists
= NULL
;
605 context
->poll_func
= g_poll
;
607 context
->cached_poll_array
= NULL
;
608 context
->cached_poll_array_size
= 0;
610 context
->pending_dispatches
= g_ptr_array_new ();
612 context
->time_is_fresh
= FALSE
;
614 context
->wakeup
= g_wakeup_new ();
615 g_wakeup_get_pollfd (context
->wakeup
, &context
->wake_up_rec
);
616 g_main_context_add_poll_unlocked (context
, 0, &context
->wake_up_rec
);
618 G_LOCK (main_context_list
);
619 main_context_list
= g_slist_append (main_context_list
, context
);
621 #ifdef G_MAIN_POLL_DEBUG
622 if (_g_main_poll_debug
)
623 g_print ("created context=%p\n", context
);
626 G_UNLOCK (main_context_list
);
632 * g_main_context_default:
634 * Returns the global default main context. This is the main context
635 * used for main loop functions when a main loop is not explicitly
636 * specified, and corresponds to the "main" main loop. See also
637 * g_main_context_get_thread_default().
639 * Return value: (transfer none): the global default main context.
642 g_main_context_default (void)
648 if (!default_main_context
)
650 default_main_context
= g_main_context_new ();
651 #ifdef G_MAIN_POLL_DEBUG
652 if (_g_main_poll_debug
)
653 g_print ("default context=%p\n", default_main_context
);
657 G_UNLOCK (main_loop
);
659 return default_main_context
;
663 free_context (gpointer data
)
665 GMainContext
*context
= data
;
667 g_main_context_release (context
);
669 g_main_context_unref (context
);
673 free_context_stack (gpointer data
)
675 g_queue_free_full((GQueue
*) data
, (GDestroyNotify
) free_context
);
678 static GPrivate thread_context_stack
= G_PRIVATE_INIT (free_context_stack
);
681 * g_main_context_push_thread_default:
682 * @context: (allow-none): a #GMainContext, or %NULL for the global default context
684 * Acquires @context and sets it as the thread-default context for the
685 * current thread. This will cause certain asynchronous operations
686 * (such as most <link linkend="gio">gio</link>-based I/O) which are
687 * started in this thread to run under @context and deliver their
688 * results to its main loop, rather than running under the global
689 * default context in the main thread. Note that calling this function
690 * changes the context returned by
691 * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
692 * one returned by g_main_context_default(), so it does not affect the
693 * context used by functions like g_idle_add().
695 * Normally you would call this function shortly after creating a new
696 * thread, passing it a #GMainContext which will be run by a
697 * #GMainLoop in that thread, to set a new default context for all
698 * async operations in that thread. (In this case, you don't need to
699 * ever call g_main_context_pop_thread_default().) In some cases
700 * however, you may want to schedule a single operation in a
701 * non-default context, or temporarily use a non-default context in
702 * the main thread. In that case, you can wrap the call to the
703 * asynchronous operation inside a
704 * g_main_context_push_thread_default() /
705 * g_main_context_pop_thread_default() pair, but it is up to you to
706 * ensure that no other asynchronous operations accidentally get
707 * started while the non-default context is active.
709 * Beware that libraries that predate this function may not correctly
710 * handle being used from a thread with a thread-default context. Eg,
711 * see g_file_supports_thread_contexts().
716 g_main_context_push_thread_default (GMainContext
*context
)
719 gboolean acquired_context
;
721 acquired_context
= g_main_context_acquire (context
);
722 g_return_if_fail (acquired_context
);
724 if (context
== g_main_context_default ())
727 g_main_context_ref (context
);
729 stack
= g_private_get (&thread_context_stack
);
732 stack
= g_queue_new ();
733 g_private_set (&thread_context_stack
, stack
);
736 g_queue_push_head (stack
, context
);
740 * g_main_context_pop_thread_default:
741 * @context: (allow-none): a #GMainContext object, or %NULL
743 * Pops @context off the thread-default context stack (verifying that
744 * it was on the top of the stack).
749 g_main_context_pop_thread_default (GMainContext
*context
)
753 if (context
== g_main_context_default ())
756 stack
= g_private_get (&thread_context_stack
);
758 g_return_if_fail (stack
!= NULL
);
759 g_return_if_fail (g_queue_peek_head (stack
) == context
);
761 g_queue_pop_head (stack
);
763 g_main_context_release (context
);
765 g_main_context_unref (context
);
769 * g_main_context_get_thread_default:
771 * Gets the thread-default #GMainContext for this thread. Asynchronous
772 * operations that want to be able to be run in contexts other than
773 * the default one should call this method or
774 * g_main_context_ref_thread_default() to get a #GMainContext to add
775 * their #GSource<!-- -->s to. (Note that even in single-threaded
776 * programs applications may sometimes want to temporarily push a
777 * non-default context, so it is not safe to assume that this will
778 * always return %NULL if you are running in the default thread.)
780 * If you need to hold a reference on the context, use
781 * g_main_context_ref_thread_default() instead.
783 * Returns: (transfer none): the thread-default #GMainContext, or
784 * %NULL if the thread-default context is the global default context.
789 g_main_context_get_thread_default (void)
793 stack
= g_private_get (&thread_context_stack
);
795 return g_queue_peek_head (stack
);
801 * g_main_context_ref_thread_default:
803 * Gets the thread-default #GMainContext for this thread, as with
804 * g_main_context_get_thread_default(), but also adds a reference to
805 * it with g_main_context_ref(). In addition, unlike
806 * g_main_context_get_thread_default(), if the thread-default context
807 * is the global default context, this will return that #GMainContext
808 * (with a ref added to it) rather than returning %NULL.
810 * Returns: (transfer full): the thread-default #GMainContext. Unref
811 * with g_main_context_unref() when you are done with it.
816 g_main_context_ref_thread_default (void)
818 GMainContext
*context
;
820 context
= g_main_context_get_thread_default ();
822 context
= g_main_context_default ();
823 return g_main_context_ref (context
);
826 /* Hooks for adding to the main loop */
830 * @source_funcs: structure containing functions that implement
831 * the sources behavior.
832 * @struct_size: size of the #GSource structure to create.
834 * Creates a new #GSource structure. The size is specified to
835 * allow creating structures derived from #GSource that contain
836 * additional data. The size passed in must be at least
837 * <literal>sizeof (GSource)</literal>.
839 * The source will not initially be associated with any #GMainContext
840 * and must be added to one with g_source_attach() before it will be
843 * Return value: the newly-created #GSource.
846 g_source_new (GSourceFuncs
*source_funcs
,
851 g_return_val_if_fail (source_funcs
!= NULL
, NULL
);
852 g_return_val_if_fail (struct_size
>= sizeof (GSource
), NULL
);
854 source
= (GSource
*) g_malloc0 (struct_size
);
855 source
->priv
= g_slice_new0 (GSourcePrivate
);
856 source
->source_funcs
= source_funcs
;
857 source
->ref_count
= 1;
859 source
->priority
= G_PRIORITY_DEFAULT
;
861 source
->flags
= G_HOOK_FLAG_ACTIVE
;
863 source
->priv
->ready_time
= -1;
865 /* NULL/0 initialization for all other fields */
870 /* Holds context's lock */
872 g_source_iter_init (GSourceIter
*iter
,
873 GMainContext
*context
,
876 iter
->context
= context
;
877 iter
->current_list
= NULL
;
879 iter
->may_modify
= may_modify
;
882 /* Holds context's lock */
884 g_source_iter_next (GSourceIter
*iter
, GSource
**source
)
886 GSource
*next_source
;
889 next_source
= iter
->source
->next
;
895 if (iter
->current_list
)
896 iter
->current_list
= iter
->current_list
->next
;
898 iter
->current_list
= iter
->context
->source_lists
;
900 if (iter
->current_list
)
902 GSourceList
*source_list
= iter
->current_list
->data
;
904 next_source
= source_list
->head
;
908 /* Note: unreffing iter->source could potentially cause its
909 * GSourceList to be removed from source_lists (if iter->source is
910 * the only source in its list, and it is destroyed), so we have to
911 * keep it reffed until after we advance iter->current_list, above.
914 if (iter
->source
&& iter
->may_modify
)
915 SOURCE_UNREF (iter
->source
, iter
->context
);
916 iter
->source
= next_source
;
917 if (iter
->source
&& iter
->may_modify
)
918 iter
->source
->ref_count
++;
920 *source
= iter
->source
;
921 return *source
!= NULL
;
924 /* Holds context's lock. Only necessary to call if you broke out of
925 * the g_source_iter_next() loop early.
928 g_source_iter_clear (GSourceIter
*iter
)
930 if (iter
->source
&& iter
->may_modify
)
932 SOURCE_UNREF (iter
->source
, iter
->context
);
937 /* Holds context's lock
940 find_source_list_for_priority (GMainContext
*context
,
945 GSourceList
*source_list
;
948 for (iter
= context
->source_lists
; iter
!= NULL
; last
= iter
, iter
= iter
->next
)
950 source_list
= iter
->data
;
952 if (source_list
->priority
== priority
)
955 if (source_list
->priority
> priority
)
960 source_list
= g_slice_new0 (GSourceList
);
961 source_list
->priority
= priority
;
962 context
->source_lists
= g_list_insert_before (context
->source_lists
,
972 source_list
= g_slice_new0 (GSourceList
);
973 source_list
->priority
= priority
;
976 context
->source_lists
= g_list_append (NULL
, source_list
);
979 /* This just appends source_list to the end of
980 * context->source_lists without having to walk the list again.
982 last
= g_list_append (last
, source_list
);
987 /* Holds context's lock
990 source_add_to_context (GSource
*source
,
991 GMainContext
*context
)
993 GSourceList
*source_list
;
994 GSource
*prev
, *next
;
996 source_list
= find_source_list_for_priority (context
, source
->priority
, TRUE
);
998 if (source
->priv
->parent_source
)
1000 g_assert (source_list
->head
!= NULL
);
1002 /* Put the source immediately before its parent */
1003 prev
= source
->priv
->parent_source
->prev
;
1004 next
= source
->priv
->parent_source
;
1008 prev
= source_list
->tail
;
1012 source
->next
= next
;
1014 next
->prev
= source
;
1016 source_list
->tail
= source
;
1018 source
->prev
= prev
;
1020 prev
->next
= source
;
1022 source_list
->head
= source
;
1025 /* Holds context's lock
1028 source_remove_from_context (GSource
*source
,
1029 GMainContext
*context
)
1031 GSourceList
*source_list
;
1033 source_list
= find_source_list_for_priority (context
, source
->priority
, FALSE
);
1034 g_return_if_fail (source_list
!= NULL
);
1037 source
->prev
->next
= source
->next
;
1039 source_list
->head
= source
->next
;
1042 source
->next
->prev
= source
->prev
;
1044 source_list
->tail
= source
->prev
;
1046 source
->prev
= NULL
;
1047 source
->next
= NULL
;
1049 if (source_list
->head
== NULL
)
1051 context
->source_lists
= g_list_remove (context
->source_lists
, source_list
);
1052 g_slice_free (GSourceList
, source_list
);
1055 if (context
->overflow_used_source_ids
)
1056 g_hash_table_remove (context
->overflow_used_source_ids
,
1057 GUINT_TO_POINTER (source
->source_id
));
1062 assign_source_id_unlocked (GMainContext
*context
,
1067 /* Are we about to overflow back to 0?
1068 * See https://bugzilla.gnome.org/show_bug.cgi?id=687098
1070 if (G_UNLIKELY (context
->next_id
== G_MAXUINT
&&
1071 context
->overflow_used_source_ids
== NULL
))
1076 context
->overflow_used_source_ids
= g_hash_table_new (NULL
, NULL
);
1078 g_source_iter_init (&iter
, context
, FALSE
);
1079 while (g_source_iter_next (&iter
, &source
))
1081 g_hash_table_add (context
->overflow_used_source_ids
,
1082 GUINT_TO_POINTER (source
->source_id
));
1086 else if (context
->overflow_used_source_ids
== NULL
)
1088 id
= context
->next_id
++;
1093 * If we overran G_MAXUINT, we fall back to randomly probing the
1094 * source ids for the current context. This will be slower the more
1095 * sources there are, but we're mainly concerned right now about
1096 * correctness and code size. There's time for a more clever solution
1100 id
= g_random_int ();
1102 g_hash_table_contains (context
->overflow_used_source_ids
,
1103 GUINT_TO_POINTER (id
)));
1104 g_hash_table_add (context
->overflow_used_source_ids
, GUINT_TO_POINTER (id
));
1107 source
->source_id
= id
;
1111 g_source_attach_unlocked (GSource
*source
,
1112 GMainContext
*context
)
1116 source
->context
= context
;
1117 assign_source_id_unlocked (context
, source
);
1118 source
->ref_count
++;
1119 source_add_to_context (source
, context
);
1121 tmp_list
= source
->poll_fds
;
1124 g_main_context_add_poll_unlocked (context
, source
->priority
, tmp_list
->data
);
1125 tmp_list
= tmp_list
->next
;
1128 for (tmp_list
= source
->priv
->fds
; tmp_list
; tmp_list
= tmp_list
->next
)
1129 g_main_context_add_poll_unlocked (context
, source
->priority
, tmp_list
->data
);
1131 tmp_list
= source
->priv
->child_sources
;
1134 g_source_attach_unlocked (tmp_list
->data
, context
);
1135 tmp_list
= tmp_list
->next
;
1138 return source
->source_id
;
1143 * @source: a #GSource
1144 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
1146 * Adds a #GSource to a @context so that it will be executed within
1147 * that context. Remove it by calling g_source_destroy().
1149 * Return value: the ID (greater than 0) for the source within the
1153 g_source_attach (GSource
*source
,
1154 GMainContext
*context
)
1158 g_return_val_if_fail (source
->context
== NULL
, 0);
1159 g_return_val_if_fail (!SOURCE_DESTROYED (source
), 0);
1162 context
= g_main_context_default ();
1164 LOCK_CONTEXT (context
);
1166 result
= g_source_attach_unlocked (source
, context
);
1168 /* If another thread has acquired the context, wake it up since it
1169 * might be in poll() right now.
1171 if (context
->owner
&& context
->owner
!= G_THREAD_SELF
)
1172 g_wakeup_signal (context
->wakeup
);
1174 UNLOCK_CONTEXT (context
);
1180 g_source_destroy_internal (GSource
*source
,
1181 GMainContext
*context
,
1185 LOCK_CONTEXT (context
);
1187 if (!SOURCE_DESTROYED (source
))
1190 gpointer old_cb_data
;
1191 GSourceCallbackFuncs
*old_cb_funcs
;
1193 source
->flags
&= ~G_HOOK_FLAG_ACTIVE
;
1195 old_cb_data
= source
->callback_data
;
1196 old_cb_funcs
= source
->callback_funcs
;
1198 source
->callback_data
= NULL
;
1199 source
->callback_funcs
= NULL
;
1203 UNLOCK_CONTEXT (context
);
1204 old_cb_funcs
->unref (old_cb_data
);
1205 LOCK_CONTEXT (context
);
1208 if (!SOURCE_BLOCKED (source
))
1210 tmp_list
= source
->poll_fds
;
1213 g_main_context_remove_poll_unlocked (context
, tmp_list
->data
);
1214 tmp_list
= tmp_list
->next
;
1217 for (tmp_list
= source
->priv
->fds
; tmp_list
; tmp_list
= tmp_list
->next
)
1218 g_main_context_remove_poll_unlocked (context
, tmp_list
->data
);
1221 while (source
->priv
->child_sources
)
1222 g_child_source_remove_internal (source
->priv
->child_sources
->data
, context
);
1224 if (source
->priv
->parent_source
)
1225 g_child_source_remove_internal (source
, context
);
1227 g_source_unref_internal (source
, context
, TRUE
);
1231 UNLOCK_CONTEXT (context
);
1236 * @source: a #GSource
1238 * Removes a source from its #GMainContext, if any, and mark it as
1239 * destroyed. The source cannot be subsequently added to another
1243 g_source_destroy (GSource
*source
)
1245 GMainContext
*context
;
1247 g_return_if_fail (source
!= NULL
);
1249 context
= source
->context
;
1252 g_source_destroy_internal (source
, context
, FALSE
);
1254 source
->flags
&= ~G_HOOK_FLAG_ACTIVE
;
1259 * @source: a #GSource
1261 * Returns the numeric ID for a particular source. The ID of a source
1262 * is a positive integer which is unique within a particular main loop
1263 * context. The reverse
1264 * mapping from ID to source is done by g_main_context_find_source_by_id().
1266 * Return value: the ID (greater than 0) for the source
1269 g_source_get_id (GSource
*source
)
1273 g_return_val_if_fail (source
!= NULL
, 0);
1274 g_return_val_if_fail (source
->context
!= NULL
, 0);
1276 LOCK_CONTEXT (source
->context
);
1277 result
= source
->source_id
;
1278 UNLOCK_CONTEXT (source
->context
);
1284 * g_source_get_context:
1285 * @source: a #GSource
1287 * Gets the #GMainContext with which the source is associated.
1289 * You can call this on a source that has been destroyed, provided
1290 * that the #GMainContext it was attached to still exists (in which
1291 * case it will return that #GMainContext). In particular, you can
1292 * always call this function on the source returned from
1293 * g_main_current_source(). But calling this function on a source
1294 * whose #GMainContext has been destroyed is an error.
1296 * Return value: (transfer none) (allow-none): the #GMainContext with which the
1297 * source is associated, or %NULL if the context has not
1298 * yet been added to a source.
1301 g_source_get_context (GSource
*source
)
1303 g_return_val_if_fail (source
->context
!= NULL
|| !SOURCE_DESTROYED (source
), NULL
);
1305 return source
->context
;
1309 * g_source_add_poll:
1310 * @source:a #GSource
1311 * @fd: a #GPollFD structure holding information about a file
1312 * descriptor to watch.
1314 * Adds a file descriptor to the set of file descriptors polled for
1315 * this source. This is usually combined with g_source_new() to add an
1316 * event source. The event source's check function will typically test
1317 * the @revents field in the #GPollFD struct and return %TRUE if events need
1320 * Using this API forces the linear scanning of event sources on each
1321 * main loop iteration. Newly-written event sources should try to use
1322 * g_source_add_unix_fd() instead of this API.
1325 g_source_add_poll (GSource
*source
,
1328 GMainContext
*context
;
1330 g_return_if_fail (source
!= NULL
);
1331 g_return_if_fail (fd
!= NULL
);
1332 g_return_if_fail (!SOURCE_DESTROYED (source
));
1334 context
= source
->context
;
1337 LOCK_CONTEXT (context
);
1339 source
->poll_fds
= g_slist_prepend (source
->poll_fds
, fd
);
1343 if (!SOURCE_BLOCKED (source
))
1344 g_main_context_add_poll_unlocked (context
, source
->priority
, fd
);
1345 UNLOCK_CONTEXT (context
);
1350 * g_source_remove_poll:
1351 * @source:a #GSource
1352 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1354 * Removes a file descriptor from the set of file descriptors polled for
1358 g_source_remove_poll (GSource
*source
,
1361 GMainContext
*context
;
1363 g_return_if_fail (source
!= NULL
);
1364 g_return_if_fail (fd
!= NULL
);
1365 g_return_if_fail (!SOURCE_DESTROYED (source
));
1367 context
= source
->context
;
1370 LOCK_CONTEXT (context
);
1372 source
->poll_fds
= g_slist_remove (source
->poll_fds
, fd
);
1376 if (!SOURCE_BLOCKED (source
))
1377 g_main_context_remove_poll_unlocked (context
, fd
);
1378 UNLOCK_CONTEXT (context
);
1383 * g_source_add_child_source:
1384 * @source:a #GSource
1385 * @child_source: a second #GSource that @source should "poll"
1387 * Adds @child_source to @source as a "polled" source; when @source is
1388 * added to a #GMainContext, @child_source will be automatically added
1389 * with the same priority, when @child_source is triggered, it will
1390 * cause @source to dispatch (in addition to calling its own
1391 * callback), and when @source is destroyed, it will destroy
1392 * @child_source as well. (@source will also still be dispatched if
1393 * its own prepare/check functions indicate that it is ready.)
1395 * If you don't need @child_source to do anything on its own when it
1396 * triggers, you can call g_source_set_dummy_callback() on it to set a
1397 * callback that does nothing (except return %TRUE if appropriate).
1399 * @source will hold a reference on @child_source while @child_source
1400 * is attached to it.
1405 g_source_add_child_source (GSource
*source
,
1406 GSource
*child_source
)
1408 GMainContext
*context
;
1410 g_return_if_fail (source
!= NULL
);
1411 g_return_if_fail (child_source
!= NULL
);
1412 g_return_if_fail (!SOURCE_DESTROYED (source
));
1413 g_return_if_fail (!SOURCE_DESTROYED (child_source
));
1414 g_return_if_fail (child_source
->context
== NULL
);
1415 g_return_if_fail (child_source
->priv
->parent_source
== NULL
);
1417 context
= source
->context
;
1420 LOCK_CONTEXT (context
);
1422 source
->priv
->child_sources
= g_slist_prepend (source
->priv
->child_sources
,
1423 g_source_ref (child_source
));
1424 child_source
->priv
->parent_source
= source
;
1425 g_source_set_priority_unlocked (child_source
, NULL
, source
->priority
);
1426 if (SOURCE_BLOCKED (source
))
1427 block_source (child_source
);
1431 UNLOCK_CONTEXT (context
);
1432 g_source_attach (child_source
, context
);
1437 g_child_source_remove_internal (GSource
*child_source
,
1438 GMainContext
*context
)
1440 GSource
*parent_source
= child_source
->priv
->parent_source
;
1442 parent_source
->priv
->child_sources
=
1443 g_slist_remove (parent_source
->priv
->child_sources
, child_source
);
1444 child_source
->priv
->parent_source
= NULL
;
1446 g_source_destroy_internal (child_source
, context
, TRUE
);
1447 g_source_unref_internal (child_source
, context
, TRUE
);
1451 * g_source_remove_child_source:
1452 * @source:a #GSource
1453 * @child_source: a #GSource previously passed to
1454 * g_source_add_child_source().
1456 * Detaches @child_source from @source and destroys it.
1461 g_source_remove_child_source (GSource
*source
,
1462 GSource
*child_source
)
1464 GMainContext
*context
;
1466 g_return_if_fail (source
!= NULL
);
1467 g_return_if_fail (child_source
!= NULL
);
1468 g_return_if_fail (child_source
->priv
->parent_source
== source
);
1469 g_return_if_fail (!SOURCE_DESTROYED (source
));
1470 g_return_if_fail (!SOURCE_DESTROYED (child_source
));
1472 context
= source
->context
;
1475 LOCK_CONTEXT (context
);
1477 g_child_source_remove_internal (child_source
, context
);
1480 UNLOCK_CONTEXT (context
);
1484 * g_source_set_callback_indirect:
1485 * @source: the source
1486 * @callback_data: pointer to callback data "object"
1487 * @callback_funcs: functions for reference counting @callback_data
1488 * and getting the callback and data
1490 * Sets the callback function storing the data as a refcounted callback
1491 * "object". This is used internally. Note that calling
1492 * g_source_set_callback_indirect() assumes
1493 * an initial reference count on @callback_data, and thus
1494 * @callback_funcs->unref will eventually be called once more
1495 * than @callback_funcs->ref.
1498 g_source_set_callback_indirect (GSource
*source
,
1499 gpointer callback_data
,
1500 GSourceCallbackFuncs
*callback_funcs
)
1502 GMainContext
*context
;
1503 gpointer old_cb_data
;
1504 GSourceCallbackFuncs
*old_cb_funcs
;
1506 g_return_if_fail (source
!= NULL
);
1507 g_return_if_fail (callback_funcs
!= NULL
|| callback_data
== NULL
);
1509 context
= source
->context
;
1512 LOCK_CONTEXT (context
);
1514 old_cb_data
= source
->callback_data
;
1515 old_cb_funcs
= source
->callback_funcs
;
1517 source
->callback_data
= callback_data
;
1518 source
->callback_funcs
= callback_funcs
;
1521 UNLOCK_CONTEXT (context
);
1524 old_cb_funcs
->unref (old_cb_data
);
1528 g_source_callback_ref (gpointer cb_data
)
1530 GSourceCallback
*callback
= cb_data
;
1532 callback
->ref_count
++;
1537 g_source_callback_unref (gpointer cb_data
)
1539 GSourceCallback
*callback
= cb_data
;
1541 callback
->ref_count
--;
1542 if (callback
->ref_count
== 0)
1544 if (callback
->notify
)
1545 callback
->notify (callback
->data
);
1551 g_source_callback_get (gpointer cb_data
,
1556 GSourceCallback
*callback
= cb_data
;
1558 *func
= callback
->func
;
1559 *data
= callback
->data
;
1562 static GSourceCallbackFuncs g_source_callback_funcs
= {
1563 g_source_callback_ref
,
1564 g_source_callback_unref
,
1565 g_source_callback_get
,
1569 * g_source_set_callback:
1570 * @source: the source
1571 * @func: a callback function
1572 * @data: the data to pass to callback function
1573 * @notify: (allow-none): a function to call when @data is no longer in use, or %NULL.
1575 * Sets the callback function for a source. The callback for a source is
1576 * called from the source's dispatch function.
1578 * The exact type of @func depends on the type of source; ie. you
1579 * should not count on @func being called with @data as its first
1582 * Typically, you won't use this function. Instead use functions specific
1583 * to the type of source you are using.
1586 g_source_set_callback (GSource
*source
,
1589 GDestroyNotify notify
)
1591 GSourceCallback
*new_callback
;
1593 g_return_if_fail (source
!= NULL
);
1595 new_callback
= g_new (GSourceCallback
, 1);
1597 new_callback
->ref_count
= 1;
1598 new_callback
->func
= func
;
1599 new_callback
->data
= data
;
1600 new_callback
->notify
= notify
;
1602 g_source_set_callback_indirect (source
, new_callback
, &g_source_callback_funcs
);
1607 * g_source_set_funcs:
1608 * @source: a #GSource
1609 * @funcs: the new #GSourceFuncs
1611 * Sets the source functions (can be used to override
1612 * default implementations) of an unattached source.
1617 g_source_set_funcs (GSource
*source
,
1618 GSourceFuncs
*funcs
)
1620 g_return_if_fail (source
!= NULL
);
1621 g_return_if_fail (source
->context
== NULL
);
1622 g_return_if_fail (source
->ref_count
> 0);
1623 g_return_if_fail (funcs
!= NULL
);
1625 source
->source_funcs
= funcs
;
1629 g_source_set_priority_unlocked (GSource
*source
,
1630 GMainContext
*context
,
1635 g_return_if_fail (source
->priv
->parent_source
== NULL
||
1636 source
->priv
->parent_source
->priority
== priority
);
1640 /* Remove the source from the context's source and then
1641 * add it back after so it is sorted in the correct place
1643 source_remove_from_context (source
, source
->context
);
1646 source
->priority
= priority
;
1650 source_add_to_context (source
, source
->context
);
1652 if (!SOURCE_BLOCKED (source
))
1654 tmp_list
= source
->poll_fds
;
1657 g_main_context_remove_poll_unlocked (context
, tmp_list
->data
);
1658 g_main_context_add_poll_unlocked (context
, priority
, tmp_list
->data
);
1660 tmp_list
= tmp_list
->next
;
1663 for (tmp_list
= source
->priv
->fds
; tmp_list
; tmp_list
= tmp_list
->next
)
1665 g_main_context_remove_poll_unlocked (context
, tmp_list
->data
);
1666 g_main_context_add_poll_unlocked (context
, priority
, tmp_list
->data
);
1671 if (source
->priv
->child_sources
)
1673 tmp_list
= source
->priv
->child_sources
;
1676 g_source_set_priority_unlocked (tmp_list
->data
, context
, priority
);
1677 tmp_list
= tmp_list
->next
;
1683 * g_source_set_priority:
1684 * @source: a #GSource
1685 * @priority: the new priority.
1687 * Sets the priority of a source. While the main loop is being run, a
1688 * source will be dispatched if it is ready to be dispatched and no
1689 * sources at a higher (numerically smaller) priority are ready to be
1693 g_source_set_priority (GSource
*source
,
1696 GMainContext
*context
;
1698 g_return_if_fail (source
!= NULL
);
1700 context
= source
->context
;
1703 LOCK_CONTEXT (context
);
1704 g_source_set_priority_unlocked (source
, context
, priority
);
1706 UNLOCK_CONTEXT (source
->context
);
1710 * g_source_get_priority:
1711 * @source: a #GSource
1713 * Gets the priority of a source.
1715 * Return value: the priority of the source
1718 g_source_get_priority (GSource
*source
)
1720 g_return_val_if_fail (source
!= NULL
, 0);
1722 return source
->priority
;
1726 * g_source_set_ready_time:
1727 * @source: a #GSource
1728 * @ready_time: the monotonic time at which the source will be ready,
1729 * 0 for "immediately", -1 for "never"
1731 * Sets a #GSource to be dispatched when the given monotonic time is
1732 * reached (or passed). If the monotonic time is in the past (as it
1733 * always will be if @ready_time is 0) then the source will be
1734 * dispatched immediately.
1736 * If @ready_time is -1 then the source is never woken up on the basis
1737 * of the passage of time.
1739 * Dispatching the source does not reset the ready time. You should do
1740 * so yourself, from the source dispatch function.
1742 * Note that if you have a pair of sources where the ready time of one
1743 * suggests that it will be delivered first but the priority for the
1744 * other suggests that it would be delivered first, and the ready time
1745 * for both sources is reached during the same main context iteration
1746 * then the order of dispatch is undefined.
1751 g_source_set_ready_time (GSource
*source
,
1754 GMainContext
*context
;
1756 g_return_if_fail (source
!= NULL
);
1757 g_return_if_fail (source
->ref_count
> 0);
1759 if (source
->priv
->ready_time
== ready_time
)
1762 context
= source
->context
;
1765 LOCK_CONTEXT (context
);
1767 source
->priv
->ready_time
= ready_time
;
1771 /* Quite likely that we need to change the timeout on the poll */
1772 if (!SOURCE_BLOCKED (source
))
1773 g_wakeup_signal (context
->wakeup
);
1774 UNLOCK_CONTEXT (context
);
1779 * g_source_get_ready_time:
1780 * @source: a #GSource
1782 * Gets the "ready time" of @source, as set by
1783 * g_source_set_ready_time().
1785 * Any time before the current monotonic time (including 0) is an
1786 * indication that the source will fire immediately.
1788 * Returns: the monotonic ready time, -1 for "never"
1791 g_source_get_ready_time (GSource
*source
)
1793 g_return_val_if_fail (source
!= NULL
, -1);
1795 return source
->priv
->ready_time
;
1799 * g_source_set_can_recurse:
1800 * @source: a #GSource
1801 * @can_recurse: whether recursion is allowed for this source
1803 * Sets whether a source can be called recursively. If @can_recurse is
1804 * %TRUE, then while the source is being dispatched then this source
1805 * will be processed normally. Otherwise, all processing of this
1806 * source is blocked until the dispatch function returns.
1809 g_source_set_can_recurse (GSource
*source
,
1810 gboolean can_recurse
)
1812 GMainContext
*context
;
1814 g_return_if_fail (source
!= NULL
);
1816 context
= source
->context
;
1819 LOCK_CONTEXT (context
);
1822 source
->flags
|= G_SOURCE_CAN_RECURSE
;
1824 source
->flags
&= ~G_SOURCE_CAN_RECURSE
;
1827 UNLOCK_CONTEXT (context
);
1831 * g_source_get_can_recurse:
1832 * @source: a #GSource
1834 * Checks whether a source is allowed to be called recursively.
1835 * see g_source_set_can_recurse().
1837 * Return value: whether recursion is allowed.
1840 g_source_get_can_recurse (GSource
*source
)
1842 g_return_val_if_fail (source
!= NULL
, FALSE
);
1844 return (source
->flags
& G_SOURCE_CAN_RECURSE
) != 0;
1849 * g_source_set_name:
1850 * @source: a #GSource
1851 * @name: debug name for the source
1853 * Sets a name for the source, used in debugging and profiling.
1854 * The name defaults to #NULL.
1856 * The source name should describe in a human-readable way
1857 * what the source does. For example, "X11 event queue"
1858 * or "GTK+ repaint idle handler" or whatever it is.
1860 * It is permitted to call this function multiple times, but is not
1861 * recommended due to the potential performance impact. For example,
1862 * one could change the name in the "check" function of a #GSourceFuncs
1863 * to include details like the event type in the source name.
1868 g_source_set_name (GSource
*source
,
1871 g_return_if_fail (source
!= NULL
);
1873 /* setting back to NULL is allowed, just because it's
1874 * weird if get_name can return NULL but you can't
1878 g_free (source
->name
);
1879 source
->name
= g_strdup (name
);
1883 * g_source_get_name:
1884 * @source: a #GSource
1886 * Gets a name for the source, used in debugging and profiling.
1887 * The name may be #NULL if it has never been set with
1888 * g_source_set_name().
1890 * Return value: the name of the source
1894 g_source_get_name (GSource
*source
)
1896 g_return_val_if_fail (source
!= NULL
, NULL
);
1898 return source
->name
;
1902 * g_source_set_name_by_id:
1903 * @tag: a #GSource ID
1904 * @name: debug name for the source
1906 * Sets the name of a source using its ID.
1908 * This is a convenience utility to set source names from the return
1909 * value of g_idle_add(), g_timeout_add(), etc.
1914 g_source_set_name_by_id (guint tag
,
1919 g_return_if_fail (tag
> 0);
1921 source
= g_main_context_find_source_by_id (NULL
, tag
);
1925 g_source_set_name (source
, name
);
1931 * @source: a #GSource
1933 * Increases the reference count on a source by one.
1935 * Return value: @source
1938 g_source_ref (GSource
*source
)
1940 GMainContext
*context
;
1942 g_return_val_if_fail (source
!= NULL
, NULL
);
1944 context
= source
->context
;
1947 LOCK_CONTEXT (context
);
1949 source
->ref_count
++;
1952 UNLOCK_CONTEXT (context
);
1957 /* g_source_unref() but possible to call within context lock
1960 g_source_unref_internal (GSource
*source
,
1961 GMainContext
*context
,
1964 gpointer old_cb_data
= NULL
;
1965 GSourceCallbackFuncs
*old_cb_funcs
= NULL
;
1967 g_return_if_fail (source
!= NULL
);
1969 if (!have_lock
&& context
)
1970 LOCK_CONTEXT (context
);
1972 source
->ref_count
--;
1973 if (source
->ref_count
== 0)
1975 old_cb_data
= source
->callback_data
;
1976 old_cb_funcs
= source
->callback_funcs
;
1978 source
->callback_data
= NULL
;
1979 source
->callback_funcs
= NULL
;
1983 if (!SOURCE_DESTROYED (source
))
1984 g_warning (G_STRLOC
": ref_count == 0, but source was still attached to a context!");
1985 source_remove_from_context (source
, context
);
1988 if (source
->source_funcs
->finalize
)
1991 UNLOCK_CONTEXT (context
);
1992 source
->source_funcs
->finalize (source
);
1994 LOCK_CONTEXT (context
);
1997 g_free (source
->name
);
1998 source
->name
= NULL
;
2000 g_slist_free (source
->poll_fds
);
2001 source
->poll_fds
= NULL
;
2003 g_slist_free_full (source
->priv
->fds
, g_free
);
2005 g_slice_free (GSourcePrivate
, source
->priv
);
2006 source
->priv
= NULL
;
2011 if (!have_lock
&& context
)
2012 UNLOCK_CONTEXT (context
);
2017 UNLOCK_CONTEXT (context
);
2019 old_cb_funcs
->unref (old_cb_data
);
2022 LOCK_CONTEXT (context
);
2028 * @source: a #GSource
2030 * Decreases the reference count of a source by one. If the
2031 * resulting reference count is zero the source and associated
2032 * memory will be destroyed.
2035 g_source_unref (GSource
*source
)
2037 g_return_if_fail (source
!= NULL
);
2039 g_source_unref_internal (source
, source
->context
, FALSE
);
2043 * g_main_context_find_source_by_id:
2044 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
2045 * @source_id: the source ID, as returned by g_source_get_id().
2047 * Finds a #GSource given a pair of context and ID.
2049 * Return value: (transfer none): the #GSource if found, otherwise, %NULL
2052 g_main_context_find_source_by_id (GMainContext
*context
,
2058 g_return_val_if_fail (source_id
> 0, NULL
);
2060 if (context
== NULL
)
2061 context
= g_main_context_default ();
2063 LOCK_CONTEXT (context
);
2065 g_source_iter_init (&iter
, context
, FALSE
);
2066 while (g_source_iter_next (&iter
, &source
))
2068 if (!SOURCE_DESTROYED (source
) &&
2069 source
->source_id
== source_id
)
2072 g_source_iter_clear (&iter
);
2074 UNLOCK_CONTEXT (context
);
2080 * g_main_context_find_source_by_funcs_user_data:
2081 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
2082 * @funcs: the @source_funcs passed to g_source_new().
2083 * @user_data: the user data from the callback.
2085 * Finds a source with the given source functions and user data. If
2086 * multiple sources exist with the same source function and user data,
2087 * the first one found will be returned.
2089 * Return value: (transfer none): the source, if one was found, otherwise %NULL
2092 g_main_context_find_source_by_funcs_user_data (GMainContext
*context
,
2093 GSourceFuncs
*funcs
,
2099 g_return_val_if_fail (funcs
!= NULL
, NULL
);
2101 if (context
== NULL
)
2102 context
= g_main_context_default ();
2104 LOCK_CONTEXT (context
);
2106 g_source_iter_init (&iter
, context
, FALSE
);
2107 while (g_source_iter_next (&iter
, &source
))
2109 if (!SOURCE_DESTROYED (source
) &&
2110 source
->source_funcs
== funcs
&&
2111 source
->callback_funcs
)
2113 GSourceFunc callback
;
2114 gpointer callback_data
;
2116 source
->callback_funcs
->get (source
->callback_data
, source
, &callback
, &callback_data
);
2118 if (callback_data
== user_data
)
2122 g_source_iter_clear (&iter
);
2124 UNLOCK_CONTEXT (context
);
2130 * g_main_context_find_source_by_user_data:
2131 * @context: a #GMainContext
2132 * @user_data: the user_data for the callback.
2134 * Finds a source with the given user data for the callback. If
2135 * multiple sources exist with the same user data, the first
2136 * one found will be returned.
2138 * Return value: (transfer none): the source, if one was found, otherwise %NULL
2141 g_main_context_find_source_by_user_data (GMainContext
*context
,
2147 if (context
== NULL
)
2148 context
= g_main_context_default ();
2150 LOCK_CONTEXT (context
);
2152 g_source_iter_init (&iter
, context
, FALSE
);
2153 while (g_source_iter_next (&iter
, &source
))
2155 if (!SOURCE_DESTROYED (source
) &&
2156 source
->callback_funcs
)
2158 GSourceFunc callback
;
2159 gpointer callback_data
= NULL
;
2161 source
->callback_funcs
->get (source
->callback_data
, source
, &callback
, &callback_data
);
2163 if (callback_data
== user_data
)
2167 g_source_iter_clear (&iter
);
2169 UNLOCK_CONTEXT (context
);
2176 * @tag: the ID of the source to remove.
2178 * Removes the source with the given id from the default main context.
2180 * a #GSource is given by g_source_get_id(), or will be returned by the
2181 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
2182 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
2183 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
2185 * See also g_source_destroy(). You must use g_source_destroy() for sources
2186 * added to a non-default main context.
2188 * Return value: %TRUE if the source was found and removed.
2191 g_source_remove (guint tag
)
2195 g_return_val_if_fail (tag
> 0, FALSE
);
2197 source
= g_main_context_find_source_by_id (NULL
, tag
);
2199 g_source_destroy (source
);
2201 return source
!= NULL
;
2205 * g_source_remove_by_user_data:
2206 * @user_data: the user_data for the callback.
2208 * Removes a source from the default main loop context given the user
2209 * data for the callback. If multiple sources exist with the same user
2210 * data, only one will be destroyed.
2212 * Return value: %TRUE if a source was found and removed.
2215 g_source_remove_by_user_data (gpointer user_data
)
2219 source
= g_main_context_find_source_by_user_data (NULL
, user_data
);
2222 g_source_destroy (source
);
2230 * g_source_remove_by_funcs_user_data:
2231 * @funcs: The @source_funcs passed to g_source_new()
2232 * @user_data: the user data for the callback
2234 * Removes a source from the default main loop context given the
2235 * source functions and user data. If multiple sources exist with the
2236 * same source functions and user data, only one will be destroyed.
2238 * Return value: %TRUE if a source was found and removed.
2241 g_source_remove_by_funcs_user_data (GSourceFuncs
*funcs
,
2246 g_return_val_if_fail (funcs
!= NULL
, FALSE
);
2248 source
= g_main_context_find_source_by_funcs_user_data (NULL
, funcs
, user_data
);
2251 g_source_destroy (source
);
2260 * g_source_add_unix_fd:
2261 * @source: a #GSource
2262 * @fd: the fd to monitor
2263 * @events: an event mask
2265 * Monitors @fd for the IO events in @events.
2267 * The tag returned by this function can be used to remove or modify the
2268 * monitoring of the fd using g_source_remove_unix_fd() or
2269 * g_source_modify_unix_fd().
2271 * It is not necessary to remove the fd before destroying the source; it
2272 * will be cleaned up automatically.
2274 * As the name suggests, this function is not available on Windows.
2276 * Returns: an opaque tag
2281 g_source_add_unix_fd (GSource
*source
,
2283 GIOCondition events
)
2285 GMainContext
*context
;
2288 g_return_val_if_fail (source
!= NULL
, NULL
);
2289 g_return_val_if_fail (!SOURCE_DESTROYED (source
), NULL
);
2291 poll_fd
= g_new (GPollFD
, 1);
2293 poll_fd
->events
= events
;
2294 poll_fd
->revents
= 0;
2296 context
= source
->context
;
2299 LOCK_CONTEXT (context
);
2301 source
->priv
->fds
= g_slist_prepend (source
->priv
->fds
, poll_fd
);
2305 if (!SOURCE_BLOCKED (source
))
2306 g_main_context_add_poll_unlocked (context
, source
->priority
, poll_fd
);
2307 UNLOCK_CONTEXT (context
);
2314 * g_source_modify_unix_fd:
2315 * @source: a #GSource
2316 * @tag: the tag from g_source_add_unix_fd()
2317 * @new_events: the new event mask to watch
2319 * Updates the event mask to watch for the fd identified by @tag.
2321 * @tag is the tag returned from g_source_add_unix_fd().
2323 * If you want to remove a fd, don't set its event mask to zero.
2324 * Instead, call g_source_remove_unix_fd().
2326 * As the name suggests, this function is not available on Windows.
2331 g_source_modify_unix_fd (GSource
*source
,
2333 GIOCondition new_events
)
2335 GMainContext
*context
;
2338 g_return_if_fail (source
!= NULL
);
2339 g_return_if_fail (g_slist_find (source
->priv
->fds
, tag
));
2341 context
= source
->context
;
2344 poll_fd
->events
= new_events
;
2347 g_main_context_wakeup (context
);
2351 * g_source_remove_unix_fd:
2352 * @source: a #GSource
2353 * @tag: the tag from g_source_add_unix_fd()
2355 * Reverses the effect of a previous call to g_source_add_unix_fd().
2357 * You only need to call this if you want to remove an fd from being
2358 * watched while keeping the same source around. In the normal case you
2359 * will just want to destroy the source.
2361 * As the name suggests, this function is not available on Windows.
2366 g_source_remove_unix_fd (GSource
*source
,
2369 GMainContext
*context
;
2372 g_return_if_fail (source
!= NULL
);
2373 g_return_if_fail (g_slist_find (source
->priv
->fds
, tag
));
2375 context
= source
->context
;
2379 LOCK_CONTEXT (context
);
2381 source
->priv
->fds
= g_slist_remove (source
->priv
->fds
, poll_fd
);
2385 if (!SOURCE_BLOCKED (source
))
2386 g_main_context_remove_poll_unlocked (context
, poll_fd
);
2388 UNLOCK_CONTEXT (context
);
2395 * g_source_query_unix_fd:
2396 * @source: a #GSource
2397 * @tag: the tag from g_source_add_unix_fd()
2399 * Queries the events reported for the fd corresponding to @tag on
2400 * @source during the last poll.
2402 * The return value of this function is only defined when the function
2403 * is called from the check or dispatch functions for @source.
2405 * As the name suggests, this function is not available on Windows.
2407 * Returns: the conditions reported on the fd
2412 g_source_query_unix_fd (GSource
*source
,
2417 g_return_val_if_fail (source
!= NULL
, 0);
2418 g_return_val_if_fail (g_slist_find (source
->priv
->fds
, tag
), 0);
2422 return poll_fd
->revents
;
2424 #endif /* G_OS_UNIX */
2427 * g_get_current_time:
2428 * @result: #GTimeVal structure in which to store current time.
2430 * Equivalent to the UNIX gettimeofday() function, but portable.
2432 * You may find g_get_real_time() to be more convenient.
2435 g_get_current_time (GTimeVal
*result
)
2440 g_return_if_fail (result
!= NULL
);
2442 /*this is required on alpha, there the timeval structs are int's
2443 not longs and a cast only would fail horribly*/
2444 gettimeofday (&r
, NULL
);
2445 result
->tv_sec
= r
.tv_sec
;
2446 result
->tv_usec
= r
.tv_usec
;
2451 g_return_if_fail (result
!= NULL
);
2453 GetSystemTimeAsFileTime (&ft
);
2454 memmove (&time64
, &ft
, sizeof (FILETIME
));
2456 /* Convert from 100s of nanoseconds since 1601-01-01
2457 * to Unix epoch. Yes, this is Y2038 unsafe.
2459 time64
-= G_GINT64_CONSTANT (116444736000000000);
2462 result
->tv_sec
= time64
/ 1000000;
2463 result
->tv_usec
= time64
% 1000000;
2470 * Queries the system wall-clock time.
2472 * This call is functionally equivalent to g_get_current_time() except
2473 * that the return value is often more convenient than dealing with a
2476 * You should only use this call if you are actually interested in the real
2477 * wall-clock time. g_get_monotonic_time() is probably more useful for
2478 * measuring intervals.
2480 * Returns: the number of microseconds since January 1, 1970 UTC.
2485 g_get_real_time (void)
2489 g_get_current_time (&tv
);
2491 return (((gint64
) tv
.tv_sec
) * 1000000) + tv
.tv_usec
;
2495 static ULONGLONG (*g_GetTickCount64
) (void) = NULL
;
2496 static guint32 g_win32_tick_epoch
= 0;
2499 g_clock_win32_init (void)
2503 g_GetTickCount64
= NULL
;
2504 kernel32
= GetModuleHandle ("KERNEL32.DLL");
2505 if (kernel32
!= NULL
)
2506 g_GetTickCount64
= (void *) GetProcAddress (kernel32
, "GetTickCount64");
2507 g_win32_tick_epoch
= ((guint32
)GetTickCount()) >> 31;
2512 * g_get_monotonic_time:
2514 * Queries the system monotonic time, if available.
2516 * On POSIX systems with clock_gettime() and <literal>CLOCK_MONOTONIC</literal> this call
2517 * is a very shallow wrapper for that. Otherwise, we make a best effort
2518 * that probably involves returning the wall clock time (with at least
2519 * microsecond accuracy, subject to the limitations of the OS kernel).
2521 * It's important to note that POSIX <literal>CLOCK_MONOTONIC</literal> does
2522 * not count time spent while the machine is suspended.
2524 * On Windows, "limitations of the OS kernel" is a rather substantial
2525 * statement. Depending on the configuration of the system, the wall
2526 * clock time is updated as infrequently as 64 times a second (which
2527 * is approximately every 16ms). Also, on XP (but not on Vista or later)
2528 * the monotonic clock is locally monotonic, but may differ in exact
2529 * value between processes due to timer wrap handling.
2531 * Returns: the monotonic time, in microseconds
2536 g_get_monotonic_time (void)
2538 #ifdef HAVE_CLOCK_GETTIME
2539 /* librt clock_gettime() is our first choice */
2542 #ifdef CLOCK_MONOTONIC
2543 clock_gettime (CLOCK_MONOTONIC
, &ts
);
2545 clock_gettime (CLOCK_REALTIME
, &ts
);
2548 /* In theory monotonic time can have any epoch.
2550 * glib presently assumes the following:
2552 * 1) The epoch comes some time after the birth of Jesus of Nazareth, but
2553 * not more than 10000 years later.
2555 * 2) The current time also falls sometime within this range.
2557 * These two reasonable assumptions leave us with a maximum deviation from
2558 * the epoch of 10000 years, or 315569520000000000 seconds.
2560 * If we restrict ourselves to this range then the number of microseconds
2561 * will always fit well inside the constraints of a int64 (by a factor of
2564 * If you actually hit the following assertion, probably you should file a
2565 * bug against your operating system for being excessively silly.
2567 g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts
.tv_sec
&&
2568 ts
.tv_sec
< G_GINT64_CONSTANT (315569520000000000));
2570 return (((gint64
) ts
.tv_sec
) * 1000000) + (ts
.tv_nsec
/ 1000);
2572 #elif defined (G_OS_WIN32)
2576 /* There are four sources for the monotonic time on Windows:
2578 * Three are based on a (1 msec accuracy, but only read periodically) clock chip:
2579 * - GetTickCount (GTC)
2580 * 32bit msec counter, updated each ~15msec, wraps in ~50 days
2581 * - GetTickCount64 (GTC64)
2582 * Same as GetTickCount, but extended to 64bit, so no wrap
2583 * Only available in Vista or later
2584 * - timeGetTime (TGT)
2585 * similar to GetTickCount by default: 15msec, 50 day wrap.
2586 * available in winmm.dll (thus known as the multimedia timers)
2587 * However apps can raise the system timer clock frequency using timeBeginPeriod()
2588 * increasing the accuracy up to 1 msec, at a cost in general system performance
2591 * One is based on high precision clocks:
2592 * - QueryPrecisionCounter (QPC)
2593 * This has much higher accuracy, but is not guaranteed monotonic, and
2594 * has lots of complications like clock jumps and different times on different
2595 * CPUs. It also has lower long term accuracy (i.e. it will drift compared to
2596 * the low precision clocks.
2598 * Additionally, the precision available in the timer-based wakeup such as
2599 * MsgWaitForMultipleObjectsEx (which is what the mainloop is based on) is based
2600 * on the TGT resolution, so by default it is ~15msec, but can be increased by apps.
2602 * The QPC timer has too many issues to be used as is. The only way it could be used
2603 * is to use it to interpolate the lower precision clocks. Firefox does something like
2605 * https://bugzilla.mozilla.org/show_bug.cgi?id=363258
2607 * However this seems quite complicated, so we're not doing this right now.
2609 * The approach we take instead is to use the TGT timer, extending it to 64bit
2610 * either by using the GTC64 value, or if that is not available, a process local
2611 * time epoch that we increment when we detect a timer wrap (assumes that we read
2612 * the time at least once every 50 days).
2615 * - We have a globally consistent monotonic clock on Vista and later
2616 * - We have a locally monotonic clock on XP
2617 * - Apps that need higher precision in timeouts and clock reads can call
2618 * timeBeginPeriod() to increase it as much as they want
2621 if (g_GetTickCount64
!= NULL
)
2623 guint32 ticks_as_32bit
;
2625 ticks
= g_GetTickCount64 ();
2626 ticks32
= timeGetTime();
2628 /* GTC64 and TGT are sampled at different times, however they
2629 * have the same base and source (msecs since system boot).
2630 * They can differ by as much as -16 to +16 msecs.
2631 * We can't just inject the low bits into the 64bit counter
2632 * as one of the counters can have wrapped in 32bit space and
2633 * the other not. Instead we calculate the signed difference
2634 * in 32bit space and apply that difference to the 64bit counter.
2636 ticks_as_32bit
= (guint32
)ticks
;
2638 /* We could do some 2's complement hack, but we play it safe */
2639 if (ticks32
- ticks_as_32bit
<= G_MAXINT32
)
2640 ticks
+= ticks32
- ticks_as_32bit
;
2642 ticks
-= ticks_as_32bit
- ticks32
;
2648 epoch
= g_atomic_int_get (&g_win32_tick_epoch
);
2650 /* Must read ticks after the epoch. Then we're guaranteed
2651 * that the ticks value we read is higher or equal to any
2652 * previous ones that lead to the writing of the epoch.
2654 ticks32
= timeGetTime();
2656 /* We store the MSB of the current time as the LSB
2657 * of the epoch. Comparing these bits lets us detect when
2658 * the 32bit counter has wrapped so we can increase the
2661 * This will work as long as this function is called at
2662 * least once every ~24 days, which is half the wrap time
2663 * of a 32bit msec counter. I think this is pretty likely.
2665 * Note that g_win32_tick_epoch is a process local state,
2666 * so the monotonic clock will not be the same between
2669 if ((ticks32
>> 31) != (epoch
& 1))
2672 g_atomic_int_set (&g_win32_tick_epoch
, epoch
);
2676 ticks
= (guint64
)ticks32
| ((guint64
)epoch
) << 31;
2679 return ticks
* 1000;
2681 #else /* !HAVE_CLOCK_GETTIME && ! G_OS_WIN32*/
2685 g_get_current_time (&tv
);
2687 return (((gint64
) tv
.tv_sec
) * 1000000) + tv
.tv_usec
;
2692 g_main_dispatch_free (gpointer dispatch
)
2694 g_slice_free (GMainDispatch
, dispatch
);
2697 /* Running the main loop */
2699 static GMainDispatch
*
2702 static GPrivate depth_private
= G_PRIVATE_INIT (g_main_dispatch_free
);
2703 GMainDispatch
*dispatch
;
2705 dispatch
= g_private_get (&depth_private
);
2709 dispatch
= g_slice_new0 (GMainDispatch
);
2710 g_private_set (&depth_private
, dispatch
);
2719 * Returns the depth of the stack of calls to
2720 * g_main_context_dispatch() on any #GMainContext in the current thread.
2721 * That is, when called from the toplevel, it gives 0. When
2722 * called from within a callback from g_main_context_iteration()
2723 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2724 * a callback to a recursive call to g_main_context_iteration(),
2725 * it returns 2. And so forth.
2727 * This function is useful in a situation like the following:
2728 * Imagine an extremely simple "garbage collected" system.
2731 * static GList *free_list;
2734 * allocate_memory (gsize size)
2736 * gpointer result = g_malloc (size);
2737 * free_list = g_list_prepend (free_list, result);
2742 * free_allocated_memory (void)
2745 * for (l = free_list; l; l = l->next);
2747 * g_list_free (free_list);
2755 * g_main_context_iteration (NULL, TRUE);
2756 * free_allocated_memory();
2760 * This works from an application, however, if you want to do the same
2761 * thing from a library, it gets more difficult, since you no longer
2762 * control the main loop. You might think you can simply use an idle
2763 * function to make the call to free_allocated_memory(), but that
2764 * doesn't work, since the idle function could be called from a
2765 * recursive callback. This can be fixed by using g_main_depth()
2769 * allocate_memory (gsize size)
2771 * FreeListBlock *block = g_new (FreeListBlock, 1);
2772 * block->mem = g_malloc (size);
2773 * block->depth = g_main_depth ();
2774 * free_list = g_list_prepend (free_list, block);
2775 * return block->mem;
2779 * free_allocated_memory (void)
2783 * int depth = g_main_depth ();
2784 * for (l = free_list; l; );
2786 * GList *next = l->next;
2787 * FreeListBlock *block = l->data;
2788 * if (block->depth > depth)
2790 * g_free (block->mem);
2792 * free_list = g_list_delete_link (free_list, l);
2800 * There is a temptation to use g_main_depth() to solve
2801 * problems with reentrancy. For instance, while waiting for data
2802 * to be received from the network in response to a menu item,
2803 * the menu item might be selected again. It might seem that
2804 * one could make the menu item's callback return immediately
2805 * and do nothing if g_main_depth() returns a value greater than 1.
2806 * However, this should be avoided since the user then sees selecting
2807 * the menu item do nothing. Furthermore, you'll find yourself adding
2808 * these checks all over your code, since there are doubtless many,
2809 * many things that the user could do. Instead, you can use the
2810 * following techniques:
2815 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
2816 * the user from interacting with elements while the main
2817 * loop is recursing.
2822 * Avoid main loop recursion in situations where you can't handle
2823 * arbitrary callbacks. Instead, structure your code so that you
2824 * simply return to the main loop and then get called again when
2825 * there is more work to do.
2830 * Return value: The main loop recursion level in the current thread
2835 GMainDispatch
*dispatch
= get_dispatch ();
2836 return dispatch
->depth
;
2840 * g_main_current_source:
2842 * Returns the currently firing source for this thread.
2844 * Return value: (transfer none): The currently firing source or %NULL.
2849 g_main_current_source (void)
2851 GMainDispatch
*dispatch
= get_dispatch ();
2852 return dispatch
->dispatching_sources
? dispatch
->dispatching_sources
->data
: NULL
;
2856 * g_source_is_destroyed:
2857 * @source: a #GSource
2859 * Returns whether @source has been destroyed.
2861 * This is important when you operate upon your objects
2862 * from within idle handlers, but may have freed the object
2863 * before the dispatch of your idle handler.
2867 * idle_callback (gpointer data)
2869 * SomeWidget *self = data;
2871 * GDK_THREADS_ENTER (<!-- -->);
2872 * /<!-- -->* do stuff with self *<!-- -->/
2873 * self->idle_id = 0;
2874 * GDK_THREADS_LEAVE (<!-- -->);
2876 * return G_SOURCE_REMOVE;
2880 * some_widget_do_stuff_later (SomeWidget *self)
2882 * self->idle_id = g_idle_add (idle_callback, self);
2886 * some_widget_finalize (GObject *object)
2888 * SomeWidget *self = SOME_WIDGET (object);
2890 * if (self->idle_id)
2891 * g_source_remove (self->idle_id);
2893 * G_OBJECT_CLASS (parent_class)->finalize (object);
2897 * This will fail in a multi-threaded application if the
2898 * widget is destroyed before the idle handler fires due
2899 * to the use after free in the callback. A solution, to
2900 * this particular problem, is to check to if the source
2901 * has already been destroy within the callback.
2905 * idle_callback (gpointer data)
2907 * SomeWidget *self = data;
2909 * GDK_THREADS_ENTER ();
2910 * if (!g_source_is_destroyed (g_main_current_source ()))
2912 * /<!-- -->* do stuff with self *<!-- -->/
2914 * GDK_THREADS_LEAVE ();
2920 * Return value: %TRUE if the source has been destroyed
2925 g_source_is_destroyed (GSource
*source
)
2927 return SOURCE_DESTROYED (source
);
2930 /* Temporarily remove all this source's file descriptors from the
2931 * poll(), so that if data comes available for one of the file descriptors
2932 * we don't continually spin in the poll()
2934 /* HOLDS: source->context's lock */
2936 block_source (GSource
*source
)
2940 g_return_if_fail (!SOURCE_BLOCKED (source
));
2942 source
->flags
|= G_SOURCE_BLOCKED
;
2944 tmp_list
= source
->poll_fds
;
2947 g_main_context_remove_poll_unlocked (source
->context
, tmp_list
->data
);
2948 tmp_list
= tmp_list
->next
;
2951 for (tmp_list
= source
->priv
->fds
; tmp_list
; tmp_list
= tmp_list
->next
)
2952 g_main_context_remove_poll_unlocked (source
->context
, tmp_list
->data
);
2954 if (source
->priv
&& source
->priv
->child_sources
)
2956 tmp_list
= source
->priv
->child_sources
;
2959 block_source (tmp_list
->data
);
2960 tmp_list
= tmp_list
->next
;
2965 /* HOLDS: source->context's lock */
2967 unblock_source (GSource
*source
)
2971 g_return_if_fail (SOURCE_BLOCKED (source
)); /* Source already unblocked */
2972 g_return_if_fail (!SOURCE_DESTROYED (source
));
2974 source
->flags
&= ~G_SOURCE_BLOCKED
;
2976 tmp_list
= source
->poll_fds
;
2979 g_main_context_add_poll_unlocked (source
->context
, source
->priority
, tmp_list
->data
);
2980 tmp_list
= tmp_list
->next
;
2983 for (tmp_list
= source
->priv
->fds
; tmp_list
; tmp_list
= tmp_list
->next
)
2984 g_main_context_add_poll_unlocked (source
->context
, source
->priority
, tmp_list
->data
);
2986 if (source
->priv
&& source
->priv
->child_sources
)
2988 tmp_list
= source
->priv
->child_sources
;
2991 unblock_source (tmp_list
->data
);
2992 tmp_list
= tmp_list
->next
;
2997 /* HOLDS: context's lock */
2999 g_main_dispatch (GMainContext
*context
)
3001 GMainDispatch
*current
= get_dispatch ();
3004 for (i
= 0; i
< context
->pending_dispatches
->len
; i
++)
3006 GSource
*source
= context
->pending_dispatches
->pdata
[i
];
3008 context
->pending_dispatches
->pdata
[i
] = NULL
;
3011 source
->flags
&= ~G_SOURCE_READY
;
3013 if (!SOURCE_DESTROYED (source
))
3015 gboolean was_in_call
;
3016 gpointer user_data
= NULL
;
3017 GSourceFunc callback
= NULL
;
3018 GSourceCallbackFuncs
*cb_funcs
;
3020 gboolean need_destroy
;
3022 gboolean (*dispatch
) (GSource
*,
3025 GSList current_source_link
;
3027 dispatch
= source
->source_funcs
->dispatch
;
3028 cb_funcs
= source
->callback_funcs
;
3029 cb_data
= source
->callback_data
;
3032 cb_funcs
->ref (cb_data
);
3034 if ((source
->flags
& G_SOURCE_CAN_RECURSE
) == 0)
3035 block_source (source
);
3037 was_in_call
= source
->flags
& G_HOOK_FLAG_IN_CALL
;
3038 source
->flags
|= G_HOOK_FLAG_IN_CALL
;
3041 cb_funcs
->get (cb_data
, source
, &callback
, &user_data
);
3043 UNLOCK_CONTEXT (context
);
3046 /* The on-stack allocation of the GSList is unconventional, but
3047 * we know that the lifetime of the link is bounded to this
3048 * function as the link is kept in a thread specific list and
3049 * not manipulated outside of this function and its descendants.
3050 * Avoiding the overhead of a g_slist_alloc() is useful as many
3051 * applications do little more than dispatch events.
3053 * This is a performance hack - do not revert to g_slist_prepend()!
3055 current_source_link
.data
= source
;
3056 current_source_link
.next
= current
->dispatching_sources
;
3057 current
->dispatching_sources
= ¤t_source_link
;
3058 need_destroy
= ! dispatch (source
,
3061 g_assert (current
->dispatching_sources
== ¤t_source_link
);
3062 current
->dispatching_sources
= current_source_link
.next
;
3066 cb_funcs
->unref (cb_data
);
3068 LOCK_CONTEXT (context
);
3071 source
->flags
&= ~G_HOOK_FLAG_IN_CALL
;
3073 if (SOURCE_BLOCKED (source
) && !SOURCE_DESTROYED (source
))
3074 unblock_source (source
);
3076 /* Note: this depends on the fact that we can't switch
3077 * sources from one main context to another
3079 if (need_destroy
&& !SOURCE_DESTROYED (source
))
3081 g_assert (source
->context
== context
);
3082 g_source_destroy_internal (source
, context
, TRUE
);
3086 SOURCE_UNREF (source
, context
);
3089 g_ptr_array_set_size (context
->pending_dispatches
, 0);
3093 * g_main_context_acquire:
3094 * @context: a #GMainContext
3096 * Tries to become the owner of the specified context.
3097 * If some other thread is the owner of the context,
3098 * returns %FALSE immediately. Ownership is properly
3099 * recursive: the owner can require ownership again
3100 * and will release ownership when g_main_context_release()
3101 * is called as many times as g_main_context_acquire().
3103 * You must be the owner of a context before you
3104 * can call g_main_context_prepare(), g_main_context_query(),
3105 * g_main_context_check(), g_main_context_dispatch().
3107 * Return value: %TRUE if the operation succeeded, and
3108 * this thread is now the owner of @context.
3111 g_main_context_acquire (GMainContext
*context
)
3113 gboolean result
= FALSE
;
3114 GThread
*self
= G_THREAD_SELF
;
3116 if (context
== NULL
)
3117 context
= g_main_context_default ();
3119 LOCK_CONTEXT (context
);
3121 if (!context
->owner
)
3123 context
->owner
= self
;
3124 g_assert (context
->owner_count
== 0);
3127 if (context
->owner
== self
)
3129 context
->owner_count
++;
3133 UNLOCK_CONTEXT (context
);
3139 * g_main_context_release:
3140 * @context: a #GMainContext
3142 * Releases ownership of a context previously acquired by this thread
3143 * with g_main_context_acquire(). If the context was acquired multiple
3144 * times, the ownership will be released only when g_main_context_release()
3145 * is called as many times as it was acquired.
3148 g_main_context_release (GMainContext
*context
)
3150 if (context
== NULL
)
3151 context
= g_main_context_default ();
3153 LOCK_CONTEXT (context
);
3155 context
->owner_count
--;
3156 if (context
->owner_count
== 0)
3158 context
->owner
= NULL
;
3160 if (context
->waiters
)
3162 GMainWaiter
*waiter
= context
->waiters
->data
;
3163 gboolean loop_internal_waiter
= (waiter
->mutex
== &context
->mutex
);
3164 context
->waiters
= g_slist_delete_link (context
->waiters
,
3166 if (!loop_internal_waiter
)
3167 g_mutex_lock (waiter
->mutex
);
3169 g_cond_signal (waiter
->cond
);
3171 if (!loop_internal_waiter
)
3172 g_mutex_unlock (waiter
->mutex
);
3176 UNLOCK_CONTEXT (context
);
3180 * g_main_context_wait:
3181 * @context: a #GMainContext
3182 * @cond: a condition variable
3183 * @mutex: a mutex, currently held
3185 * Tries to become the owner of the specified context,
3186 * as with g_main_context_acquire(). But if another thread
3187 * is the owner, atomically drop @mutex and wait on @cond until
3188 * that owner releases ownership or until @cond is signaled, then
3189 * try again (once) to become the owner.
3191 * Return value: %TRUE if the operation succeeded, and
3192 * this thread is now the owner of @context.
3195 g_main_context_wait (GMainContext
*context
,
3199 gboolean result
= FALSE
;
3200 GThread
*self
= G_THREAD_SELF
;
3201 gboolean loop_internal_waiter
;
3203 if (context
== NULL
)
3204 context
= g_main_context_default ();
3206 loop_internal_waiter
= (mutex
== &context
->mutex
);
3208 if (!loop_internal_waiter
)
3209 LOCK_CONTEXT (context
);
3211 if (context
->owner
&& context
->owner
!= self
)
3216 waiter
.mutex
= mutex
;
3218 context
->waiters
= g_slist_append (context
->waiters
, &waiter
);
3220 if (!loop_internal_waiter
)
3221 UNLOCK_CONTEXT (context
);
3222 g_cond_wait (cond
, mutex
);
3223 if (!loop_internal_waiter
)
3224 LOCK_CONTEXT (context
);
3226 context
->waiters
= g_slist_remove (context
->waiters
, &waiter
);
3229 if (!context
->owner
)
3231 context
->owner
= self
;
3232 g_assert (context
->owner_count
== 0);
3235 if (context
->owner
== self
)
3237 context
->owner_count
++;
3241 if (!loop_internal_waiter
)
3242 UNLOCK_CONTEXT (context
);
3248 * g_main_context_prepare:
3249 * @context: a #GMainContext
3250 * @priority: location to store priority of highest priority
3251 * source already ready.
3253 * Prepares to poll sources within a main loop. The resulting information
3254 * for polling is determined by calling g_main_context_query ().
3256 * Return value: %TRUE if some source is ready to be dispatched
3260 g_main_context_prepare (GMainContext
*context
,
3265 gint current_priority
= G_MAXINT
;
3269 if (context
== NULL
)
3270 context
= g_main_context_default ();
3272 LOCK_CONTEXT (context
);
3274 context
->time_is_fresh
= FALSE
;
3276 if (context
->in_check_or_prepare
)
3278 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
3279 "prepare() member.");
3280 UNLOCK_CONTEXT (context
);
3285 /* If recursing, finish up current dispatch, before starting over */
3286 if (context
->pending_dispatches
)
3289 g_main_dispatch (context
, ¤t_time
);
3291 UNLOCK_CONTEXT (context
);
3296 /* If recursing, clear list of pending dispatches */
3298 for (i
= 0; i
< context
->pending_dispatches
->len
; i
++)
3300 if (context
->pending_dispatches
->pdata
[i
])
3301 SOURCE_UNREF ((GSource
*)context
->pending_dispatches
->pdata
[i
], context
);
3303 g_ptr_array_set_size (context
->pending_dispatches
, 0);
3305 /* Prepare all sources */
3307 context
->timeout
= -1;
3309 g_source_iter_init (&iter
, context
, TRUE
);
3310 while (g_source_iter_next (&iter
, &source
))
3312 gint source_timeout
= -1;
3314 if (SOURCE_DESTROYED (source
) || SOURCE_BLOCKED (source
))
3316 if ((n_ready
> 0) && (source
->priority
> current_priority
))
3319 if (!(source
->flags
& G_SOURCE_READY
))
3322 gboolean (* prepare
) (GSource
*source
,
3325 prepare
= source
->source_funcs
->prepare
;
3329 context
->in_check_or_prepare
++;
3330 UNLOCK_CONTEXT (context
);
3332 result
= (* prepare
) (source
, &source_timeout
);
3334 LOCK_CONTEXT (context
);
3335 context
->in_check_or_prepare
--;
3339 source_timeout
= -1;
3343 if (result
== FALSE
&& source
->priv
->ready_time
!= -1)
3345 if (!context
->time_is_fresh
)
3347 context
->time
= g_get_monotonic_time ();
3348 context
->time_is_fresh
= TRUE
;
3351 if (source
->priv
->ready_time
<= context
->time
)
3360 /* rounding down will lead to spinning, so always round up */
3361 timeout
= (source
->priv
->ready_time
- context
->time
+ 999) / 1000;
3363 if (source_timeout
< 0 || timeout
< source_timeout
)
3364 source_timeout
= timeout
;
3370 GSource
*ready_source
= source
;
3372 while (ready_source
)
3374 ready_source
->flags
|= G_SOURCE_READY
;
3375 ready_source
= ready_source
->priv
->parent_source
;
3380 if (source
->flags
& G_SOURCE_READY
)
3383 current_priority
= source
->priority
;
3384 context
->timeout
= 0;
3387 if (source_timeout
>= 0)
3389 if (context
->timeout
< 0)
3390 context
->timeout
= source_timeout
;
3392 context
->timeout
= MIN (context
->timeout
, source_timeout
);
3395 g_source_iter_clear (&iter
);
3397 UNLOCK_CONTEXT (context
);
3400 *priority
= current_priority
;
3402 return (n_ready
> 0);
3406 * g_main_context_query:
3407 * @context: a #GMainContext
3408 * @max_priority: maximum priority source to check
3409 * @timeout_: (out): location to store timeout to be used in polling
3410 * @fds: (out caller-allocates) (array length=n_fds): location to
3411 * store #GPollFD records that need to be polled.
3412 * @n_fds: length of @fds.
3414 * Determines information necessary to poll this main loop.
3416 * Return value: the number of records actually stored in @fds,
3417 * or, if more than @n_fds records need to be stored, the number
3418 * of records that need to be stored.
3421 g_main_context_query (GMainContext
*context
,
3430 LOCK_CONTEXT (context
);
3432 pollrec
= context
->poll_records
;
3434 while (pollrec
&& max_priority
>= pollrec
->priority
)
3436 /* We need to include entries with fd->events == 0 in the array because
3437 * otherwise if the application changes fd->events behind our back and
3438 * makes it non-zero, we'll be out of sync when we check the fds[] array.
3439 * (Changing fd->events after adding an FD wasn't an anticipated use of
3440 * this API, but it occurs in practice.) */
3443 fds
[n_poll
].fd
= pollrec
->fd
->fd
;
3444 /* In direct contradiction to the Unix98 spec, IRIX runs into
3445 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
3446 * flags in the events field of the pollfd while it should
3447 * just ignoring them. So we mask them out here.
3449 fds
[n_poll
].events
= pollrec
->fd
->events
& ~(G_IO_ERR
|G_IO_HUP
|G_IO_NVAL
);
3450 fds
[n_poll
].revents
= 0;
3453 pollrec
= pollrec
->next
;
3457 context
->poll_changed
= FALSE
;
3461 *timeout
= context
->timeout
;
3463 context
->time_is_fresh
= FALSE
;
3466 UNLOCK_CONTEXT (context
);
3472 * g_main_context_check:
3473 * @context: a #GMainContext
3474 * @max_priority: the maximum numerical priority of sources to check
3475 * @fds: (array length=n_fds): array of #GPollFD's that was passed to
3476 * the last call to g_main_context_query()
3477 * @n_fds: return value of g_main_context_query()
3479 * Passes the results of polling back to the main loop.
3481 * Return value: %TRUE if some sources are ready to be dispatched.
3484 g_main_context_check (GMainContext
*context
,
3495 LOCK_CONTEXT (context
);
3497 if (context
->in_check_or_prepare
)
3499 g_warning ("g_main_context_check() called recursively from within a source's check() or "
3500 "prepare() member.");
3501 UNLOCK_CONTEXT (context
);
3505 if (context
->wake_up_rec
.revents
)
3506 g_wakeup_acknowledge (context
->wakeup
);
3508 /* If the set of poll file descriptors changed, bail out
3509 * and let the main loop rerun
3511 if (context
->poll_changed
)
3513 UNLOCK_CONTEXT (context
);
3517 pollrec
= context
->poll_records
;
3521 if (pollrec
->fd
->events
)
3522 pollrec
->fd
->revents
= fds
[i
].revents
;
3524 pollrec
= pollrec
->next
;
3528 g_source_iter_init (&iter
, context
, TRUE
);
3529 while (g_source_iter_next (&iter
, &source
))
3531 if (SOURCE_DESTROYED (source
) || SOURCE_BLOCKED (source
))
3533 if ((n_ready
> 0) && (source
->priority
> max_priority
))
3536 if (!(source
->flags
& G_SOURCE_READY
))
3539 gboolean (* check
) (GSource
*source
);
3541 check
= source
->source_funcs
->check
;
3545 /* If the check function is set, call it. */
3546 context
->in_check_or_prepare
++;
3547 UNLOCK_CONTEXT (context
);
3549 result
= (* check
) (source
);
3551 LOCK_CONTEXT (context
);
3552 context
->in_check_or_prepare
--;
3557 if (result
== FALSE
)
3561 /* If not already explicitly flagged ready by ->check()
3562 * (or if we have no check) then we can still be ready if
3563 * any of our fds poll as ready.
3565 for (tmp_list
= source
->priv
->fds
; tmp_list
; tmp_list
= tmp_list
->next
)
3567 GPollFD
*pollfd
= tmp_list
->data
;
3569 if (pollfd
->revents
)
3577 if (result
== FALSE
&& source
->priv
->ready_time
!= -1)
3579 if (!context
->time_is_fresh
)
3581 context
->time
= g_get_monotonic_time ();
3582 context
->time_is_fresh
= TRUE
;
3585 if (source
->priv
->ready_time
<= context
->time
)
3591 GSource
*ready_source
= source
;
3593 while (ready_source
)
3595 ready_source
->flags
|= G_SOURCE_READY
;
3596 ready_source
= ready_source
->priv
->parent_source
;
3601 if (source
->flags
& G_SOURCE_READY
)
3603 source
->ref_count
++;
3604 g_ptr_array_add (context
->pending_dispatches
, source
);
3608 /* never dispatch sources with less priority than the first
3609 * one we choose to dispatch
3611 max_priority
= source
->priority
;
3614 g_source_iter_clear (&iter
);
3616 UNLOCK_CONTEXT (context
);
3622 * g_main_context_dispatch:
3623 * @context: a #GMainContext
3625 * Dispatches all pending sources.
3628 g_main_context_dispatch (GMainContext
*context
)
3630 LOCK_CONTEXT (context
);
3632 if (context
->pending_dispatches
->len
> 0)
3634 g_main_dispatch (context
);
3637 UNLOCK_CONTEXT (context
);
3640 /* HOLDS context lock */
3642 g_main_context_iterate (GMainContext
*context
,
3649 gboolean some_ready
;
3650 gint nfds
, allocated_nfds
;
3651 GPollFD
*fds
= NULL
;
3653 UNLOCK_CONTEXT (context
);
3655 if (!g_main_context_acquire (context
))
3657 gboolean got_ownership
;
3659 LOCK_CONTEXT (context
);
3664 got_ownership
= g_main_context_wait (context
,
3672 LOCK_CONTEXT (context
);
3674 if (!context
->cached_poll_array
)
3676 context
->cached_poll_array_size
= context
->n_poll_records
;
3677 context
->cached_poll_array
= g_new (GPollFD
, context
->n_poll_records
);
3680 allocated_nfds
= context
->cached_poll_array_size
;
3681 fds
= context
->cached_poll_array
;
3683 UNLOCK_CONTEXT (context
);
3685 g_main_context_prepare (context
, &max_priority
);
3687 while ((nfds
= g_main_context_query (context
, max_priority
, &timeout
, fds
,
3688 allocated_nfds
)) > allocated_nfds
)
3690 LOCK_CONTEXT (context
);
3692 context
->cached_poll_array_size
= allocated_nfds
= nfds
;
3693 context
->cached_poll_array
= fds
= g_new (GPollFD
, nfds
);
3694 UNLOCK_CONTEXT (context
);
3700 g_main_context_poll (context
, timeout
, max_priority
, fds
, nfds
);
3702 some_ready
= g_main_context_check (context
, max_priority
, fds
, nfds
);
3705 g_main_context_dispatch (context
);
3707 g_main_context_release (context
);
3709 LOCK_CONTEXT (context
);
3715 * g_main_context_pending:
3716 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
3718 * Checks if any sources have pending events for the given context.
3720 * Return value: %TRUE if events are pending.
3723 g_main_context_pending (GMainContext
*context
)
3728 context
= g_main_context_default();
3730 LOCK_CONTEXT (context
);
3731 retval
= g_main_context_iterate (context
, FALSE
, FALSE
, G_THREAD_SELF
);
3732 UNLOCK_CONTEXT (context
);
3738 * g_main_context_iteration:
3739 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
3740 * @may_block: whether the call may block.
3742 * Runs a single iteration for the given main loop. This involves
3743 * checking to see if any event sources are ready to be processed,
3744 * then if no events sources are ready and @may_block is %TRUE, waiting
3745 * for a source to become ready, then dispatching the highest priority
3746 * events sources that are ready. Otherwise, if @may_block is %FALSE
3747 * sources are not waited to become ready, only those highest priority
3748 * events sources will be dispatched (if any), that are ready at this
3749 * given moment without further waiting.
3751 * Note that even when @may_block is %TRUE, it is still possible for
3752 * g_main_context_iteration() to return %FALSE, since the wait may
3753 * be interrupted for other reasons than an event source becoming ready.
3755 * Return value: %TRUE if events were dispatched.
3758 g_main_context_iteration (GMainContext
*context
, gboolean may_block
)
3763 context
= g_main_context_default();
3765 LOCK_CONTEXT (context
);
3766 retval
= g_main_context_iterate (context
, may_block
, TRUE
, G_THREAD_SELF
);
3767 UNLOCK_CONTEXT (context
);
3774 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
3775 * @is_running: set to %TRUE to indicate that the loop is running. This
3776 * is not very important since calling g_main_loop_run() will set this to
3779 * Creates a new #GMainLoop structure.
3781 * Return value: a new #GMainLoop.
3784 g_main_loop_new (GMainContext
*context
,
3785 gboolean is_running
)
3790 context
= g_main_context_default();
3792 g_main_context_ref (context
);
3794 loop
= g_new0 (GMainLoop
, 1);
3795 loop
->context
= context
;
3796 loop
->is_running
= is_running
!= FALSE
;
3797 loop
->ref_count
= 1;
3804 * @loop: a #GMainLoop
3806 * Increases the reference count on a #GMainLoop object by one.
3808 * Return value: @loop
3811 g_main_loop_ref (GMainLoop
*loop
)
3813 g_return_val_if_fail (loop
!= NULL
, NULL
);
3814 g_return_val_if_fail (g_atomic_int_get (&loop
->ref_count
) > 0, NULL
);
3816 g_atomic_int_inc (&loop
->ref_count
);
3822 * g_main_loop_unref:
3823 * @loop: a #GMainLoop
3825 * Decreases the reference count on a #GMainLoop object by one. If
3826 * the result is zero, free the loop and free all associated memory.
3829 g_main_loop_unref (GMainLoop
*loop
)
3831 g_return_if_fail (loop
!= NULL
);
3832 g_return_if_fail (g_atomic_int_get (&loop
->ref_count
) > 0);
3834 if (!g_atomic_int_dec_and_test (&loop
->ref_count
))
3837 g_main_context_unref (loop
->context
);
3843 * @loop: a #GMainLoop
3845 * Runs a main loop until g_main_loop_quit() is called on the loop.
3846 * If this is called for the thread of the loop's #GMainContext,
3847 * it will process events from the loop, otherwise it will
3851 g_main_loop_run (GMainLoop
*loop
)
3853 GThread
*self
= G_THREAD_SELF
;
3855 g_return_if_fail (loop
!= NULL
);
3856 g_return_if_fail (g_atomic_int_get (&loop
->ref_count
) > 0);
3858 if (!g_main_context_acquire (loop
->context
))
3860 gboolean got_ownership
= FALSE
;
3862 /* Another thread owns this context */
3863 LOCK_CONTEXT (loop
->context
);
3865 g_atomic_int_inc (&loop
->ref_count
);
3867 if (!loop
->is_running
)
3868 loop
->is_running
= TRUE
;
3870 while (loop
->is_running
&& !got_ownership
)
3871 got_ownership
= g_main_context_wait (loop
->context
,
3872 &loop
->context
->cond
,
3873 &loop
->context
->mutex
);
3875 if (!loop
->is_running
)
3877 UNLOCK_CONTEXT (loop
->context
);
3879 g_main_context_release (loop
->context
);
3880 g_main_loop_unref (loop
);
3884 g_assert (got_ownership
);
3887 LOCK_CONTEXT (loop
->context
);
3889 if (loop
->context
->in_check_or_prepare
)
3891 g_warning ("g_main_loop_run(): called recursively from within a source's "
3892 "check() or prepare() member, iteration not possible.");
3896 g_atomic_int_inc (&loop
->ref_count
);
3897 loop
->is_running
= TRUE
;
3898 while (loop
->is_running
)
3899 g_main_context_iterate (loop
->context
, TRUE
, TRUE
, self
);
3901 UNLOCK_CONTEXT (loop
->context
);
3903 g_main_context_release (loop
->context
);
3905 g_main_loop_unref (loop
);
3910 * @loop: a #GMainLoop
3912 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3913 * for the loop will return.
3915 * Note that sources that have already been dispatched when
3916 * g_main_loop_quit() is called will still be executed.
3919 g_main_loop_quit (GMainLoop
*loop
)
3921 g_return_if_fail (loop
!= NULL
);
3922 g_return_if_fail (g_atomic_int_get (&loop
->ref_count
) > 0);
3924 LOCK_CONTEXT (loop
->context
);
3925 loop
->is_running
= FALSE
;
3926 g_wakeup_signal (loop
->context
->wakeup
);
3928 g_cond_broadcast (&loop
->context
->cond
);
3930 UNLOCK_CONTEXT (loop
->context
);
3934 * g_main_loop_is_running:
3935 * @loop: a #GMainLoop.
3937 * Checks to see if the main loop is currently being run via g_main_loop_run().
3939 * Return value: %TRUE if the mainloop is currently being run.
3942 g_main_loop_is_running (GMainLoop
*loop
)
3944 g_return_val_if_fail (loop
!= NULL
, FALSE
);
3945 g_return_val_if_fail (g_atomic_int_get (&loop
->ref_count
) > 0, FALSE
);
3947 return loop
->is_running
;
3951 * g_main_loop_get_context:
3952 * @loop: a #GMainLoop.
3954 * Returns the #GMainContext of @loop.
3956 * Return value: (transfer none): the #GMainContext of @loop
3959 g_main_loop_get_context (GMainLoop
*loop
)
3961 g_return_val_if_fail (loop
!= NULL
, NULL
);
3962 g_return_val_if_fail (g_atomic_int_get (&loop
->ref_count
) > 0, NULL
);
3964 return loop
->context
;
3967 /* HOLDS: context's lock */
3969 g_main_context_poll (GMainContext
*context
,
3975 #ifdef G_MAIN_POLL_DEBUG
3981 GPollFunc poll_func
;
3983 if (n_fds
|| timeout
!= 0)
3985 #ifdef G_MAIN_POLL_DEBUG
3986 if (_g_main_poll_debug
)
3988 g_print ("polling context=%p n=%d timeout=%d\n",
3989 context
, n_fds
, timeout
);
3990 poll_timer
= g_timer_new ();
3994 LOCK_CONTEXT (context
);
3996 poll_func
= context
->poll_func
;
3998 UNLOCK_CONTEXT (context
);
3999 if ((*poll_func
) (fds
, n_fds
, timeout
) < 0 && errno
!= EINTR
)
4002 g_warning ("poll(2) failed due to: %s.",
4003 g_strerror (errno
));
4005 /* If g_poll () returns -1, it has already called g_warning() */
4009 #ifdef G_MAIN_POLL_DEBUG
4010 if (_g_main_poll_debug
)
4012 LOCK_CONTEXT (context
);
4014 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
4017 g_timer_elapsed (poll_timer
, NULL
));
4018 g_timer_destroy (poll_timer
);
4019 pollrec
= context
->poll_records
;
4021 while (pollrec
!= NULL
)
4026 if (fds
[i
].fd
== pollrec
->fd
->fd
&&
4027 pollrec
->fd
->events
&&
4030 g_print (" [" G_POLLFD_FORMAT
" :", fds
[i
].fd
);
4031 if (fds
[i
].revents
& G_IO_IN
)
4033 if (fds
[i
].revents
& G_IO_OUT
)
4035 if (fds
[i
].revents
& G_IO_PRI
)
4037 if (fds
[i
].revents
& G_IO_ERR
)
4039 if (fds
[i
].revents
& G_IO_HUP
)
4041 if (fds
[i
].revents
& G_IO_NVAL
)
4047 pollrec
= pollrec
->next
;
4051 UNLOCK_CONTEXT (context
);
4054 } /* if (n_fds || timeout != 0) */
4058 * g_main_context_add_poll:
4059 * @context: (allow-none): a #GMainContext (or %NULL for the default context)
4060 * @fd: a #GPollFD structure holding information about a file
4061 * descriptor to watch.
4062 * @priority: the priority for this file descriptor which should be
4063 * the same as the priority used for g_source_attach() to ensure that the
4064 * file descriptor is polled whenever the results may be needed.
4066 * Adds a file descriptor to the set of file descriptors polled for
4067 * this context. This will very seldom be used directly. Instead
4068 * a typical event source will use g_source_add_unix_fd() instead.
4071 g_main_context_add_poll (GMainContext
*context
,
4076 context
= g_main_context_default ();
4078 g_return_if_fail (g_atomic_int_get (&context
->ref_count
) > 0);
4079 g_return_if_fail (fd
);
4081 LOCK_CONTEXT (context
);
4082 g_main_context_add_poll_unlocked (context
, priority
, fd
);
4083 UNLOCK_CONTEXT (context
);
4086 /* HOLDS: main_loop_lock */
4088 g_main_context_add_poll_unlocked (GMainContext
*context
,
4092 GPollRec
*prevrec
, *nextrec
;
4093 GPollRec
*newrec
= g_slice_new (GPollRec
);
4095 /* This file descriptor may be checked before we ever poll */
4098 newrec
->priority
= priority
;
4100 prevrec
= context
->poll_records_tail
;
4102 while (prevrec
&& priority
< prevrec
->priority
)
4105 prevrec
= prevrec
->prev
;
4109 prevrec
->next
= newrec
;
4111 context
->poll_records
= newrec
;
4113 newrec
->prev
= prevrec
;
4114 newrec
->next
= nextrec
;
4117 nextrec
->prev
= newrec
;
4119 context
->poll_records_tail
= newrec
;
4121 context
->n_poll_records
++;
4123 context
->poll_changed
= TRUE
;
4125 /* Now wake up the main loop if it is waiting in the poll() */
4126 g_wakeup_signal (context
->wakeup
);
4130 * g_main_context_remove_poll:
4131 * @context:a #GMainContext
4132 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
4134 * Removes file descriptor from the set of file descriptors to be
4135 * polled for a particular context.
4138 g_main_context_remove_poll (GMainContext
*context
,
4142 context
= g_main_context_default ();
4144 g_return_if_fail (g_atomic_int_get (&context
->ref_count
) > 0);
4145 g_return_if_fail (fd
);
4147 LOCK_CONTEXT (context
);
4148 g_main_context_remove_poll_unlocked (context
, fd
);
4149 UNLOCK_CONTEXT (context
);
4153 g_main_context_remove_poll_unlocked (GMainContext
*context
,
4156 GPollRec
*pollrec
, *prevrec
, *nextrec
;
4159 pollrec
= context
->poll_records
;
4163 nextrec
= pollrec
->next
;
4164 if (pollrec
->fd
== fd
)
4166 if (prevrec
!= NULL
)
4167 prevrec
->next
= nextrec
;
4169 context
->poll_records
= nextrec
;
4171 if (nextrec
!= NULL
)
4172 nextrec
->prev
= prevrec
;
4174 context
->poll_records_tail
= prevrec
;
4176 g_slice_free (GPollRec
, pollrec
);
4178 context
->n_poll_records
--;
4185 context
->poll_changed
= TRUE
;
4187 /* Now wake up the main loop if it is waiting in the poll() */
4188 g_wakeup_signal (context
->wakeup
);
4192 * g_source_get_current_time:
4193 * @source: a #GSource
4194 * @timeval: #GTimeVal structure in which to store current time.
4196 * This function ignores @source and is otherwise the same as
4197 * g_get_current_time().
4199 * Deprecated: 2.28: use g_source_get_time() instead
4202 g_source_get_current_time (GSource
*source
,
4205 g_get_current_time (timeval
);
4209 * g_source_get_time:
4210 * @source: a #GSource
4212 * Gets the time to be used when checking this source. The advantage of
4213 * calling this function over calling g_get_monotonic_time() directly is
4214 * that when checking multiple sources, GLib can cache a single value
4215 * instead of having to repeatedly get the system monotonic time.
4217 * The time here is the system monotonic time, if available, or some
4218 * other reasonable alternative otherwise. See g_get_monotonic_time().
4220 * Returns: the monotonic time in microseconds
4225 g_source_get_time (GSource
*source
)
4227 GMainContext
*context
;
4230 g_return_val_if_fail (source
->context
!= NULL
, 0);
4232 context
= source
->context
;
4234 LOCK_CONTEXT (context
);
4236 if (!context
->time_is_fresh
)
4238 context
->time
= g_get_monotonic_time ();
4239 context
->time_is_fresh
= TRUE
;
4242 result
= context
->time
;
4244 UNLOCK_CONTEXT (context
);
4250 * g_main_context_set_poll_func:
4251 * @context: a #GMainContext
4252 * @func: the function to call to poll all file descriptors
4254 * Sets the function to use to handle polling of file descriptors. It
4255 * will be used instead of the poll() system call
4256 * (or GLib's replacement function, which is used where
4257 * poll() isn't available).
4259 * This function could possibly be used to integrate the GLib event
4260 * loop with an external event loop.
4263 g_main_context_set_poll_func (GMainContext
*context
,
4267 context
= g_main_context_default ();
4269 g_return_if_fail (g_atomic_int_get (&context
->ref_count
) > 0);
4271 LOCK_CONTEXT (context
);
4274 context
->poll_func
= func
;
4276 context
->poll_func
= g_poll
;
4278 UNLOCK_CONTEXT (context
);
4282 * g_main_context_get_poll_func:
4283 * @context: a #GMainContext
4285 * Gets the poll function set by g_main_context_set_poll_func().
4287 * Return value: the poll function
4290 g_main_context_get_poll_func (GMainContext
*context
)
4295 context
= g_main_context_default ();
4297 g_return_val_if_fail (g_atomic_int_get (&context
->ref_count
) > 0, NULL
);
4299 LOCK_CONTEXT (context
);
4300 result
= context
->poll_func
;
4301 UNLOCK_CONTEXT (context
);
4307 * g_main_context_wakeup:
4308 * @context: a #GMainContext
4310 * If @context is currently waiting in a poll(), interrupt
4311 * the poll(), and continue the iteration process.
4314 g_main_context_wakeup (GMainContext
*context
)
4317 context
= g_main_context_default ();
4319 g_return_if_fail (g_atomic_int_get (&context
->ref_count
) > 0);
4321 g_wakeup_signal (context
->wakeup
);
4325 * g_main_context_is_owner:
4326 * @context: a #GMainContext
4328 * Determines whether this thread holds the (recursive)
4329 * ownership of this #GMainContext. This is useful to
4330 * know before waiting on another thread that may be
4331 * blocking to get ownership of @context.
4333 * Returns: %TRUE if current thread is owner of @context.
4338 g_main_context_is_owner (GMainContext
*context
)
4343 context
= g_main_context_default ();
4345 LOCK_CONTEXT (context
);
4346 is_owner
= context
->owner
== G_THREAD_SELF
;
4347 UNLOCK_CONTEXT (context
);
4355 g_timeout_set_expiration (GTimeoutSource
*timeout_source
,
4356 gint64 current_time
)
4360 expiration
= current_time
+ (guint64
) timeout_source
->interval
* 1000;
4362 if (timeout_source
->seconds
)
4365 static gint timer_perturb
= -1;
4367 if (timer_perturb
== -1)
4370 * we want a per machine/session unique 'random' value; try the dbus
4371 * address first, that has a UUID in it. If there is no dbus, use the
4372 * hostname for hashing.
4374 const char *session_bus_address
= g_getenv ("DBUS_SESSION_BUS_ADDRESS");
4375 if (!session_bus_address
)
4376 session_bus_address
= g_getenv ("HOSTNAME");
4377 if (session_bus_address
)
4378 timer_perturb
= ABS ((gint
) g_str_hash (session_bus_address
)) % 1000000;
4383 /* We want the microseconds part of the timeout to land on the
4384 * 'timer_perturb' mark, but we need to make sure we don't try to
4385 * set the timeout in the past. We do this by ensuring that we
4386 * always only *increase* the expiration time by adding a full
4387 * second in the case that the microsecond portion decreases.
4389 expiration
-= timer_perturb
;
4391 remainder
= expiration
% 1000000;
4392 if (remainder
>= 1000000/4)
4393 expiration
+= 1000000;
4395 expiration
-= remainder
;
4396 expiration
+= timer_perturb
;
4399 g_source_set_ready_time ((GSource
*) timeout_source
, expiration
);
4403 g_timeout_dispatch (GSource
*source
,
4404 GSourceFunc callback
,
4407 GTimeoutSource
*timeout_source
= (GTimeoutSource
*)source
;
4412 g_warning ("Timeout source dispatched without callback\n"
4413 "You must call g_source_set_callback().");
4417 again
= callback (user_data
);
4420 g_timeout_set_expiration (timeout_source
, g_source_get_time (source
));
4426 * g_timeout_source_new:
4427 * @interval: the timeout interval in milliseconds.
4429 * Creates a new timeout source.
4431 * The source will not initially be associated with any #GMainContext
4432 * and must be added to one with g_source_attach() before it will be
4435 * The interval given is in terms of monotonic time, not wall clock
4436 * time. See g_get_monotonic_time().
4438 * Return value: the newly-created timeout source
4441 g_timeout_source_new (guint interval
)
4443 GSource
*source
= g_source_new (&g_timeout_funcs
, sizeof (GTimeoutSource
));
4444 GTimeoutSource
*timeout_source
= (GTimeoutSource
*)source
;
4446 timeout_source
->interval
= interval
;
4447 g_timeout_set_expiration (timeout_source
, g_get_monotonic_time ());
4453 * g_timeout_source_new_seconds:
4454 * @interval: the timeout interval in seconds
4456 * Creates a new timeout source.
4458 * The source will not initially be associated with any #GMainContext
4459 * and must be added to one with g_source_attach() before it will be
4462 * The scheduling granularity/accuracy of this timeout source will be
4465 * The interval given in terms of monotonic time, not wall clock time.
4466 * See g_get_monotonic_time().
4468 * Return value: the newly-created timeout source
4473 g_timeout_source_new_seconds (guint interval
)
4475 GSource
*source
= g_source_new (&g_timeout_funcs
, sizeof (GTimeoutSource
));
4476 GTimeoutSource
*timeout_source
= (GTimeoutSource
*)source
;
4478 timeout_source
->interval
= 1000 * interval
;
4479 timeout_source
->seconds
= TRUE
;
4481 g_timeout_set_expiration (timeout_source
, g_get_monotonic_time ());
4488 * g_timeout_add_full:
4489 * @priority: the priority of the timeout source. Typically this will be in
4490 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4491 * @interval: the time between calls to the function, in milliseconds
4492 * (1/1000ths of a second)
4493 * @function: function to call
4494 * @data: data to pass to @function
4495 * @notify: (allow-none): function to call when the timeout is removed, or %NULL
4497 * Sets a function to be called at regular intervals, with the given
4498 * priority. The function is called repeatedly until it returns
4499 * %FALSE, at which point the timeout is automatically destroyed and
4500 * the function will not be called again. The @notify function is
4501 * called when the timeout is destroyed. The first call to the
4502 * function will be at the end of the first @interval.
4504 * Note that timeout functions may be delayed, due to the processing of other
4505 * event sources. Thus they should not be relied on for precise timing.
4506 * After each call to the timeout function, the time of the next
4507 * timeout is recalculated based on the current time and the given interval
4508 * (it does not try to 'catch up' time lost in delays).
4510 * This internally creates a main loop source using g_timeout_source_new()
4511 * and attaches it to the main loop context using g_source_attach(). You can
4512 * do these steps manually if you need greater control.
4514 * The interval given in terms of monotonic time, not wall clock time.
4515 * See g_get_monotonic_time().
4517 * Return value: the ID (greater than 0) of the event source.
4518 * Rename to: g_timeout_add
4521 g_timeout_add_full (gint priority
,
4523 GSourceFunc function
,
4525 GDestroyNotify notify
)
4530 g_return_val_if_fail (function
!= NULL
, 0);
4532 source
= g_timeout_source_new (interval
);
4534 if (priority
!= G_PRIORITY_DEFAULT
)
4535 g_source_set_priority (source
, priority
);
4537 g_source_set_callback (source
, function
, data
, notify
);
4538 id
= g_source_attach (source
, NULL
);
4539 g_source_unref (source
);
4546 * @interval: the time between calls to the function, in milliseconds
4547 * (1/1000ths of a second)
4548 * @function: function to call
4549 * @data: data to pass to @function
4551 * Sets a function to be called at regular intervals, with the default
4552 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
4553 * until it returns %FALSE, at which point the timeout is automatically
4554 * destroyed and the function will not be called again. The first call
4555 * to the function will be at the end of the first @interval.
4557 * Note that timeout functions may be delayed, due to the processing of other
4558 * event sources. Thus they should not be relied on for precise timing.
4559 * After each call to the timeout function, the time of the next
4560 * timeout is recalculated based on the current time and the given interval
4561 * (it does not try to 'catch up' time lost in delays).
4563 * If you want to have a timer in the "seconds" range and do not care
4564 * about the exact time of the first call of the timer, use the
4565 * g_timeout_add_seconds() function; this function allows for more
4566 * optimizations and more efficient system power usage.
4568 * This internally creates a main loop source using g_timeout_source_new()
4569 * and attaches it to the main loop context using g_source_attach(). You can
4570 * do these steps manually if you need greater control.
4572 * The interval given is in terms of monotonic time, not wall clock
4573 * time. See g_get_monotonic_time().
4575 * Return value: the ID (greater than 0) of the event source.
4578 g_timeout_add (guint32 interval
,
4579 GSourceFunc function
,
4582 return g_timeout_add_full (G_PRIORITY_DEFAULT
,
4583 interval
, function
, data
, NULL
);
4587 * g_timeout_add_seconds_full:
4588 * @priority: the priority of the timeout source. Typically this will be in
4589 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4590 * @interval: the time between calls to the function, in seconds
4591 * @function: function to call
4592 * @data: data to pass to @function
4593 * @notify: (allow-none): function to call when the timeout is removed, or %NULL
4595 * Sets a function to be called at regular intervals, with @priority.
4596 * The function is called repeatedly until it returns %FALSE, at which
4597 * point the timeout is automatically destroyed and the function will
4598 * not be called again.
4600 * Unlike g_timeout_add(), this function operates at whole second granularity.
4601 * The initial starting point of the timer is determined by the implementation
4602 * and the implementation is expected to group multiple timers together so that
4603 * they fire all at the same time.
4604 * To allow this grouping, the @interval to the first timer is rounded
4605 * and can deviate up to one second from the specified interval.
4606 * Subsequent timer iterations will generally run at the specified interval.
4608 * Note that timeout functions may be delayed, due to the processing of other
4609 * event sources. Thus they should not be relied on for precise timing.
4610 * After each call to the timeout function, the time of the next
4611 * timeout is recalculated based on the current time and the given @interval
4613 * If you want timing more precise than whole seconds, use g_timeout_add()
4616 * The grouping of timers to fire at the same time results in a more power
4617 * and CPU efficient behavior so if your timer is in multiples of seconds
4618 * and you don't require the first timer exactly one second from now, the
4619 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
4621 * This internally creates a main loop source using
4622 * g_timeout_source_new_seconds() and attaches it to the main loop context
4623 * using g_source_attach(). You can do these steps manually if you need
4626 * The interval given is in terms of monotonic time, not wall clock
4627 * time. See g_get_monotonic_time().
4629 * Return value: the ID (greater than 0) of the event source.
4631 * Rename to: g_timeout_add_seconds
4635 g_timeout_add_seconds_full (gint priority
,
4637 GSourceFunc function
,
4639 GDestroyNotify notify
)
4644 g_return_val_if_fail (function
!= NULL
, 0);
4646 source
= g_timeout_source_new_seconds (interval
);
4648 if (priority
!= G_PRIORITY_DEFAULT
)
4649 g_source_set_priority (source
, priority
);
4651 g_source_set_callback (source
, function
, data
, notify
);
4652 id
= g_source_attach (source
, NULL
);
4653 g_source_unref (source
);
4659 * g_timeout_add_seconds:
4660 * @interval: the time between calls to the function, in seconds
4661 * @function: function to call
4662 * @data: data to pass to @function
4664 * Sets a function to be called at regular intervals with the default
4665 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4666 * it returns %FALSE, at which point the timeout is automatically destroyed
4667 * and the function will not be called again.
4669 * This internally creates a main loop source using
4670 * g_timeout_source_new_seconds() and attaches it to the main loop context
4671 * using g_source_attach(). You can do these steps manually if you need
4672 * greater control. Also see g_timeout_add_seconds_full().
4674 * Note that the first call of the timer may not be precise for timeouts
4675 * of one second. If you need finer precision and have such a timeout,
4676 * you may want to use g_timeout_add() instead.
4678 * The interval given is in terms of monotonic time, not wall clock
4679 * time. See g_get_monotonic_time().
4681 * Return value: the ID (greater than 0) of the event source.
4686 g_timeout_add_seconds (guint interval
,
4687 GSourceFunc function
,
4690 g_return_val_if_fail (function
!= NULL
, 0);
4692 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT
, interval
, function
, data
, NULL
);
4695 /* Child watch functions */
4700 g_child_watch_prepare (GSource
*source
,
4708 g_child_watch_check (GSource
*source
)
4710 GChildWatchSource
*child_watch_source
;
4711 gboolean child_exited
;
4713 child_watch_source
= (GChildWatchSource
*) source
;
4715 child_exited
= child_watch_source
->poll
.revents
& G_IO_IN
;
4722 * Note: We do _not_ check for the special value of STILL_ACTIVE
4723 * since we know that the process has exited and doing so runs into
4724 * problems if the child process "happens to return STILL_ACTIVE(259)"
4725 * as Microsoft's Platform SDK puts it.
4727 if (!GetExitCodeProcess (child_watch_source
->pid
, &child_status
))
4729 gchar
*emsg
= g_win32_error_message (GetLastError ());
4730 g_warning (G_STRLOC
": GetExitCodeProcess() failed: %s", emsg
);
4733 child_watch_source
->child_status
= -1;
4736 child_watch_source
->child_status
= child_status
;
4739 return child_exited
;
4743 g_child_watch_finalize (GSource
*source
)
4747 #else /* G_OS_WIN32 */
4750 wake_source (GSource
*source
)
4752 GMainContext
*context
;
4754 /* This should be thread-safe:
4756 * - if the source is currently being added to a context, that
4757 * context will be woken up anyway
4759 * - if the source is currently being destroyed, we simply need not
4762 * - the memory for the source will remain valid until after the
4763 * source finalize function was called (which would remove the
4764 * source from the global list which we are currently holding the
4767 * - the GMainContext will either be NULL or point to a live
4770 * - the GMainContext will remain valid since we hold the
4771 * main_context_list lock
4773 * Since we are holding a lot of locks here, don't try to enter any
4774 * more GMainContext functions for fear of dealock -- just hit the
4775 * GWakeup and run. Even if that's safe now, it could easily become
4776 * unsafe with some very minor changes in the future, and signal
4777 * handling is not the most well-tested codepath.
4779 G_LOCK(main_context_list
);
4780 context
= source
->context
;
4782 g_wakeup_signal (context
->wakeup
);
4783 G_UNLOCK(main_context_list
);
4787 dispatch_unix_signals (void)
4791 /* clear this first incase another one arrives while we're processing */
4792 any_unix_signal_pending
= FALSE
;
4794 G_LOCK(unix_signal_lock
);
4796 /* handle GChildWatchSource instances */
4797 if (unix_signal_pending
[SIGCHLD
])
4799 unix_signal_pending
[SIGCHLD
] = FALSE
;
4801 /* The only way we can do this is to scan all of the children.
4803 * The docs promise that we will not reap children that we are not
4804 * explicitly watching, so that ties our hands from calling
4805 * waitpid(-1). We also can't use siginfo's si_pid field since if
4806 * multiple SIGCHLD arrive at the same time, one of them can be
4807 * dropped (since a given UNIX signal can only be pending once).
4809 for (node
= unix_child_watches
; node
; node
= node
->next
)
4811 GChildWatchSource
*source
= node
->data
;
4813 if (!source
->child_exited
)
4818 pid
= waitpid (source
->pid
, &source
->child_status
, WNOHANG
);
4821 source
->child_exited
= TRUE
;
4822 wake_source ((GSource
*) source
);
4824 else if (pid
== -1 && errno
== ECHILD
)
4826 g_warning ("GChildWatchSource: Exit status of a child process was requested but ECHILD was received by waitpid(). Most likely the process is ignoring SIGCHLD, or some other thread is invoking waitpid() with a nonpositive first argument; either behavior can break applications that use g_child_watch_add()/g_spawn_sync() either directly or indirectly.");
4827 source
->child_exited
= TRUE
;
4828 source
->child_status
= 0;
4829 wake_source ((GSource
*) source
);
4832 while (pid
== -1 && errno
== EINTR
);
4837 /* handle GUnixSignalWatchSource instances */
4838 for (node
= unix_signal_watches
; node
; node
= node
->next
)
4840 GUnixSignalWatchSource
*source
= node
->data
;
4842 if (!source
->pending
)
4844 if (unix_signal_pending
[source
->signum
])
4846 unix_signal_pending
[source
->signum
] = FALSE
;
4847 source
->pending
= TRUE
;
4849 wake_source ((GSource
*) source
);
4854 G_UNLOCK(unix_signal_lock
);
4858 g_child_watch_prepare (GSource
*source
,
4861 GChildWatchSource
*child_watch_source
;
4863 child_watch_source
= (GChildWatchSource
*) source
;
4865 return child_watch_source
->child_exited
;
4869 g_child_watch_check (GSource
*source
)
4871 GChildWatchSource
*child_watch_source
;
4873 child_watch_source
= (GChildWatchSource
*) source
;
4875 return child_watch_source
->child_exited
;
4879 g_unix_signal_watch_prepare (GSource
*source
,
4882 GUnixSignalWatchSource
*unix_signal_source
;
4884 unix_signal_source
= (GUnixSignalWatchSource
*) source
;
4886 return unix_signal_source
->pending
;
4890 g_unix_signal_watch_check (GSource
*source
)
4892 GUnixSignalWatchSource
*unix_signal_source
;
4894 unix_signal_source
= (GUnixSignalWatchSource
*) source
;
4896 return unix_signal_source
->pending
;
4900 g_unix_signal_watch_dispatch (GSource
*source
,
4901 GSourceFunc callback
,
4904 GUnixSignalWatchSource
*unix_signal_source
;
4907 unix_signal_source
= (GUnixSignalWatchSource
*) source
;
4911 g_warning ("Unix signal source dispatched without callback\n"
4912 "You must call g_source_set_callback().");
4916 again
= (callback
) (user_data
);
4918 unix_signal_source
->pending
= FALSE
;
4924 ensure_unix_signal_handler_installed_unlocked (int signum
)
4926 static sigset_t installed_signal_mask
;
4927 static gboolean initialized
;
4928 struct sigaction action
;
4932 sigemptyset (&installed_signal_mask
);
4933 g_get_worker_context ();
4937 if (sigismember (&installed_signal_mask
, signum
))
4940 sigaddset (&installed_signal_mask
, signum
);
4942 action
.sa_handler
= g_unix_signal_handler
;
4943 sigemptyset (&action
.sa_mask
);
4944 action
.sa_flags
= SA_RESTART
| SA_NOCLDSTOP
;
4945 sigaction (signum
, &action
, NULL
);
4949 _g_main_create_unix_signal_watch (int signum
)
4952 GUnixSignalWatchSource
*unix_signal_source
;
4954 source
= g_source_new (&g_unix_signal_funcs
, sizeof (GUnixSignalWatchSource
));
4955 unix_signal_source
= (GUnixSignalWatchSource
*) source
;
4957 unix_signal_source
->signum
= signum
;
4958 unix_signal_source
->pending
= FALSE
;
4960 G_LOCK (unix_signal_lock
);
4961 ensure_unix_signal_handler_installed_unlocked (signum
);
4962 unix_signal_watches
= g_slist_prepend (unix_signal_watches
, unix_signal_source
);
4963 if (unix_signal_pending
[signum
])
4964 unix_signal_source
->pending
= TRUE
;
4965 unix_signal_pending
[signum
] = FALSE
;
4966 G_UNLOCK (unix_signal_lock
);
4972 g_unix_signal_watch_finalize (GSource
*source
)
4974 G_LOCK (unix_signal_lock
);
4975 unix_signal_watches
= g_slist_remove (unix_signal_watches
, source
);
4976 G_UNLOCK (unix_signal_lock
);
4980 g_child_watch_finalize (GSource
*source
)
4982 G_LOCK (unix_signal_lock
);
4983 unix_child_watches
= g_slist_remove (unix_child_watches
, source
);
4984 G_UNLOCK (unix_signal_lock
);
4987 #endif /* G_OS_WIN32 */
4990 g_child_watch_dispatch (GSource
*source
,
4991 GSourceFunc callback
,
4994 GChildWatchSource
*child_watch_source
;
4995 GChildWatchFunc child_watch_callback
= (GChildWatchFunc
) callback
;
4997 child_watch_source
= (GChildWatchSource
*) source
;
5001 g_warning ("Child watch source dispatched without callback\n"
5002 "You must call g_source_set_callback().");
5006 (child_watch_callback
) (child_watch_source
->pid
, child_watch_source
->child_status
, user_data
);
5008 /* We never keep a child watch source around as the child is gone */
5015 g_unix_signal_handler (int signum
)
5017 unix_signal_pending
[signum
] = TRUE
;
5018 any_unix_signal_pending
= TRUE
;
5020 g_wakeup_signal (glib_worker_context
->wakeup
);
5023 #endif /* !G_OS_WIN32 */
5026 * g_child_watch_source_new:
5027 * @pid: process to watch. On POSIX the pid of a child process. On
5028 * Windows a handle for a process (which doesn't have to be a child).
5030 * Creates a new child_watch source.
5032 * The source will not initially be associated with any #GMainContext
5033 * and must be added to one with g_source_attach() before it will be
5036 * Note that child watch sources can only be used in conjunction with
5037 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
5040 * Note that on platforms where #GPid must be explicitly closed
5041 * (see g_spawn_close_pid()) @pid must not be closed while the
5042 * source is still active. Typically, you will want to call
5043 * g_spawn_close_pid() in the callback function for the source.
5045 * Note further that using g_child_watch_source_new() is not
5046 * compatible with calling <literal>waitpid</literal> with a
5047 * nonpositive first argument in the application. Calling waitpid()
5048 * for individual pids will still work fine.
5050 * Return value: the newly-created child watch source
5055 g_child_watch_source_new (GPid pid
)
5057 GSource
*source
= g_source_new (&g_child_watch_funcs
, sizeof (GChildWatchSource
));
5058 GChildWatchSource
*child_watch_source
= (GChildWatchSource
*)source
;
5060 child_watch_source
->pid
= pid
;
5063 child_watch_source
->poll
.fd
= (gintptr
) pid
;
5064 child_watch_source
->poll
.events
= G_IO_IN
;
5066 g_source_add_poll (source
, &child_watch_source
->poll
);
5067 #else /* G_OS_WIN32 */
5068 G_LOCK (unix_signal_lock
);
5069 ensure_unix_signal_handler_installed_unlocked (SIGCHLD
);
5070 unix_child_watches
= g_slist_prepend (unix_child_watches
, child_watch_source
);
5071 if (waitpid (pid
, &child_watch_source
->child_status
, WNOHANG
) > 0)
5072 child_watch_source
->child_exited
= TRUE
;
5073 G_UNLOCK (unix_signal_lock
);
5074 #endif /* G_OS_WIN32 */
5080 * g_child_watch_add_full:
5081 * @priority: the priority of the idle source. Typically this will be in the
5082 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
5083 * @pid: process to watch. On POSIX the pid of a child process. On
5084 * Windows a handle for a process (which doesn't have to be a child).
5085 * @function: function to call
5086 * @data: data to pass to @function
5087 * @notify: (allow-none): function to call when the idle is removed, or %NULL
5089 * Sets a function to be called when the child indicated by @pid
5090 * exits, at the priority @priority.
5092 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
5093 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
5094 * the spawn function for the child watching to work.
5096 * In many programs, you will want to call g_spawn_check_exit_status()
5097 * in the callback to determine whether or not the child exited
5100 * Also, note that on platforms where #GPid must be explicitly closed
5101 * (see g_spawn_close_pid()) @pid must not be closed while the source
5102 * is still active. Typically, you should invoke g_spawn_close_pid()
5103 * in the callback function for the source.
5105 * GLib supports only a single callback per process id.
5107 * This internally creates a main loop source using
5108 * g_child_watch_source_new() and attaches it to the main loop context
5109 * using g_source_attach(). You can do these steps manually if you
5110 * need greater control.
5112 * Return value: the ID (greater than 0) of the event source.
5114 * Rename to: g_child_watch_add
5118 g_child_watch_add_full (gint priority
,
5120 GChildWatchFunc function
,
5122 GDestroyNotify notify
)
5127 g_return_val_if_fail (function
!= NULL
, 0);
5129 source
= g_child_watch_source_new (pid
);
5131 if (priority
!= G_PRIORITY_DEFAULT
)
5132 g_source_set_priority (source
, priority
);
5134 g_source_set_callback (source
, (GSourceFunc
) function
, data
, notify
);
5135 id
= g_source_attach (source
, NULL
);
5136 g_source_unref (source
);
5142 * g_child_watch_add:
5143 * @pid: process id to watch. On POSIX the pid of a child process. On
5144 * Windows a handle for a process (which doesn't have to be a child).
5145 * @function: function to call
5146 * @data: data to pass to @function
5148 * Sets a function to be called when the child indicated by @pid
5149 * exits, at a default priority, #G_PRIORITY_DEFAULT.
5151 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
5152 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
5153 * the spawn function for the child watching to work.
5155 * Note that on platforms where #GPid must be explicitly closed
5156 * (see g_spawn_close_pid()) @pid must not be closed while the
5157 * source is still active. Typically, you will want to call
5158 * g_spawn_close_pid() in the callback function for the source.
5160 * GLib supports only a single callback per process id.
5162 * This internally creates a main loop source using
5163 * g_child_watch_source_new() and attaches it to the main loop context
5164 * using g_source_attach(). You can do these steps manually if you
5165 * need greater control.
5167 * Return value: the ID (greater than 0) of the event source.
5172 g_child_watch_add (GPid pid
,
5173 GChildWatchFunc function
,
5176 return g_child_watch_add_full (G_PRIORITY_DEFAULT
, pid
, function
, data
, NULL
);
5180 /* Idle functions */
5183 g_idle_prepare (GSource
*source
,
5192 g_idle_check (GSource
*source
)
5198 g_idle_dispatch (GSource
*source
,
5199 GSourceFunc callback
,
5204 g_warning ("Idle source dispatched without callback\n"
5205 "You must call g_source_set_callback().");
5209 return callback (user_data
);
5213 * g_idle_source_new:
5215 * Creates a new idle source.
5217 * The source will not initially be associated with any #GMainContext
5218 * and must be added to one with g_source_attach() before it will be
5219 * executed. Note that the default priority for idle sources is
5220 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
5221 * have a default priority of %G_PRIORITY_DEFAULT.
5223 * Return value: the newly-created idle source
5226 g_idle_source_new (void)
5230 source
= g_source_new (&g_idle_funcs
, sizeof (GSource
));
5231 g_source_set_priority (source
, G_PRIORITY_DEFAULT_IDLE
);
5238 * @priority: the priority of the idle source. Typically this will be in the
5239 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
5240 * @function: function to call
5241 * @data: data to pass to @function
5242 * @notify: (allow-none): function to call when the idle is removed, or %NULL
5244 * Adds a function to be called whenever there are no higher priority
5245 * events pending. If the function returns %FALSE it is automatically
5246 * removed from the list of event sources and will not be called again.
5248 * This internally creates a main loop source using g_idle_source_new()
5249 * and attaches it to the main loop context using g_source_attach().
5250 * You can do these steps manually if you need greater control.
5252 * Return value: the ID (greater than 0) of the event source.
5253 * Rename to: g_idle_add
5256 g_idle_add_full (gint priority
,
5257 GSourceFunc function
,
5259 GDestroyNotify notify
)
5264 g_return_val_if_fail (function
!= NULL
, 0);
5266 source
= g_idle_source_new ();
5268 if (priority
!= G_PRIORITY_DEFAULT_IDLE
)
5269 g_source_set_priority (source
, priority
);
5271 g_source_set_callback (source
, function
, data
, notify
);
5272 id
= g_source_attach (source
, NULL
);
5273 g_source_unref (source
);
5280 * @function: function to call
5281 * @data: data to pass to @function.
5283 * Adds a function to be called whenever there are no higher priority
5284 * events pending to the default main loop. The function is given the
5285 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
5286 * returns %FALSE it is automatically removed from the list of event
5287 * sources and will not be called again.
5289 * This internally creates a main loop source using g_idle_source_new()
5290 * and attaches it to the main loop context using g_source_attach().
5291 * You can do these steps manually if you need greater control.
5293 * Return value: the ID (greater than 0) of the event source.
5296 g_idle_add (GSourceFunc function
,
5299 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE
, function
, data
, NULL
);
5303 * g_idle_remove_by_data:
5304 * @data: the data for the idle source's callback.
5306 * Removes the idle function with the given data.
5308 * Return value: %TRUE if an idle source was found and removed.
5311 g_idle_remove_by_data (gpointer data
)
5313 return g_source_remove_by_funcs_user_data (&g_idle_funcs
, data
);
5317 * g_main_context_invoke:
5318 * @context: (allow-none): a #GMainContext, or %NULL
5319 * @function: function to call
5320 * @data: data to pass to @function
5322 * Invokes a function in such a way that @context is owned during the
5323 * invocation of @function.
5325 * If @context is %NULL then the global default main context — as
5326 * returned by g_main_context_default() — is used.
5328 * If @context is owned by the current thread, @function is called
5329 * directly. Otherwise, if @context is the thread-default main context
5330 * of the current thread and g_main_context_acquire() succeeds, then
5331 * @function is called and g_main_context_release() is called
5334 * In any other case, an idle source is created to call @function and
5335 * that source is attached to @context (presumably to be run in another
5336 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
5337 * priority. If you want a different priority, use
5338 * g_main_context_invoke_full().
5340 * Note that, as with normal idle functions, @function should probably
5341 * return %FALSE. If it returns %TRUE, it will be continuously run in a
5342 * loop (and may prevent this call from returning).
5347 g_main_context_invoke (GMainContext
*context
,
5348 GSourceFunc function
,
5351 g_main_context_invoke_full (context
,
5353 function
, data
, NULL
);
5357 * g_main_context_invoke_full:
5358 * @context: (allow-none): a #GMainContext, or %NULL
5359 * @priority: the priority at which to run @function
5360 * @function: function to call
5361 * @data: data to pass to @function
5362 * @notify: (allow-none): a function to call when @data is no longer in use, or %NULL.
5364 * Invokes a function in such a way that @context is owned during the
5365 * invocation of @function.
5367 * This function is the same as g_main_context_invoke() except that it
5368 * lets you specify the priority incase @function ends up being
5369 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
5371 * @notify should not assume that it is called from any particular
5372 * thread or with any particular context acquired.
5377 g_main_context_invoke_full (GMainContext
*context
,
5379 GSourceFunc function
,
5381 GDestroyNotify notify
)
5383 g_return_if_fail (function
!= NULL
);
5386 context
= g_main_context_default ();
5388 if (g_main_context_is_owner (context
))
5390 while (function (data
));
5397 GMainContext
*thread_default
;
5399 thread_default
= g_main_context_get_thread_default ();
5401 if (!thread_default
)
5402 thread_default
= g_main_context_default ();
5404 if (thread_default
== context
&& g_main_context_acquire (context
))
5406 while (function (data
));
5408 g_main_context_release (context
);
5417 source
= g_idle_source_new ();
5418 g_source_set_priority (source
, priority
);
5419 g_source_set_callback (source
, function
, data
, notify
);
5420 g_source_attach (source
, context
);
5421 g_source_unref (source
);
5427 glib_worker_main (gpointer data
)
5431 g_main_context_iteration (glib_worker_context
, TRUE
);
5434 if (any_unix_signal_pending
)
5435 dispatch_unix_signals ();
5439 return NULL
; /* worst GCC warning message ever... */
5443 g_get_worker_context (void)
5445 static gsize initialised
;
5447 if (g_once_init_enter (&initialised
))
5449 /* mask all signals in the worker thread */
5455 pthread_sigmask (SIG_SETMASK
, &all
, &prev_mask
);
5457 glib_worker_context
= g_main_context_new ();
5458 g_thread_new ("gmain", glib_worker_main
, NULL
);
5460 pthread_sigmask (SIG_SETMASK
, &prev_mask
, NULL
);
5462 g_once_init_leave (&initialised
, TRUE
);
5465 return glib_worker_context
;