application: Use printerr for runtime errors
[glib.git] / glib / gmain.c
blob09003746c1d79da09c0ea5c708724859865c8b4e
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/.
31 * MT safe
34 #include "config.h"
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 */
43 #ifdef _WIN32
44 /* Always enable debugging printout on Windows, as it is more often
45 * needed there...
47 #define G_MAIN_POLL_DEBUG
48 #endif
50 #ifdef G_OS_UNIX
51 #include "glib-unix.h"
52 #include <pthread.h>
53 #ifdef HAVE_EVENTFD
54 #include <sys/eventfd.h>
55 #endif
56 #endif
58 #include <signal.h>
59 #include <sys/types.h>
60 #include <time.h>
61 #include <stdlib.h>
62 #ifdef HAVE_SYS_TIME_H
63 #include <sys/time.h>
64 #endif /* HAVE_SYS_TIME_H */
65 #ifdef G_OS_UNIX
66 #include <unistd.h>
67 #endif /* G_OS_UNIX */
68 #include <errno.h>
69 #include <string.h>
71 #ifdef G_OS_WIN32
72 #define STRICT
73 #include <windows.h>
74 #endif /* G_OS_WIN32 */
76 #include "glib_trace.h"
78 #include "gmain.h"
80 #include "garray.h"
81 #include "giochannel.h"
82 #include "ghash.h"
83 #include "ghook.h"
84 #include "gqueue.h"
85 #include "gstrfuncs.h"
86 #include "gtestutils.h"
88 #ifdef G_OS_WIN32
89 #include "gwin32.h"
90 #endif
92 #ifdef G_MAIN_POLL_DEBUG
93 #include "gtimer.h"
94 #endif
96 #include "gwakeup.h"
97 #include "gmain-internal.h"
98 #include "glib-init.h"
99 #include "glib-private.h"
102 * SECTION:main
103 * @title: The Main Event Loop
104 * @short_description: manages all available sources of events
106 * The main event loop manages all the available sources of events for
107 * GLib and GTK+ applications. These events can come from any number of
108 * different types of sources such as file descriptors (plain files,
109 * pipes or sockets) and timeouts. New types of event sources can also
110 * be added using g_source_attach().
112 * To allow multiple independent sets of sources to be handled in
113 * different threads, each source is associated with a #GMainContext.
114 * A GMainContext can only be running in a single thread, but
115 * sources can be added to it and removed from it from other threads.
117 * Each event source is assigned a priority. The default priority,
118 * #G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
119 * Values greater than 0 denote lower priorities. Events from high priority
120 * sources are always processed before events from lower priority sources.
122 * Idle functions can also be added, and assigned a priority. These will
123 * be run whenever no events with a higher priority are ready to be processed.
125 * The #GMainLoop data type represents a main event loop. A GMainLoop is
126 * created with g_main_loop_new(). After adding the initial event sources,
127 * g_main_loop_run() is called. This continuously checks for new events from
128 * each of the event sources and dispatches them. Finally, the processing of
129 * an event from one of the sources leads to a call to g_main_loop_quit() to
130 * exit the main loop, and g_main_loop_run() returns.
132 * It is possible to create new instances of #GMainLoop recursively.
133 * This is often used in GTK+ applications when showing modal dialog
134 * boxes. Note that event sources are associated with a particular
135 * #GMainContext, and will be checked and dispatched for all main
136 * loops associated with that GMainContext.
138 * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
139 * gtk_main_quit() and gtk_events_pending().
141 * <refsect2><title>Creating new source types</title>
142 * <para>One of the unusual features of the #GMainLoop functionality
143 * is that new types of event source can be created and used in
144 * addition to the builtin type of event source. A new event source
145 * type is used for handling GDK events. A new source type is created
146 * by <firstterm>deriving</firstterm> from the #GSource structure.
147 * The derived type of source is represented by a structure that has
148 * the #GSource structure as a first element, and other elements specific
149 * to the new source type. To create an instance of the new source type,
150 * call g_source_new() passing in the size of the derived structure and
151 * a table of functions. These #GSourceFuncs determine the behavior of
152 * the new source type.</para>
153 * <para>New source types basically interact with the main context
154 * in two ways. Their prepare function in #GSourceFuncs can set a timeout
155 * to determine the maximum amount of time that the main loop will sleep
156 * before checking the source again. In addition, or as well, the source
157 * can add file descriptors to the set that the main context checks using
158 * g_source_add_poll().</para>
159 * </refsect2>
160 * <refsect2><title>Customizing the main loop iteration</title>
161 * <para>Single iterations of a #GMainContext can be run with
162 * g_main_context_iteration(). In some cases, more detailed control
163 * of exactly how the details of the main loop work is desired, for
164 * instance, when integrating the #GMainLoop with an external main loop.
165 * In such cases, you can call the component functions of
166 * g_main_context_iteration() directly. These functions are
167 * g_main_context_prepare(), g_main_context_query(),
168 * g_main_context_check() and g_main_context_dispatch().</para>
169 * <para>The operation of these functions can best be seen in terms
170 * of a state diagram, as shown in <xref linkend="mainloop-states"/>.</para>
171 * <figure id="mainloop-states"><title>States of a Main Context</title>
172 * <graphic fileref="mainloop-states.gif" format="GIF"></graphic>
173 * </figure>
174 * </refsect2>
176 * On Unix, the GLib mainloop is incompatible with fork(). Any program
177 * using the mainloop must either exec() or exit() from the child
178 * without returning to the mainloop.
181 /* Types */
183 typedef struct _GTimeoutSource GTimeoutSource;
184 typedef struct _GChildWatchSource GChildWatchSource;
185 typedef struct _GUnixSignalWatchSource GUnixSignalWatchSource;
186 typedef struct _GPollRec GPollRec;
187 typedef struct _GSourceCallback GSourceCallback;
189 typedef enum
191 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
192 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1),
193 G_SOURCE_BLOCKED = 1 << (G_HOOK_FLAG_USER_SHIFT + 2)
194 } GSourceFlags;
196 typedef struct _GSourceList GSourceList;
198 struct _GSourceList
200 GSource *head, *tail;
201 gint priority;
204 typedef struct _GMainWaiter GMainWaiter;
206 struct _GMainWaiter
208 GCond *cond;
209 GMutex *mutex;
212 typedef struct _GMainDispatch GMainDispatch;
214 struct _GMainDispatch
216 gint depth;
217 GSource *source;
220 #ifdef G_MAIN_POLL_DEBUG
221 gboolean _g_main_poll_debug = FALSE;
222 #endif
224 struct _GMainContext
226 /* The following lock is used for both the list of sources
227 * and the list of poll records
229 GMutex mutex;
230 GCond cond;
231 GThread *owner;
232 guint owner_count;
233 GSList *waiters;
235 gint ref_count;
237 GPtrArray *pending_dispatches;
238 gint timeout; /* Timeout for current iteration */
240 guint next_id;
241 GHashTable *overflow_used_source_ids; /* set<guint> */
242 GList *source_lists;
243 gint in_check_or_prepare;
245 GPollRec *poll_records, *poll_records_tail;
246 guint n_poll_records;
247 GPollFD *cached_poll_array;
248 guint cached_poll_array_size;
250 GWakeup *wakeup;
252 GPollFD wake_up_rec;
254 /* Flag indicating whether the set of fd's changed during a poll */
255 gboolean poll_changed;
257 GPollFunc poll_func;
259 gint64 time;
260 gboolean time_is_fresh;
263 struct _GSourceCallback
265 guint ref_count;
266 GSourceFunc func;
267 gpointer data;
268 GDestroyNotify notify;
271 struct _GMainLoop
273 GMainContext *context;
274 gboolean is_running;
275 gint ref_count;
278 struct _GTimeoutSource
280 GSource source;
281 guint interval;
282 gboolean seconds;
285 struct _GChildWatchSource
287 GSource source;
288 GPid pid;
289 gint child_status;
290 #ifdef G_OS_WIN32
291 GPollFD poll;
292 #else /* G_OS_WIN32 */
293 gboolean child_exited;
294 #endif /* G_OS_WIN32 */
297 struct _GUnixSignalWatchSource
299 GSource source;
300 int signum;
301 gboolean pending;
304 struct _GPollRec
306 GPollFD *fd;
307 GPollRec *prev;
308 GPollRec *next;
309 gint priority;
312 struct _GSourcePrivate
314 GSList *child_sources;
315 GSource *parent_source;
317 gint64 ready_time;
319 /* This is currently only used on UNIX, but we always declare it (and
320 * let it remain empty on Windows) to avoid #ifdef all over the place.
322 GSList *fds;
325 typedef struct _GSourceIter
327 GMainContext *context;
328 gboolean may_modify;
329 GList *current_list;
330 GSource *source;
331 } GSourceIter;
333 #define LOCK_CONTEXT(context) g_mutex_lock (&context->mutex)
334 #define UNLOCK_CONTEXT(context) g_mutex_unlock (&context->mutex)
335 #define G_THREAD_SELF g_thread_self ()
337 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
338 #define SOURCE_BLOCKED(source) (((source)->flags & G_SOURCE_BLOCKED) != 0)
340 #define SOURCE_UNREF(source, context) \
341 G_STMT_START { \
342 if ((source)->ref_count > 1) \
343 (source)->ref_count--; \
344 else \
345 g_source_unref_internal ((source), (context), TRUE); \
346 } G_STMT_END
349 /* Forward declarations */
351 static void g_source_unref_internal (GSource *source,
352 GMainContext *context,
353 gboolean have_lock);
354 static void g_source_destroy_internal (GSource *source,
355 GMainContext *context,
356 gboolean have_lock);
357 static void g_source_set_priority_unlocked (GSource *source,
358 GMainContext *context,
359 gint priority);
360 static void g_child_source_remove_internal (GSource *child_source,
361 GMainContext *context);
363 static void g_main_context_poll (GMainContext *context,
364 gint timeout,
365 gint priority,
366 GPollFD *fds,
367 gint n_fds);
368 static void g_main_context_add_poll_unlocked (GMainContext *context,
369 gint priority,
370 GPollFD *fd);
371 static void g_main_context_remove_poll_unlocked (GMainContext *context,
372 GPollFD *fd);
374 static void g_source_iter_init (GSourceIter *iter,
375 GMainContext *context,
376 gboolean may_modify);
377 static gboolean g_source_iter_next (GSourceIter *iter,
378 GSource **source);
379 static void g_source_iter_clear (GSourceIter *iter);
381 static gboolean g_timeout_dispatch (GSource *source,
382 GSourceFunc callback,
383 gpointer user_data);
384 static gboolean g_child_watch_prepare (GSource *source,
385 gint *timeout);
386 static gboolean g_child_watch_check (GSource *source);
387 static gboolean g_child_watch_dispatch (GSource *source,
388 GSourceFunc callback,
389 gpointer user_data);
390 static void g_child_watch_finalize (GSource *source);
391 #ifdef G_OS_UNIX
392 static void g_unix_signal_handler (int signum);
393 static gboolean g_unix_signal_watch_prepare (GSource *source,
394 gint *timeout);
395 static gboolean g_unix_signal_watch_check (GSource *source);
396 static gboolean g_unix_signal_watch_dispatch (GSource *source,
397 GSourceFunc callback,
398 gpointer user_data);
399 static void g_unix_signal_watch_finalize (GSource *source);
400 #endif
401 static gboolean g_idle_prepare (GSource *source,
402 gint *timeout);
403 static gboolean g_idle_check (GSource *source);
404 static gboolean g_idle_dispatch (GSource *source,
405 GSourceFunc callback,
406 gpointer user_data);
408 static void block_source (GSource *source);
410 static GMainContext *glib_worker_context;
412 G_LOCK_DEFINE_STATIC (main_loop);
413 static GMainContext *default_main_context;
415 #ifndef G_OS_WIN32
418 /* UNIX signals work by marking one of these variables then waking the
419 * worker context to check on them and dispatch accordingly.
421 #ifdef HAVE_SIG_ATOMIC_T
422 static volatile sig_atomic_t unix_signal_pending[NSIG];
423 static volatile sig_atomic_t any_unix_signal_pending;
424 #else
425 static volatile int unix_signal_pending[NSIG];
426 static volatile int any_unix_signal_pending;
427 #endif
428 static volatile guint unix_signal_refcount[NSIG];
430 /* Guards all the data below */
431 G_LOCK_DEFINE_STATIC (unix_signal_lock);
432 static GSList *unix_signal_watches;
433 static GSList *unix_child_watches;
435 GSourceFuncs g_unix_signal_funcs =
437 g_unix_signal_watch_prepare,
438 g_unix_signal_watch_check,
439 g_unix_signal_watch_dispatch,
440 g_unix_signal_watch_finalize
442 #endif /* !G_OS_WIN32 */
443 G_LOCK_DEFINE_STATIC (main_context_list);
444 static GSList *main_context_list = NULL;
446 GSourceFuncs g_timeout_funcs =
448 NULL, /* prepare */
449 NULL, /* check */
450 g_timeout_dispatch,
451 NULL
454 GSourceFuncs g_child_watch_funcs =
456 g_child_watch_prepare,
457 g_child_watch_check,
458 g_child_watch_dispatch,
459 g_child_watch_finalize
462 GSourceFuncs g_idle_funcs =
464 g_idle_prepare,
465 g_idle_check,
466 g_idle_dispatch,
467 NULL
471 * g_main_context_ref:
472 * @context: a #GMainContext
474 * Increases the reference count on a #GMainContext object by one.
476 * Returns: the @context that was passed in (since 2.6)
478 GMainContext *
479 g_main_context_ref (GMainContext *context)
481 g_return_val_if_fail (context != NULL, NULL);
482 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
484 g_atomic_int_inc (&context->ref_count);
486 return context;
489 static inline void
490 poll_rec_list_free (GMainContext *context,
491 GPollRec *list)
493 g_slice_free_chain (GPollRec, list, next);
497 * g_main_context_unref:
498 * @context: a #GMainContext
500 * Decreases the reference count on a #GMainContext object by one. If
501 * the result is zero, free the context and free all associated memory.
503 void
504 g_main_context_unref (GMainContext *context)
506 GSourceIter iter;
507 GSource *source;
508 GList *sl_iter;
509 GSourceList *list;
511 g_return_if_fail (context != NULL);
512 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
514 if (!g_atomic_int_dec_and_test (&context->ref_count))
515 return;
517 G_LOCK (main_context_list);
518 main_context_list = g_slist_remove (main_context_list, context);
519 G_UNLOCK (main_context_list);
521 /* g_source_iter_next() assumes the context is locked. */
522 LOCK_CONTEXT (context);
523 g_source_iter_init (&iter, context, TRUE);
524 while (g_source_iter_next (&iter, &source))
526 source->context = NULL;
527 g_source_destroy_internal (source, context, TRUE);
529 UNLOCK_CONTEXT (context);
531 for (sl_iter = context->source_lists; sl_iter; sl_iter = sl_iter->next)
533 list = sl_iter->data;
534 g_slice_free (GSourceList, list);
536 g_list_free (context->source_lists);
538 if (context->overflow_used_source_ids)
539 g_hash_table_destroy (context->overflow_used_source_ids);
541 g_mutex_clear (&context->mutex);
543 g_ptr_array_free (context->pending_dispatches, TRUE);
544 g_free (context->cached_poll_array);
546 poll_rec_list_free (context, context->poll_records);
548 g_wakeup_free (context->wakeup);
549 g_cond_clear (&context->cond);
551 g_free (context);
554 /* Helper function used by mainloop/overflow test.
556 GMainContext *
557 g_main_context_new_with_next_id (guint next_id)
559 GMainContext *ret = g_main_context_new ();
561 ret->next_id = next_id;
563 return ret;
567 * g_main_context_new:
569 * Creates a new #GMainContext structure.
571 * Return value: the new #GMainContext
573 GMainContext *
574 g_main_context_new (void)
576 static gsize initialised;
577 GMainContext *context;
579 if (g_once_init_enter (&initialised))
581 #ifdef G_MAIN_POLL_DEBUG
582 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
583 _g_main_poll_debug = TRUE;
584 #endif
586 g_once_init_leave (&initialised, TRUE);
589 context = g_new0 (GMainContext, 1);
591 g_mutex_init (&context->mutex);
592 g_cond_init (&context->cond);
594 context->owner = NULL;
595 context->waiters = NULL;
597 context->ref_count = 1;
599 context->next_id = 1;
601 context->source_lists = NULL;
603 context->poll_func = g_poll;
605 context->cached_poll_array = NULL;
606 context->cached_poll_array_size = 0;
608 context->pending_dispatches = g_ptr_array_new ();
610 context->time_is_fresh = FALSE;
612 context->wakeup = g_wakeup_new ();
613 g_wakeup_get_pollfd (context->wakeup, &context->wake_up_rec);
614 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
616 G_LOCK (main_context_list);
617 main_context_list = g_slist_append (main_context_list, context);
619 #ifdef G_MAIN_POLL_DEBUG
620 if (_g_main_poll_debug)
621 g_print ("created context=%p\n", context);
622 #endif
624 G_UNLOCK (main_context_list);
626 return context;
630 * g_main_context_default:
632 * Returns the global default main context. This is the main context
633 * used for main loop functions when a main loop is not explicitly
634 * specified, and corresponds to the "main" main loop. See also
635 * g_main_context_get_thread_default().
637 * Return value: (transfer none): the global default main context.
639 GMainContext *
640 g_main_context_default (void)
642 /* Slow, but safe */
644 G_LOCK (main_loop);
646 if (!default_main_context)
648 default_main_context = g_main_context_new ();
649 #ifdef G_MAIN_POLL_DEBUG
650 if (_g_main_poll_debug)
651 g_print ("default context=%p\n", default_main_context);
652 #endif
655 G_UNLOCK (main_loop);
657 return default_main_context;
660 static void
661 free_context (gpointer data)
663 GMainContext *context = data;
665 g_main_context_release (context);
666 if (context)
667 g_main_context_unref (context);
670 static void
671 free_context_stack (gpointer data)
673 g_queue_free_full((GQueue *) data, (GDestroyNotify) free_context);
676 static GPrivate thread_context_stack = G_PRIVATE_INIT (free_context_stack);
679 * g_main_context_push_thread_default:
680 * @context: (allow-none): a #GMainContext, or %NULL for the global default context
682 * Acquires @context and sets it as the thread-default context for the
683 * current thread. This will cause certain asynchronous operations
684 * (such as most <link linkend="gio">gio</link>-based I/O) which are
685 * started in this thread to run under @context and deliver their
686 * results to its main loop, rather than running under the global
687 * default context in the main thread. Note that calling this function
688 * changes the context returned by
689 * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
690 * one returned by g_main_context_default(), so it does not affect the
691 * context used by functions like g_idle_add().
693 * Normally you would call this function shortly after creating a new
694 * thread, passing it a #GMainContext which will be run by a
695 * #GMainLoop in that thread, to set a new default context for all
696 * async operations in that thread. (In this case, you don't need to
697 * ever call g_main_context_pop_thread_default().) In some cases
698 * however, you may want to schedule a single operation in a
699 * non-default context, or temporarily use a non-default context in
700 * the main thread. In that case, you can wrap the call to the
701 * asynchronous operation inside a
702 * g_main_context_push_thread_default() /
703 * g_main_context_pop_thread_default() pair, but it is up to you to
704 * ensure that no other asynchronous operations accidentally get
705 * started while the non-default context is active.
707 * Beware that libraries that predate this function may not correctly
708 * handle being used from a thread with a thread-default context. Eg,
709 * see g_file_supports_thread_contexts().
711 * Since: 2.22
713 void
714 g_main_context_push_thread_default (GMainContext *context)
716 GQueue *stack;
717 gboolean acquired_context;
719 acquired_context = g_main_context_acquire (context);
720 g_return_if_fail (acquired_context);
722 if (context == g_main_context_default ())
723 context = NULL;
724 else if (context)
725 g_main_context_ref (context);
727 stack = g_private_get (&thread_context_stack);
728 if (!stack)
730 stack = g_queue_new ();
731 g_private_set (&thread_context_stack, stack);
734 g_queue_push_head (stack, context);
738 * g_main_context_pop_thread_default:
739 * @context: (allow-none): a #GMainContext object, or %NULL
741 * Pops @context off the thread-default context stack (verifying that
742 * it was on the top of the stack).
744 * Since: 2.22
746 void
747 g_main_context_pop_thread_default (GMainContext *context)
749 GQueue *stack;
751 if (context == g_main_context_default ())
752 context = NULL;
754 stack = g_private_get (&thread_context_stack);
756 g_return_if_fail (stack != NULL);
757 g_return_if_fail (g_queue_peek_head (stack) == context);
759 g_queue_pop_head (stack);
761 g_main_context_release (context);
762 if (context)
763 g_main_context_unref (context);
767 * g_main_context_get_thread_default:
769 * Gets the thread-default #GMainContext for this thread. Asynchronous
770 * operations that want to be able to be run in contexts other than
771 * the default one should call this method or
772 * g_main_context_ref_thread_default() to get a #GMainContext to add
773 * their #GSource<!-- -->s to. (Note that even in single-threaded
774 * programs applications may sometimes want to temporarily push a
775 * non-default context, so it is not safe to assume that this will
776 * always return %NULL if you are running in the default thread.)
778 * If you need to hold a reference on the context, use
779 * g_main_context_ref_thread_default() instead.
781 * Returns: (transfer none): the thread-default #GMainContext, or
782 * %NULL if the thread-default context is the global default context.
784 * Since: 2.22
786 GMainContext *
787 g_main_context_get_thread_default (void)
789 GQueue *stack;
791 stack = g_private_get (&thread_context_stack);
792 if (stack)
793 return g_queue_peek_head (stack);
794 else
795 return NULL;
799 * g_main_context_ref_thread_default:
801 * Gets the thread-default #GMainContext for this thread, as with
802 * g_main_context_get_thread_default(), but also adds a reference to
803 * it with g_main_context_ref(). In addition, unlike
804 * g_main_context_get_thread_default(), if the thread-default context
805 * is the global default context, this will return that #GMainContext
806 * (with a ref added to it) rather than returning %NULL.
808 * Returns: (transfer full): the thread-default #GMainContext. Unref
809 * with g_main_context_unref() when you are done with it.
811 * Since: 2.32
813 GMainContext *
814 g_main_context_ref_thread_default (void)
816 GMainContext *context;
818 context = g_main_context_get_thread_default ();
819 if (!context)
820 context = g_main_context_default ();
821 return g_main_context_ref (context);
824 /* Hooks for adding to the main loop */
827 * g_source_new:
828 * @source_funcs: structure containing functions that implement
829 * the sources behavior.
830 * @struct_size: size of the #GSource structure to create.
832 * Creates a new #GSource structure. The size is specified to
833 * allow creating structures derived from #GSource that contain
834 * additional data. The size passed in must be at least
835 * <literal>sizeof (GSource)</literal>.
837 * The source will not initially be associated with any #GMainContext
838 * and must be added to one with g_source_attach() before it will be
839 * executed.
841 * Return value: the newly-created #GSource.
843 GSource *
844 g_source_new (GSourceFuncs *source_funcs,
845 guint struct_size)
847 GSource *source;
849 g_return_val_if_fail (source_funcs != NULL, NULL);
850 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
852 source = (GSource*) g_malloc0 (struct_size);
853 source->priv = g_slice_new0 (GSourcePrivate);
854 source->source_funcs = source_funcs;
855 source->ref_count = 1;
857 source->priority = G_PRIORITY_DEFAULT;
859 source->flags = G_HOOK_FLAG_ACTIVE;
861 source->priv->ready_time = -1;
863 /* NULL/0 initialization for all other fields */
865 return source;
868 /* Holds context's lock */
869 static void
870 g_source_iter_init (GSourceIter *iter,
871 GMainContext *context,
872 gboolean may_modify)
874 iter->context = context;
875 iter->current_list = NULL;
876 iter->source = NULL;
877 iter->may_modify = may_modify;
880 /* Holds context's lock */
881 static gboolean
882 g_source_iter_next (GSourceIter *iter, GSource **source)
884 GSource *next_source;
886 if (iter->source)
887 next_source = iter->source->next;
888 else
889 next_source = NULL;
891 if (!next_source)
893 if (iter->current_list)
894 iter->current_list = iter->current_list->next;
895 else
896 iter->current_list = iter->context->source_lists;
898 if (iter->current_list)
900 GSourceList *source_list = iter->current_list->data;
902 next_source = source_list->head;
906 /* Note: unreffing iter->source could potentially cause its
907 * GSourceList to be removed from source_lists (if iter->source is
908 * the only source in its list, and it is destroyed), so we have to
909 * keep it reffed until after we advance iter->current_list, above.
912 if (iter->source && iter->may_modify)
913 SOURCE_UNREF (iter->source, iter->context);
914 iter->source = next_source;
915 if (iter->source && iter->may_modify)
916 iter->source->ref_count++;
918 *source = iter->source;
919 return *source != NULL;
922 /* Holds context's lock. Only necessary to call if you broke out of
923 * the g_source_iter_next() loop early.
925 static void
926 g_source_iter_clear (GSourceIter *iter)
928 if (iter->source && iter->may_modify)
930 SOURCE_UNREF (iter->source, iter->context);
931 iter->source = NULL;
935 /* Holds context's lock
937 static GSourceList *
938 find_source_list_for_priority (GMainContext *context,
939 gint priority,
940 gboolean create)
942 GList *iter, *last;
943 GSourceList *source_list;
945 last = NULL;
946 for (iter = context->source_lists; iter != NULL; last = iter, iter = iter->next)
948 source_list = iter->data;
950 if (source_list->priority == priority)
951 return source_list;
953 if (source_list->priority > priority)
955 if (!create)
956 return NULL;
958 source_list = g_slice_new0 (GSourceList);
959 source_list->priority = priority;
960 context->source_lists = g_list_insert_before (context->source_lists,
961 iter,
962 source_list);
963 return source_list;
967 if (!create)
968 return NULL;
970 source_list = g_slice_new0 (GSourceList);
971 source_list->priority = priority;
973 if (!last)
974 context->source_lists = g_list_append (NULL, source_list);
975 else
977 /* This just appends source_list to the end of
978 * context->source_lists without having to walk the list again.
980 last = g_list_append (last, source_list);
982 return source_list;
985 /* Holds context's lock
987 static void
988 source_add_to_context (GSource *source,
989 GMainContext *context)
991 GSourceList *source_list;
992 GSource *prev, *next;
994 source_list = find_source_list_for_priority (context, source->priority, TRUE);
996 if (source->priv->parent_source)
998 g_assert (source_list->head != NULL);
1000 /* Put the source immediately before its parent */
1001 prev = source->priv->parent_source->prev;
1002 next = source->priv->parent_source;
1004 else
1006 prev = source_list->tail;
1007 next = NULL;
1010 source->next = next;
1011 if (next)
1012 next->prev = source;
1013 else
1014 source_list->tail = source;
1016 source->prev = prev;
1017 if (prev)
1018 prev->next = source;
1019 else
1020 source_list->head = source;
1023 /* Holds context's lock
1025 static void
1026 source_remove_from_context (GSource *source,
1027 GMainContext *context)
1029 GSourceList *source_list;
1031 source_list = find_source_list_for_priority (context, source->priority, FALSE);
1032 g_return_if_fail (source_list != NULL);
1034 if (source->prev)
1035 source->prev->next = source->next;
1036 else
1037 source_list->head = source->next;
1039 if (source->next)
1040 source->next->prev = source->prev;
1041 else
1042 source_list->tail = source->prev;
1044 source->prev = NULL;
1045 source->next = NULL;
1047 if (source_list->head == NULL)
1049 context->source_lists = g_list_remove (context->source_lists, source_list);
1050 g_slice_free (GSourceList, source_list);
1053 if (context->overflow_used_source_ids)
1054 g_hash_table_remove (context->overflow_used_source_ids,
1055 GUINT_TO_POINTER (source->source_id));
1059 static void
1060 assign_source_id_unlocked (GMainContext *context,
1061 GSource *source)
1063 guint id;
1065 /* Are we about to overflow back to 0?
1066 * See https://bugzilla.gnome.org/show_bug.cgi?id=687098
1068 if (G_UNLIKELY (context->next_id == G_MAXUINT &&
1069 context->overflow_used_source_ids == NULL))
1071 GSourceIter iter;
1072 GSource *source;
1074 context->overflow_used_source_ids = g_hash_table_new (NULL, NULL);
1076 g_source_iter_init (&iter, context, FALSE);
1077 while (g_source_iter_next (&iter, &source))
1079 g_hash_table_add (context->overflow_used_source_ids,
1080 GUINT_TO_POINTER (source->source_id));
1082 id = G_MAXUINT;
1083 g_hash_table_add (context->overflow_used_source_ids, GUINT_TO_POINTER (id));
1085 else if (context->overflow_used_source_ids == NULL)
1087 id = context->next_id++;
1089 else
1092 * If we overran G_MAXUINT, we fall back to randomly probing the
1093 * source ids for the current context. This will be slower the more
1094 * sources there are, but we're mainly concerned right now about
1095 * correctness and code size. There's time for a more clever solution
1096 * later.
1099 id = g_random_int ();
1100 while (id == 0 ||
1101 g_hash_table_contains (context->overflow_used_source_ids,
1102 GUINT_TO_POINTER (id)));
1103 g_hash_table_add (context->overflow_used_source_ids, GUINT_TO_POINTER (id));
1106 source->source_id = id;
1109 static guint
1110 g_source_attach_unlocked (GSource *source,
1111 GMainContext *context,
1112 gboolean do_wakeup)
1114 GSList *tmp_list;
1116 source->context = context;
1117 assign_source_id_unlocked (context, source);
1118 source->ref_count++;
1119 source_add_to_context (source, context);
1121 if (!SOURCE_BLOCKED (source))
1123 tmp_list = source->poll_fds;
1124 while (tmp_list)
1126 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
1127 tmp_list = tmp_list->next;
1130 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
1131 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
1134 tmp_list = source->priv->child_sources;
1135 while (tmp_list)
1137 g_source_attach_unlocked (tmp_list->data, context, FALSE);
1138 tmp_list = tmp_list->next;
1141 /* If another thread has acquired the context, wake it up since it
1142 * might be in poll() right now.
1144 if (do_wakeup && context->owner && context->owner != G_THREAD_SELF)
1145 g_wakeup_signal (context->wakeup);
1147 return source->source_id;
1151 * g_source_attach:
1152 * @source: a #GSource
1153 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
1155 * Adds a #GSource to a @context so that it will be executed within
1156 * that context. Remove it by calling g_source_destroy().
1158 * Return value: the ID (greater than 0) for the source within the
1159 * #GMainContext.
1161 guint
1162 g_source_attach (GSource *source,
1163 GMainContext *context)
1165 guint result = 0;
1167 g_return_val_if_fail (source->context == NULL, 0);
1168 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
1170 TRACE (GLIB_MAIN_SOURCE_ATTACH (g_source_get_name (source)));
1172 if (!context)
1173 context = g_main_context_default ();
1175 LOCK_CONTEXT (context);
1177 result = g_source_attach_unlocked (source, context, TRUE);
1179 UNLOCK_CONTEXT (context);
1181 return result;
1184 static void
1185 g_source_destroy_internal (GSource *source,
1186 GMainContext *context,
1187 gboolean have_lock)
1189 TRACE (GLIB_MAIN_SOURCE_DESTROY (g_source_get_name (source)));
1191 if (!have_lock)
1192 LOCK_CONTEXT (context);
1194 if (!SOURCE_DESTROYED (source))
1196 GSList *tmp_list;
1197 gpointer old_cb_data;
1198 GSourceCallbackFuncs *old_cb_funcs;
1200 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1202 old_cb_data = source->callback_data;
1203 old_cb_funcs = source->callback_funcs;
1205 source->callback_data = NULL;
1206 source->callback_funcs = NULL;
1208 if (old_cb_funcs)
1210 UNLOCK_CONTEXT (context);
1211 old_cb_funcs->unref (old_cb_data);
1212 LOCK_CONTEXT (context);
1215 if (!SOURCE_BLOCKED (source))
1217 tmp_list = source->poll_fds;
1218 while (tmp_list)
1220 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1221 tmp_list = tmp_list->next;
1224 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
1225 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1228 while (source->priv->child_sources)
1229 g_child_source_remove_internal (source->priv->child_sources->data, context);
1231 if (source->priv->parent_source)
1232 g_child_source_remove_internal (source, context);
1234 g_source_unref_internal (source, context, TRUE);
1237 if (!have_lock)
1238 UNLOCK_CONTEXT (context);
1242 * g_source_destroy:
1243 * @source: a #GSource
1245 * Removes a source from its #GMainContext, if any, and mark it as
1246 * destroyed. The source cannot be subsequently added to another
1247 * context.
1249 void
1250 g_source_destroy (GSource *source)
1252 GMainContext *context;
1254 g_return_if_fail (source != NULL);
1256 context = source->context;
1258 if (context)
1259 g_source_destroy_internal (source, context, FALSE);
1260 else
1261 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1265 * g_source_get_id:
1266 * @source: a #GSource
1268 * Returns the numeric ID for a particular source. The ID of a source
1269 * is a positive integer which is unique within a particular main loop
1270 * context. The reverse
1271 * mapping from ID to source is done by g_main_context_find_source_by_id().
1273 * Return value: the ID (greater than 0) for the source
1275 guint
1276 g_source_get_id (GSource *source)
1278 guint result;
1280 g_return_val_if_fail (source != NULL, 0);
1281 g_return_val_if_fail (source->context != NULL, 0);
1283 LOCK_CONTEXT (source->context);
1284 result = source->source_id;
1285 UNLOCK_CONTEXT (source->context);
1287 return result;
1291 * g_source_get_context:
1292 * @source: a #GSource
1294 * Gets the #GMainContext with which the source is associated.
1296 * You can call this on a source that has been destroyed, provided
1297 * that the #GMainContext it was attached to still exists (in which
1298 * case it will return that #GMainContext). In particular, you can
1299 * always call this function on the source returned from
1300 * g_main_current_source(). But calling this function on a source
1301 * whose #GMainContext has been destroyed is an error.
1303 * Return value: (transfer none) (allow-none): the #GMainContext with which the
1304 * source is associated, or %NULL if the context has not
1305 * yet been added to a source.
1307 GMainContext *
1308 g_source_get_context (GSource *source)
1310 g_return_val_if_fail (source->context != NULL || !SOURCE_DESTROYED (source), NULL);
1312 return source->context;
1316 * g_source_add_poll:
1317 * @source:a #GSource
1318 * @fd: a #GPollFD structure holding information about a file
1319 * descriptor to watch.
1321 * Adds a file descriptor to the set of file descriptors polled for
1322 * this source. This is usually combined with g_source_new() to add an
1323 * event source. The event source's check function will typically test
1324 * the @revents field in the #GPollFD struct and return %TRUE if events need
1325 * to be processed.
1327 * Using this API forces the linear scanning of event sources on each
1328 * main loop iteration. Newly-written event sources should try to use
1329 * g_source_add_unix_fd() instead of this API.
1331 void
1332 g_source_add_poll (GSource *source,
1333 GPollFD *fd)
1335 GMainContext *context;
1337 g_return_if_fail (source != NULL);
1338 g_return_if_fail (fd != NULL);
1339 g_return_if_fail (!SOURCE_DESTROYED (source));
1341 context = source->context;
1343 if (context)
1344 LOCK_CONTEXT (context);
1346 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1348 if (context)
1350 if (!SOURCE_BLOCKED (source))
1351 g_main_context_add_poll_unlocked (context, source->priority, fd);
1352 UNLOCK_CONTEXT (context);
1357 * g_source_remove_poll:
1358 * @source:a #GSource
1359 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1361 * Removes a file descriptor from the set of file descriptors polled for
1362 * this source.
1364 void
1365 g_source_remove_poll (GSource *source,
1366 GPollFD *fd)
1368 GMainContext *context;
1370 g_return_if_fail (source != NULL);
1371 g_return_if_fail (fd != NULL);
1372 g_return_if_fail (!SOURCE_DESTROYED (source));
1374 context = source->context;
1376 if (context)
1377 LOCK_CONTEXT (context);
1379 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1381 if (context)
1383 if (!SOURCE_BLOCKED (source))
1384 g_main_context_remove_poll_unlocked (context, fd);
1385 UNLOCK_CONTEXT (context);
1390 * g_source_add_child_source:
1391 * @source:a #GSource
1392 * @child_source: a second #GSource that @source should "poll"
1394 * Adds @child_source to @source as a "polled" source; when @source is
1395 * added to a #GMainContext, @child_source will be automatically added
1396 * with the same priority, when @child_source is triggered, it will
1397 * cause @source to dispatch (in addition to calling its own
1398 * callback), and when @source is destroyed, it will destroy
1399 * @child_source as well. (@source will also still be dispatched if
1400 * its own prepare/check functions indicate that it is ready.)
1402 * If you don't need @child_source to do anything on its own when it
1403 * triggers, you can call g_source_set_dummy_callback() on it to set a
1404 * callback that does nothing (except return %TRUE if appropriate).
1406 * @source will hold a reference on @child_source while @child_source
1407 * is attached to it.
1409 * Since: 2.28
1411 void
1412 g_source_add_child_source (GSource *source,
1413 GSource *child_source)
1415 GMainContext *context;
1417 g_return_if_fail (source != NULL);
1418 g_return_if_fail (child_source != NULL);
1419 g_return_if_fail (!SOURCE_DESTROYED (source));
1420 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1421 g_return_if_fail (child_source->context == NULL);
1422 g_return_if_fail (child_source->priv->parent_source == NULL);
1424 context = source->context;
1426 if (context)
1427 LOCK_CONTEXT (context);
1429 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1430 g_source_ref (child_source));
1431 child_source->priv->parent_source = source;
1432 g_source_set_priority_unlocked (child_source, NULL, source->priority);
1433 if (SOURCE_BLOCKED (source))
1434 block_source (child_source);
1436 if (context)
1438 g_source_attach_unlocked (child_source, context, TRUE);
1439 UNLOCK_CONTEXT (context);
1443 static void
1444 g_child_source_remove_internal (GSource *child_source,
1445 GMainContext *context)
1447 GSource *parent_source = child_source->priv->parent_source;
1449 parent_source->priv->child_sources =
1450 g_slist_remove (parent_source->priv->child_sources, child_source);
1451 child_source->priv->parent_source = NULL;
1453 g_source_destroy_internal (child_source, context, TRUE);
1454 g_source_unref_internal (child_source, context, TRUE);
1458 * g_source_remove_child_source:
1459 * @source:a #GSource
1460 * @child_source: a #GSource previously passed to
1461 * g_source_add_child_source().
1463 * Detaches @child_source from @source and destroys it.
1465 * Since: 2.28
1467 void
1468 g_source_remove_child_source (GSource *source,
1469 GSource *child_source)
1471 GMainContext *context;
1473 g_return_if_fail (source != NULL);
1474 g_return_if_fail (child_source != NULL);
1475 g_return_if_fail (child_source->priv->parent_source == source);
1476 g_return_if_fail (!SOURCE_DESTROYED (source));
1477 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1479 context = source->context;
1481 if (context)
1482 LOCK_CONTEXT (context);
1484 g_child_source_remove_internal (child_source, context);
1486 if (context)
1487 UNLOCK_CONTEXT (context);
1491 * g_source_set_callback_indirect:
1492 * @source: the source
1493 * @callback_data: pointer to callback data "object"
1494 * @callback_funcs: functions for reference counting @callback_data
1495 * and getting the callback and data
1497 * Sets the callback function storing the data as a refcounted callback
1498 * "object". This is used internally. Note that calling
1499 * g_source_set_callback_indirect() assumes
1500 * an initial reference count on @callback_data, and thus
1501 * @callback_funcs->unref will eventually be called once more
1502 * than @callback_funcs->ref.
1504 void
1505 g_source_set_callback_indirect (GSource *source,
1506 gpointer callback_data,
1507 GSourceCallbackFuncs *callback_funcs)
1509 GMainContext *context;
1510 gpointer old_cb_data;
1511 GSourceCallbackFuncs *old_cb_funcs;
1513 g_return_if_fail (source != NULL);
1514 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1516 context = source->context;
1518 if (context)
1519 LOCK_CONTEXT (context);
1521 old_cb_data = source->callback_data;
1522 old_cb_funcs = source->callback_funcs;
1524 source->callback_data = callback_data;
1525 source->callback_funcs = callback_funcs;
1527 if (context)
1528 UNLOCK_CONTEXT (context);
1530 if (old_cb_funcs)
1531 old_cb_funcs->unref (old_cb_data);
1534 static void
1535 g_source_callback_ref (gpointer cb_data)
1537 GSourceCallback *callback = cb_data;
1539 callback->ref_count++;
1543 static void
1544 g_source_callback_unref (gpointer cb_data)
1546 GSourceCallback *callback = cb_data;
1548 callback->ref_count--;
1549 if (callback->ref_count == 0)
1551 if (callback->notify)
1552 callback->notify (callback->data);
1553 g_free (callback);
1557 static void
1558 g_source_callback_get (gpointer cb_data,
1559 GSource *source,
1560 GSourceFunc *func,
1561 gpointer *data)
1563 GSourceCallback *callback = cb_data;
1565 *func = callback->func;
1566 *data = callback->data;
1569 static GSourceCallbackFuncs g_source_callback_funcs = {
1570 g_source_callback_ref,
1571 g_source_callback_unref,
1572 g_source_callback_get,
1576 * g_source_set_callback:
1577 * @source: the source
1578 * @func: a callback function
1579 * @data: the data to pass to callback function
1580 * @notify: (allow-none): a function to call when @data is no longer in use, or %NULL.
1582 * Sets the callback function for a source. The callback for a source is
1583 * called from the source's dispatch function.
1585 * The exact type of @func depends on the type of source; ie. you
1586 * should not count on @func being called with @data as its first
1587 * parameter.
1589 * Typically, you won't use this function. Instead use functions specific
1590 * to the type of source you are using.
1592 void
1593 g_source_set_callback (GSource *source,
1594 GSourceFunc func,
1595 gpointer data,
1596 GDestroyNotify notify)
1598 GSourceCallback *new_callback;
1600 g_return_if_fail (source != NULL);
1602 new_callback = g_new (GSourceCallback, 1);
1604 new_callback->ref_count = 1;
1605 new_callback->func = func;
1606 new_callback->data = data;
1607 new_callback->notify = notify;
1609 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1614 * g_source_set_funcs:
1615 * @source: a #GSource
1616 * @funcs: the new #GSourceFuncs
1618 * Sets the source functions (can be used to override
1619 * default implementations) of an unattached source.
1621 * Since: 2.12
1623 void
1624 g_source_set_funcs (GSource *source,
1625 GSourceFuncs *funcs)
1627 g_return_if_fail (source != NULL);
1628 g_return_if_fail (source->context == NULL);
1629 g_return_if_fail (source->ref_count > 0);
1630 g_return_if_fail (funcs != NULL);
1632 source->source_funcs = funcs;
1635 static void
1636 g_source_set_priority_unlocked (GSource *source,
1637 GMainContext *context,
1638 gint priority)
1640 GSList *tmp_list;
1642 g_return_if_fail (source->priv->parent_source == NULL ||
1643 source->priv->parent_source->priority == priority);
1645 if (context)
1647 /* Remove the source from the context's source and then
1648 * add it back after so it is sorted in the correct place
1650 source_remove_from_context (source, source->context);
1653 source->priority = priority;
1655 if (context)
1657 source_add_to_context (source, source->context);
1659 if (!SOURCE_BLOCKED (source))
1661 tmp_list = source->poll_fds;
1662 while (tmp_list)
1664 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1665 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1667 tmp_list = tmp_list->next;
1670 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
1672 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1673 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1678 if (source->priv->child_sources)
1680 tmp_list = source->priv->child_sources;
1681 while (tmp_list)
1683 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1684 tmp_list = tmp_list->next;
1690 * g_source_set_priority:
1691 * @source: a #GSource
1692 * @priority: the new priority.
1694 * Sets the priority of a source. While the main loop is being run, a
1695 * source will be dispatched if it is ready to be dispatched and no
1696 * sources at a higher (numerically smaller) priority are ready to be
1697 * dispatched.
1699 void
1700 g_source_set_priority (GSource *source,
1701 gint priority)
1703 GMainContext *context;
1705 g_return_if_fail (source != NULL);
1707 context = source->context;
1709 if (context)
1710 LOCK_CONTEXT (context);
1711 g_source_set_priority_unlocked (source, context, priority);
1712 if (context)
1713 UNLOCK_CONTEXT (source->context);
1717 * g_source_get_priority:
1718 * @source: a #GSource
1720 * Gets the priority of a source.
1722 * Return value: the priority of the source
1724 gint
1725 g_source_get_priority (GSource *source)
1727 g_return_val_if_fail (source != NULL, 0);
1729 return source->priority;
1733 * g_source_set_ready_time:
1734 * @source: a #GSource
1735 * @ready_time: the monotonic time at which the source will be ready,
1736 * 0 for "immediately", -1 for "never"
1738 * Sets a #GSource to be dispatched when the given monotonic time is
1739 * reached (or passed). If the monotonic time is in the past (as it
1740 * always will be if @ready_time is 0) then the source will be
1741 * dispatched immediately.
1743 * If @ready_time is -1 then the source is never woken up on the basis
1744 * of the passage of time.
1746 * Dispatching the source does not reset the ready time. You should do
1747 * so yourself, from the source dispatch function.
1749 * Note that if you have a pair of sources where the ready time of one
1750 * suggests that it will be delivered first but the priority for the
1751 * other suggests that it would be delivered first, and the ready time
1752 * for both sources is reached during the same main context iteration
1753 * then the order of dispatch is undefined.
1755 * Since: 2.36
1757 void
1758 g_source_set_ready_time (GSource *source,
1759 gint64 ready_time)
1761 GMainContext *context;
1763 g_return_if_fail (source != NULL);
1764 g_return_if_fail (source->ref_count > 0);
1766 if (source->priv->ready_time == ready_time)
1767 return;
1769 context = source->context;
1771 if (context)
1772 LOCK_CONTEXT (context);
1774 source->priv->ready_time = ready_time;
1776 if (context)
1778 /* Quite likely that we need to change the timeout on the poll */
1779 if (!SOURCE_BLOCKED (source))
1780 g_wakeup_signal (context->wakeup);
1781 UNLOCK_CONTEXT (context);
1786 * g_source_get_ready_time:
1787 * @source: a #GSource
1789 * Gets the "ready time" of @source, as set by
1790 * g_source_set_ready_time().
1792 * Any time before the current monotonic time (including 0) is an
1793 * indication that the source will fire immediately.
1795 * Returns: the monotonic ready time, -1 for "never"
1797 gint64
1798 g_source_get_ready_time (GSource *source)
1800 g_return_val_if_fail (source != NULL, -1);
1802 return source->priv->ready_time;
1806 * g_source_set_can_recurse:
1807 * @source: a #GSource
1808 * @can_recurse: whether recursion is allowed for this source
1810 * Sets whether a source can be called recursively. If @can_recurse is
1811 * %TRUE, then while the source is being dispatched then this source
1812 * will be processed normally. Otherwise, all processing of this
1813 * source is blocked until the dispatch function returns.
1815 void
1816 g_source_set_can_recurse (GSource *source,
1817 gboolean can_recurse)
1819 GMainContext *context;
1821 g_return_if_fail (source != NULL);
1823 context = source->context;
1825 if (context)
1826 LOCK_CONTEXT (context);
1828 if (can_recurse)
1829 source->flags |= G_SOURCE_CAN_RECURSE;
1830 else
1831 source->flags &= ~G_SOURCE_CAN_RECURSE;
1833 if (context)
1834 UNLOCK_CONTEXT (context);
1838 * g_source_get_can_recurse:
1839 * @source: a #GSource
1841 * Checks whether a source is allowed to be called recursively.
1842 * see g_source_set_can_recurse().
1844 * Return value: whether recursion is allowed.
1846 gboolean
1847 g_source_get_can_recurse (GSource *source)
1849 g_return_val_if_fail (source != NULL, FALSE);
1851 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1856 * g_source_set_name:
1857 * @source: a #GSource
1858 * @name: debug name for the source
1860 * Sets a name for the source, used in debugging and profiling.
1861 * The name defaults to #NULL.
1863 * The source name should describe in a human-readable way
1864 * what the source does. For example, "X11 event queue"
1865 * or "GTK+ repaint idle handler" or whatever it is.
1867 * It is permitted to call this function multiple times, but is not
1868 * recommended due to the potential performance impact. For example,
1869 * one could change the name in the "check" function of a #GSourceFuncs
1870 * to include details like the event type in the source name.
1872 * Since: 2.26
1874 void
1875 g_source_set_name (GSource *source,
1876 const char *name)
1878 g_return_if_fail (source != NULL);
1880 /* setting back to NULL is allowed, just because it's
1881 * weird if get_name can return NULL but you can't
1882 * set that.
1885 g_free (source->name);
1886 source->name = g_strdup (name);
1890 * g_source_get_name:
1891 * @source: a #GSource
1893 * Gets a name for the source, used in debugging and profiling.
1894 * The name may be #NULL if it has never been set with
1895 * g_source_set_name().
1897 * Return value: the name of the source
1898 * Since: 2.26
1900 const char *
1901 g_source_get_name (GSource *source)
1903 g_return_val_if_fail (source != NULL, NULL);
1905 return source->name;
1909 * g_source_set_name_by_id:
1910 * @tag: a #GSource ID
1911 * @name: debug name for the source
1913 * Sets the name of a source using its ID.
1915 * This is a convenience utility to set source names from the return
1916 * value of g_idle_add(), g_timeout_add(), etc.
1918 * Since: 2.26
1920 void
1921 g_source_set_name_by_id (guint tag,
1922 const char *name)
1924 GSource *source;
1926 g_return_if_fail (tag > 0);
1928 source = g_main_context_find_source_by_id (NULL, tag);
1929 if (source == NULL)
1930 return;
1932 g_source_set_name (source, name);
1937 * g_source_ref:
1938 * @source: a #GSource
1940 * Increases the reference count on a source by one.
1942 * Return value: @source
1944 GSource *
1945 g_source_ref (GSource *source)
1947 GMainContext *context;
1949 g_return_val_if_fail (source != NULL, NULL);
1951 context = source->context;
1953 if (context)
1954 LOCK_CONTEXT (context);
1956 source->ref_count++;
1958 if (context)
1959 UNLOCK_CONTEXT (context);
1961 return source;
1964 /* g_source_unref() but possible to call within context lock
1966 static void
1967 g_source_unref_internal (GSource *source,
1968 GMainContext *context,
1969 gboolean have_lock)
1971 gpointer old_cb_data = NULL;
1972 GSourceCallbackFuncs *old_cb_funcs = NULL;
1974 g_return_if_fail (source != NULL);
1976 if (!have_lock && context)
1977 LOCK_CONTEXT (context);
1979 source->ref_count--;
1980 if (source->ref_count == 0)
1982 old_cb_data = source->callback_data;
1983 old_cb_funcs = source->callback_funcs;
1985 source->callback_data = NULL;
1986 source->callback_funcs = NULL;
1988 if (context)
1990 if (!SOURCE_DESTROYED (source))
1991 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
1992 source_remove_from_context (source, context);
1995 if (source->source_funcs->finalize)
1997 if (context)
1998 UNLOCK_CONTEXT (context);
1999 source->source_funcs->finalize (source);
2000 if (context)
2001 LOCK_CONTEXT (context);
2004 g_free (source->name);
2005 source->name = NULL;
2007 g_slist_free (source->poll_fds);
2008 source->poll_fds = NULL;
2010 g_slist_free_full (source->priv->fds, g_free);
2012 g_slice_free (GSourcePrivate, source->priv);
2013 source->priv = NULL;
2015 g_free (source);
2018 if (!have_lock && context)
2019 UNLOCK_CONTEXT (context);
2021 if (old_cb_funcs)
2023 if (have_lock)
2024 UNLOCK_CONTEXT (context);
2026 old_cb_funcs->unref (old_cb_data);
2028 if (have_lock)
2029 LOCK_CONTEXT (context);
2034 * g_source_unref:
2035 * @source: a #GSource
2037 * Decreases the reference count of a source by one. If the
2038 * resulting reference count is zero the source and associated
2039 * memory will be destroyed.
2041 void
2042 g_source_unref (GSource *source)
2044 g_return_if_fail (source != NULL);
2046 g_source_unref_internal (source, source->context, FALSE);
2050 * g_main_context_find_source_by_id:
2051 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
2052 * @source_id: the source ID, as returned by g_source_get_id().
2054 * Finds a #GSource given a pair of context and ID.
2056 * Return value: (transfer none): the #GSource if found, otherwise, %NULL
2058 GSource *
2059 g_main_context_find_source_by_id (GMainContext *context,
2060 guint source_id)
2062 GSourceIter iter;
2063 GSource *source;
2065 g_return_val_if_fail (source_id > 0, NULL);
2067 if (context == NULL)
2068 context = g_main_context_default ();
2070 LOCK_CONTEXT (context);
2072 g_source_iter_init (&iter, context, FALSE);
2073 while (g_source_iter_next (&iter, &source))
2075 if (!SOURCE_DESTROYED (source) &&
2076 source->source_id == source_id)
2077 break;
2079 g_source_iter_clear (&iter);
2081 UNLOCK_CONTEXT (context);
2083 return source;
2087 * g_main_context_find_source_by_funcs_user_data:
2088 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
2089 * @funcs: the @source_funcs passed to g_source_new().
2090 * @user_data: the user data from the callback.
2092 * Finds a source with the given source functions and user data. If
2093 * multiple sources exist with the same source function and user data,
2094 * the first one found will be returned.
2096 * Return value: (transfer none): the source, if one was found, otherwise %NULL
2098 GSource *
2099 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
2100 GSourceFuncs *funcs,
2101 gpointer user_data)
2103 GSourceIter iter;
2104 GSource *source;
2106 g_return_val_if_fail (funcs != NULL, NULL);
2108 if (context == NULL)
2109 context = g_main_context_default ();
2111 LOCK_CONTEXT (context);
2113 g_source_iter_init (&iter, context, FALSE);
2114 while (g_source_iter_next (&iter, &source))
2116 if (!SOURCE_DESTROYED (source) &&
2117 source->source_funcs == funcs &&
2118 source->callback_funcs)
2120 GSourceFunc callback;
2121 gpointer callback_data;
2123 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
2125 if (callback_data == user_data)
2126 break;
2129 g_source_iter_clear (&iter);
2131 UNLOCK_CONTEXT (context);
2133 return source;
2137 * g_main_context_find_source_by_user_data:
2138 * @context: a #GMainContext
2139 * @user_data: the user_data for the callback.
2141 * Finds a source with the given user data for the callback. If
2142 * multiple sources exist with the same user data, the first
2143 * one found will be returned.
2145 * Return value: (transfer none): the source, if one was found, otherwise %NULL
2147 GSource *
2148 g_main_context_find_source_by_user_data (GMainContext *context,
2149 gpointer user_data)
2151 GSourceIter iter;
2152 GSource *source;
2154 if (context == NULL)
2155 context = g_main_context_default ();
2157 LOCK_CONTEXT (context);
2159 g_source_iter_init (&iter, context, FALSE);
2160 while (g_source_iter_next (&iter, &source))
2162 if (!SOURCE_DESTROYED (source) &&
2163 source->callback_funcs)
2165 GSourceFunc callback;
2166 gpointer callback_data = NULL;
2168 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
2170 if (callback_data == user_data)
2171 break;
2174 g_source_iter_clear (&iter);
2176 UNLOCK_CONTEXT (context);
2178 return source;
2182 * g_source_remove:
2183 * @tag: the ID of the source to remove.
2185 * Removes the source with the given id from the default main context.
2187 * The id of a #GSource is given by g_source_get_id(), or will be
2188 * returned by the functions g_source_attach(), g_idle_add(),
2189 * g_idle_add_full(), g_timeout_add(), g_timeout_add_full(),
2190 * g_child_watch_add(), g_child_watch_add_full(), g_io_add_watch(), and
2191 * g_io_add_watch_full().
2193 * See also g_source_destroy(). You must use g_source_destroy() for sources
2194 * added to a non-default main context.
2196 * It is a programmer error to attempt to remove a non-existent source.
2198 * Return value: For historical reasons, this function always returns %TRUE
2200 gboolean
2201 g_source_remove (guint tag)
2203 GSource *source;
2205 g_return_val_if_fail (tag > 0, FALSE);
2207 source = g_main_context_find_source_by_id (NULL, tag);
2208 if (source)
2209 g_source_destroy (source);
2210 else
2211 g_critical ("Source ID %u was not found when attempting to remove it", tag);
2213 return source != NULL;
2217 * g_source_remove_by_user_data:
2218 * @user_data: the user_data for the callback.
2220 * Removes a source from the default main loop context given the user
2221 * data for the callback. If multiple sources exist with the same user
2222 * data, only one will be destroyed.
2224 * Return value: %TRUE if a source was found and removed.
2226 gboolean
2227 g_source_remove_by_user_data (gpointer user_data)
2229 GSource *source;
2231 source = g_main_context_find_source_by_user_data (NULL, user_data);
2232 if (source)
2234 g_source_destroy (source);
2235 return TRUE;
2237 else
2238 return FALSE;
2242 * g_source_remove_by_funcs_user_data:
2243 * @funcs: The @source_funcs passed to g_source_new()
2244 * @user_data: the user data for the callback
2246 * Removes a source from the default main loop context given the
2247 * source functions and user data. If multiple sources exist with the
2248 * same source functions and user data, only one will be destroyed.
2250 * Return value: %TRUE if a source was found and removed.
2252 gboolean
2253 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
2254 gpointer user_data)
2256 GSource *source;
2258 g_return_val_if_fail (funcs != NULL, FALSE);
2260 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
2261 if (source)
2263 g_source_destroy (source);
2264 return TRUE;
2266 else
2267 return FALSE;
2270 #ifdef G_OS_UNIX
2272 * g_source_add_unix_fd:
2273 * @source: a #GSource
2274 * @fd: the fd to monitor
2275 * @events: an event mask
2277 * Monitors @fd for the IO events in @events.
2279 * The tag returned by this function can be used to remove or modify the
2280 * monitoring of the fd using g_source_remove_unix_fd() or
2281 * g_source_modify_unix_fd().
2283 * It is not necessary to remove the fd before destroying the source; it
2284 * will be cleaned up automatically.
2286 * As the name suggests, this function is not available on Windows.
2288 * Returns: an opaque tag
2290 * Since: 2.36
2292 gpointer
2293 g_source_add_unix_fd (GSource *source,
2294 gint fd,
2295 GIOCondition events)
2297 GMainContext *context;
2298 GPollFD *poll_fd;
2300 g_return_val_if_fail (source != NULL, NULL);
2301 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
2303 poll_fd = g_new (GPollFD, 1);
2304 poll_fd->fd = fd;
2305 poll_fd->events = events;
2306 poll_fd->revents = 0;
2308 context = source->context;
2310 if (context)
2311 LOCK_CONTEXT (context);
2313 source->priv->fds = g_slist_prepend (source->priv->fds, poll_fd);
2315 if (context)
2317 if (!SOURCE_BLOCKED (source))
2318 g_main_context_add_poll_unlocked (context, source->priority, poll_fd);
2319 UNLOCK_CONTEXT (context);
2322 return poll_fd;
2326 * g_source_modify_unix_fd:
2327 * @source: a #GSource
2328 * @tag: the tag from g_source_add_unix_fd()
2329 * @new_events: the new event mask to watch
2331 * Updates the event mask to watch for the fd identified by @tag.
2333 * @tag is the tag returned from g_source_add_unix_fd().
2335 * If you want to remove a fd, don't set its event mask to zero.
2336 * Instead, call g_source_remove_unix_fd().
2338 * As the name suggests, this function is not available on Windows.
2340 * Since: 2.36
2342 void
2343 g_source_modify_unix_fd (GSource *source,
2344 gpointer tag,
2345 GIOCondition new_events)
2347 GMainContext *context;
2348 GPollFD *poll_fd;
2350 g_return_if_fail (source != NULL);
2351 g_return_if_fail (g_slist_find (source->priv->fds, tag));
2353 context = source->context;
2354 poll_fd = tag;
2356 poll_fd->events = new_events;
2358 if (context)
2359 g_main_context_wakeup (context);
2363 * g_source_remove_unix_fd:
2364 * @source: a #GSource
2365 * @tag: the tag from g_source_add_unix_fd()
2367 * Reverses the effect of a previous call to g_source_add_unix_fd().
2369 * You only need to call this if you want to remove an fd from being
2370 * watched while keeping the same source around. In the normal case you
2371 * will just want to destroy the source.
2373 * As the name suggests, this function is not available on Windows.
2375 * Since: 2.36
2377 void
2378 g_source_remove_unix_fd (GSource *source,
2379 gpointer tag)
2381 GMainContext *context;
2382 GPollFD *poll_fd;
2384 g_return_if_fail (source != NULL);
2385 g_return_if_fail (g_slist_find (source->priv->fds, tag));
2387 context = source->context;
2388 poll_fd = tag;
2390 if (context)
2391 LOCK_CONTEXT (context);
2393 source->priv->fds = g_slist_remove (source->priv->fds, poll_fd);
2395 if (context)
2397 if (!SOURCE_BLOCKED (source))
2398 g_main_context_remove_poll_unlocked (context, poll_fd);
2400 UNLOCK_CONTEXT (context);
2403 g_free (poll_fd);
2407 * g_source_query_unix_fd:
2408 * @source: a #GSource
2409 * @tag: the tag from g_source_add_unix_fd()
2411 * Queries the events reported for the fd corresponding to @tag on
2412 * @source during the last poll.
2414 * The return value of this function is only defined when the function
2415 * is called from the check or dispatch functions for @source.
2417 * As the name suggests, this function is not available on Windows.
2419 * Returns: the conditions reported on the fd
2421 * Since: 2.36
2423 GIOCondition
2424 g_source_query_unix_fd (GSource *source,
2425 gpointer tag)
2427 GPollFD *poll_fd;
2429 g_return_val_if_fail (source != NULL, 0);
2430 g_return_val_if_fail (g_slist_find (source->priv->fds, tag), 0);
2432 poll_fd = tag;
2434 return poll_fd->revents;
2436 #endif /* G_OS_UNIX */
2439 * g_get_current_time:
2440 * @result: #GTimeVal structure in which to store current time.
2442 * Equivalent to the UNIX gettimeofday() function, but portable.
2444 * You may find g_get_real_time() to be more convenient.
2446 void
2447 g_get_current_time (GTimeVal *result)
2449 #ifndef G_OS_WIN32
2450 struct timeval r;
2452 g_return_if_fail (result != NULL);
2454 /*this is required on alpha, there the timeval structs are int's
2455 not longs and a cast only would fail horribly*/
2456 gettimeofday (&r, NULL);
2457 result->tv_sec = r.tv_sec;
2458 result->tv_usec = r.tv_usec;
2459 #else
2460 FILETIME ft;
2461 guint64 time64;
2463 g_return_if_fail (result != NULL);
2465 GetSystemTimeAsFileTime (&ft);
2466 memmove (&time64, &ft, sizeof (FILETIME));
2468 /* Convert from 100s of nanoseconds since 1601-01-01
2469 * to Unix epoch. Yes, this is Y2038 unsafe.
2471 time64 -= G_GINT64_CONSTANT (116444736000000000);
2472 time64 /= 10;
2474 result->tv_sec = time64 / 1000000;
2475 result->tv_usec = time64 % 1000000;
2476 #endif
2480 * g_get_real_time:
2482 * Queries the system wall-clock time.
2484 * This call is functionally equivalent to g_get_current_time() except
2485 * that the return value is often more convenient than dealing with a
2486 * #GTimeVal.
2488 * You should only use this call if you are actually interested in the real
2489 * wall-clock time. g_get_monotonic_time() is probably more useful for
2490 * measuring intervals.
2492 * Returns: the number of microseconds since January 1, 1970 UTC.
2494 * Since: 2.28
2496 gint64
2497 g_get_real_time (void)
2499 GTimeVal tv;
2501 g_get_current_time (&tv);
2503 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2506 #ifdef G_OS_WIN32
2507 static ULONGLONG (*g_GetTickCount64) (void) = NULL;
2508 static guint32 g_win32_tick_epoch = 0;
2510 void
2511 g_clock_win32_init (void)
2513 HMODULE kernel32;
2515 g_GetTickCount64 = NULL;
2516 kernel32 = GetModuleHandle ("KERNEL32.DLL");
2517 if (kernel32 != NULL)
2518 g_GetTickCount64 = (void *) GetProcAddress (kernel32, "GetTickCount64");
2519 g_win32_tick_epoch = ((guint32)GetTickCount()) >> 31;
2521 #endif
2524 * g_get_monotonic_time:
2526 * Queries the system monotonic time, if available.
2528 * On POSIX systems with clock_gettime() and <literal>CLOCK_MONOTONIC</literal> this call
2529 * is a very shallow wrapper for that. Otherwise, we make a best effort
2530 * that probably involves returning the wall clock time (with at least
2531 * microsecond accuracy, subject to the limitations of the OS kernel).
2533 * It's important to note that POSIX <literal>CLOCK_MONOTONIC</literal> does
2534 * not count time spent while the machine is suspended.
2536 * On Windows, "limitations of the OS kernel" is a rather substantial
2537 * statement. Depending on the configuration of the system, the wall
2538 * clock time is updated as infrequently as 64 times a second (which
2539 * is approximately every 16ms). Also, on XP (but not on Vista or later)
2540 * the monotonic clock is locally monotonic, but may differ in exact
2541 * value between processes due to timer wrap handling.
2543 * Returns: the monotonic time, in microseconds
2545 * Since: 2.28
2547 gint64
2548 g_get_monotonic_time (void)
2550 #ifdef HAVE_CLOCK_GETTIME
2551 /* librt clock_gettime() is our first choice */
2552 struct timespec ts;
2554 #ifdef CLOCK_MONOTONIC
2555 clock_gettime (CLOCK_MONOTONIC, &ts);
2556 #else
2557 clock_gettime (CLOCK_REALTIME, &ts);
2558 #endif
2560 /* In theory monotonic time can have any epoch.
2562 * glib presently assumes the following:
2564 * 1) The epoch comes some time after the birth of Jesus of Nazareth, but
2565 * not more than 10000 years later.
2567 * 2) The current time also falls sometime within this range.
2569 * These two reasonable assumptions leave us with a maximum deviation from
2570 * the epoch of 10000 years, or 315569520000000000 seconds.
2572 * If we restrict ourselves to this range then the number of microseconds
2573 * will always fit well inside the constraints of a int64 (by a factor of
2574 * about 29).
2576 * If you actually hit the following assertion, probably you should file a
2577 * bug against your operating system for being excessively silly.
2579 g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts.tv_sec &&
2580 ts.tv_sec < G_GINT64_CONSTANT (315569520000000000));
2582 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2584 #elif defined (G_OS_WIN32)
2585 guint64 ticks;
2586 guint32 ticks32;
2588 /* There are four sources for the monotonic time on Windows:
2590 * Three are based on a (1 msec accuracy, but only read periodically) clock chip:
2591 * - GetTickCount (GTC)
2592 * 32bit msec counter, updated each ~15msec, wraps in ~50 days
2593 * - GetTickCount64 (GTC64)
2594 * Same as GetTickCount, but extended to 64bit, so no wrap
2595 * Only available in Vista or later
2596 * - timeGetTime (TGT)
2597 * similar to GetTickCount by default: 15msec, 50 day wrap.
2598 * available in winmm.dll (thus known as the multimedia timers)
2599 * However apps can raise the system timer clock frequency using timeBeginPeriod()
2600 * increasing the accuracy up to 1 msec, at a cost in general system performance
2601 * and battery use.
2603 * One is based on high precision clocks:
2604 * - QueryPrecisionCounter (QPC)
2605 * This has much higher accuracy, but is not guaranteed monotonic, and
2606 * has lots of complications like clock jumps and different times on different
2607 * CPUs. It also has lower long term accuracy (i.e. it will drift compared to
2608 * the low precision clocks.
2610 * Additionally, the precision available in the timer-based wakeup such as
2611 * MsgWaitForMultipleObjectsEx (which is what the mainloop is based on) is based
2612 * on the TGT resolution, so by default it is ~15msec, but can be increased by apps.
2614 * The QPC timer has too many issues to be used as is. The only way it could be used
2615 * is to use it to interpolate the lower precision clocks. Firefox does something like
2616 * this:
2617 * https://bugzilla.mozilla.org/show_bug.cgi?id=363258
2619 * However this seems quite complicated, so we're not doing this right now.
2621 * The approach we take instead is to use the TGT timer, extending it to 64bit
2622 * either by using the GTC64 value, or if that is not available, a process local
2623 * time epoch that we increment when we detect a timer wrap (assumes that we read
2624 * the time at least once every 50 days).
2626 * This means that:
2627 * - We have a globally consistent monotonic clock on Vista and later
2628 * - We have a locally monotonic clock on XP
2629 * - Apps that need higher precision in timeouts and clock reads can call
2630 * timeBeginPeriod() to increase it as much as they want
2633 if (g_GetTickCount64 != NULL)
2635 guint32 ticks_as_32bit;
2637 ticks = g_GetTickCount64 ();
2638 ticks32 = timeGetTime();
2640 /* GTC64 and TGT are sampled at different times, however they
2641 * have the same base and source (msecs since system boot).
2642 * They can differ by as much as -16 to +16 msecs.
2643 * We can't just inject the low bits into the 64bit counter
2644 * as one of the counters can have wrapped in 32bit space and
2645 * the other not. Instead we calculate the signed difference
2646 * in 32bit space and apply that difference to the 64bit counter.
2648 ticks_as_32bit = (guint32)ticks;
2650 /* We could do some 2's complement hack, but we play it safe */
2651 if (ticks32 - ticks_as_32bit <= G_MAXINT32)
2652 ticks += ticks32 - ticks_as_32bit;
2653 else
2654 ticks -= ticks_as_32bit - ticks32;
2656 else
2658 guint32 epoch;
2660 epoch = g_atomic_int_get (&g_win32_tick_epoch);
2662 /* Must read ticks after the epoch. Then we're guaranteed
2663 * that the ticks value we read is higher or equal to any
2664 * previous ones that lead to the writing of the epoch.
2666 ticks32 = timeGetTime();
2668 /* We store the MSB of the current time as the LSB
2669 * of the epoch. Comparing these bits lets us detect when
2670 * the 32bit counter has wrapped so we can increase the
2671 * epoch.
2673 * This will work as long as this function is called at
2674 * least once every ~24 days, which is half the wrap time
2675 * of a 32bit msec counter. I think this is pretty likely.
2677 * Note that g_win32_tick_epoch is a process local state,
2678 * so the monotonic clock will not be the same between
2679 * processes.
2681 if ((ticks32 >> 31) != (epoch & 1))
2683 epoch++;
2684 g_atomic_int_set (&g_win32_tick_epoch, epoch);
2688 ticks = (guint64)ticks32 | ((guint64)epoch) << 31;
2691 return ticks * 1000;
2693 #else /* !HAVE_CLOCK_GETTIME && ! G_OS_WIN32*/
2695 GTimeVal tv;
2697 g_get_current_time (&tv);
2699 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2700 #endif
2703 static void
2704 g_main_dispatch_free (gpointer dispatch)
2706 g_slice_free (GMainDispatch, dispatch);
2709 /* Running the main loop */
2711 static GMainDispatch *
2712 get_dispatch (void)
2714 static GPrivate depth_private = G_PRIVATE_INIT (g_main_dispatch_free);
2715 GMainDispatch *dispatch;
2717 dispatch = g_private_get (&depth_private);
2719 if (!dispatch)
2721 dispatch = g_slice_new0 (GMainDispatch);
2722 g_private_set (&depth_private, dispatch);
2725 return dispatch;
2729 * g_main_depth:
2731 * Returns the depth of the stack of calls to
2732 * g_main_context_dispatch() on any #GMainContext in the current thread.
2733 * That is, when called from the toplevel, it gives 0. When
2734 * called from within a callback from g_main_context_iteration()
2735 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2736 * a callback to a recursive call to g_main_context_iteration(),
2737 * it returns 2. And so forth.
2739 * This function is useful in a situation like the following:
2740 * Imagine an extremely simple "garbage collected" system.
2742 * |[
2743 * static GList *free_list;
2745 * gpointer
2746 * allocate_memory (gsize size)
2747 * {
2748 * gpointer result = g_malloc (size);
2749 * free_list = g_list_prepend (free_list, result);
2750 * return result;
2753 * void
2754 * free_allocated_memory (void)
2756 * GList *l;
2757 * for (l = free_list; l; l = l->next);
2758 * g_free (l->data);
2759 * g_list_free (free_list);
2760 * free_list = NULL;
2763 * [...]
2765 * while (TRUE);
2767 * g_main_context_iteration (NULL, TRUE);
2768 * free_allocated_memory();
2770 * ]|
2772 * This works from an application, however, if you want to do the same
2773 * thing from a library, it gets more difficult, since you no longer
2774 * control the main loop. You might think you can simply use an idle
2775 * function to make the call to free_allocated_memory(), but that
2776 * doesn't work, since the idle function could be called from a
2777 * recursive callback. This can be fixed by using g_main_depth()
2779 * |[
2780 * gpointer
2781 * allocate_memory (gsize size)
2782 * {
2783 * FreeListBlock *block = g_new (FreeListBlock, 1);
2784 * block->mem = g_malloc (size);
2785 * block->depth = g_main_depth ();
2786 * free_list = g_list_prepend (free_list, block);
2787 * return block->mem;
2790 * void
2791 * free_allocated_memory (void)
2793 * GList *l;
2795 * int depth = g_main_depth ();
2796 * for (l = free_list; l; );
2798 * GList *next = l->next;
2799 * FreeListBlock *block = l->data;
2800 * if (block->depth > depth)
2802 * g_free (block->mem);
2803 * g_free (block);
2804 * free_list = g_list_delete_link (free_list, l);
2807 * l = next;
2810 * ]|
2812 * There is a temptation to use g_main_depth() to solve
2813 * problems with reentrancy. For instance, while waiting for data
2814 * to be received from the network in response to a menu item,
2815 * the menu item might be selected again. It might seem that
2816 * one could make the menu item's callback return immediately
2817 * and do nothing if g_main_depth() returns a value greater than 1.
2818 * However, this should be avoided since the user then sees selecting
2819 * the menu item do nothing. Furthermore, you'll find yourself adding
2820 * these checks all over your code, since there are doubtless many,
2821 * many things that the user could do. Instead, you can use the
2822 * following techniques:
2824 * <orderedlist>
2825 * <listitem>
2826 * <para>
2827 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
2828 * the user from interacting with elements while the main
2829 * loop is recursing.
2830 * </para>
2831 * </listitem>
2832 * <listitem>
2833 * <para>
2834 * Avoid main loop recursion in situations where you can't handle
2835 * arbitrary callbacks. Instead, structure your code so that you
2836 * simply return to the main loop and then get called again when
2837 * there is more work to do.
2838 * </para>
2839 * </listitem>
2840 * </orderedlist>
2842 * Return value: The main loop recursion level in the current thread
2845 g_main_depth (void)
2847 GMainDispatch *dispatch = get_dispatch ();
2848 return dispatch->depth;
2852 * g_main_current_source:
2854 * Returns the currently firing source for this thread.
2856 * Return value: (transfer none): The currently firing source or %NULL.
2858 * Since: 2.12
2860 GSource *
2861 g_main_current_source (void)
2863 GMainDispatch *dispatch = get_dispatch ();
2864 return dispatch->source;
2868 * g_source_is_destroyed:
2869 * @source: a #GSource
2871 * Returns whether @source has been destroyed.
2873 * This is important when you operate upon your objects
2874 * from within idle handlers, but may have freed the object
2875 * before the dispatch of your idle handler.
2877 * |[
2878 * static gboolean
2879 * idle_callback (gpointer data)
2881 * SomeWidget *self = data;
2883 * GDK_THREADS_ENTER (<!-- -->);
2884 * /<!-- -->* do stuff with self *<!-- -->/
2885 * self->idle_id = 0;
2886 * GDK_THREADS_LEAVE (<!-- -->);
2888 * return G_SOURCE_REMOVE;
2891 * static void
2892 * some_widget_do_stuff_later (SomeWidget *self)
2894 * self->idle_id = g_idle_add (idle_callback, self);
2897 * static void
2898 * some_widget_finalize (GObject *object)
2900 * SomeWidget *self = SOME_WIDGET (object);
2902 * if (self->idle_id)
2903 * g_source_remove (self->idle_id);
2905 * G_OBJECT_CLASS (parent_class)->finalize (object);
2907 * ]|
2909 * This will fail in a multi-threaded application if the
2910 * widget is destroyed before the idle handler fires due
2911 * to the use after free in the callback. A solution, to
2912 * this particular problem, is to check to if the source
2913 * has already been destroy within the callback.
2915 * |[
2916 * static gboolean
2917 * idle_callback (gpointer data)
2919 * SomeWidget *self = data;
2921 * GDK_THREADS_ENTER ();
2922 * if (!g_source_is_destroyed (g_main_current_source ()))
2924 * /<!-- -->* do stuff with self *<!-- -->/
2926 * GDK_THREADS_LEAVE ();
2928 * return FALSE;
2930 * ]|
2932 * Return value: %TRUE if the source has been destroyed
2934 * Since: 2.12
2936 gboolean
2937 g_source_is_destroyed (GSource *source)
2939 return SOURCE_DESTROYED (source);
2942 /* Temporarily remove all this source's file descriptors from the
2943 * poll(), so that if data comes available for one of the file descriptors
2944 * we don't continually spin in the poll()
2946 /* HOLDS: source->context's lock */
2947 static void
2948 block_source (GSource *source)
2950 GSList *tmp_list;
2952 g_return_if_fail (!SOURCE_BLOCKED (source));
2954 source->flags |= G_SOURCE_BLOCKED;
2956 if (source->context)
2958 tmp_list = source->poll_fds;
2959 while (tmp_list)
2961 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2962 tmp_list = tmp_list->next;
2965 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
2966 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2969 if (source->priv && source->priv->child_sources)
2971 tmp_list = source->priv->child_sources;
2972 while (tmp_list)
2974 block_source (tmp_list->data);
2975 tmp_list = tmp_list->next;
2980 /* HOLDS: source->context's lock */
2981 static void
2982 unblock_source (GSource *source)
2984 GSList *tmp_list;
2986 g_return_if_fail (SOURCE_BLOCKED (source)); /* Source already unblocked */
2987 g_return_if_fail (!SOURCE_DESTROYED (source));
2989 source->flags &= ~G_SOURCE_BLOCKED;
2991 tmp_list = source->poll_fds;
2992 while (tmp_list)
2994 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2995 tmp_list = tmp_list->next;
2998 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
2999 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
3001 if (source->priv && source->priv->child_sources)
3003 tmp_list = source->priv->child_sources;
3004 while (tmp_list)
3006 unblock_source (tmp_list->data);
3007 tmp_list = tmp_list->next;
3012 /* HOLDS: context's lock */
3013 static void
3014 g_main_dispatch (GMainContext *context)
3016 GMainDispatch *current = get_dispatch ();
3017 guint i;
3019 for (i = 0; i < context->pending_dispatches->len; i++)
3021 GSource *source = context->pending_dispatches->pdata[i];
3023 context->pending_dispatches->pdata[i] = NULL;
3024 g_assert (source);
3026 source->flags &= ~G_SOURCE_READY;
3028 if (!SOURCE_DESTROYED (source))
3030 gboolean was_in_call;
3031 gpointer user_data = NULL;
3032 GSourceFunc callback = NULL;
3033 GSourceCallbackFuncs *cb_funcs;
3034 gpointer cb_data;
3035 gboolean need_destroy;
3037 gboolean (*dispatch) (GSource *,
3038 GSourceFunc,
3039 gpointer);
3040 GSource *prev_source;
3042 dispatch = source->source_funcs->dispatch;
3043 cb_funcs = source->callback_funcs;
3044 cb_data = source->callback_data;
3046 if (cb_funcs)
3047 cb_funcs->ref (cb_data);
3049 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
3050 block_source (source);
3052 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
3053 source->flags |= G_HOOK_FLAG_IN_CALL;
3055 if (cb_funcs)
3056 cb_funcs->get (cb_data, source, &callback, &user_data);
3058 UNLOCK_CONTEXT (context);
3060 /* These operations are safe because 'current' is thread-local
3061 * and not modified from anywhere but this function.
3063 prev_source = current->source;
3064 current->source = source;
3065 current->depth++;
3067 TRACE( GLIB_MAIN_BEFORE_DISPATCH (g_source_get_name (source)));
3068 need_destroy = !(* dispatch) (source, callback, user_data);
3069 TRACE( GLIB_MAIN_AFTER_DISPATCH (g_source_get_name (source)));
3071 current->source = prev_source;
3072 current->depth--;
3074 if (cb_funcs)
3075 cb_funcs->unref (cb_data);
3077 LOCK_CONTEXT (context);
3079 if (!was_in_call)
3080 source->flags &= ~G_HOOK_FLAG_IN_CALL;
3082 if (SOURCE_BLOCKED (source) && !SOURCE_DESTROYED (source))
3083 unblock_source (source);
3085 /* Note: this depends on the fact that we can't switch
3086 * sources from one main context to another
3088 if (need_destroy && !SOURCE_DESTROYED (source))
3090 g_assert (source->context == context);
3091 g_source_destroy_internal (source, context, TRUE);
3095 SOURCE_UNREF (source, context);
3098 g_ptr_array_set_size (context->pending_dispatches, 0);
3102 * g_main_context_acquire:
3103 * @context: a #GMainContext
3105 * Tries to become the owner of the specified context.
3106 * If some other thread is the owner of the context,
3107 * returns %FALSE immediately. Ownership is properly
3108 * recursive: the owner can require ownership again
3109 * and will release ownership when g_main_context_release()
3110 * is called as many times as g_main_context_acquire().
3112 * You must be the owner of a context before you
3113 * can call g_main_context_prepare(), g_main_context_query(),
3114 * g_main_context_check(), g_main_context_dispatch().
3116 * Return value: %TRUE if the operation succeeded, and
3117 * this thread is now the owner of @context.
3119 gboolean
3120 g_main_context_acquire (GMainContext *context)
3122 gboolean result = FALSE;
3123 GThread *self = G_THREAD_SELF;
3125 if (context == NULL)
3126 context = g_main_context_default ();
3128 LOCK_CONTEXT (context);
3130 if (!context->owner)
3132 context->owner = self;
3133 g_assert (context->owner_count == 0);
3136 if (context->owner == self)
3138 context->owner_count++;
3139 result = TRUE;
3142 UNLOCK_CONTEXT (context);
3144 return result;
3148 * g_main_context_release:
3149 * @context: a #GMainContext
3151 * Releases ownership of a context previously acquired by this thread
3152 * with g_main_context_acquire(). If the context was acquired multiple
3153 * times, the ownership will be released only when g_main_context_release()
3154 * is called as many times as it was acquired.
3156 void
3157 g_main_context_release (GMainContext *context)
3159 if (context == NULL)
3160 context = g_main_context_default ();
3162 LOCK_CONTEXT (context);
3164 context->owner_count--;
3165 if (context->owner_count == 0)
3167 context->owner = NULL;
3169 if (context->waiters)
3171 GMainWaiter *waiter = context->waiters->data;
3172 gboolean loop_internal_waiter = (waiter->mutex == &context->mutex);
3173 context->waiters = g_slist_delete_link (context->waiters,
3174 context->waiters);
3175 if (!loop_internal_waiter)
3176 g_mutex_lock (waiter->mutex);
3178 g_cond_signal (waiter->cond);
3180 if (!loop_internal_waiter)
3181 g_mutex_unlock (waiter->mutex);
3185 UNLOCK_CONTEXT (context);
3189 * g_main_context_wait:
3190 * @context: a #GMainContext
3191 * @cond: a condition variable
3192 * @mutex: a mutex, currently held
3194 * Tries to become the owner of the specified context,
3195 * as with g_main_context_acquire(). But if another thread
3196 * is the owner, atomically drop @mutex and wait on @cond until
3197 * that owner releases ownership or until @cond is signaled, then
3198 * try again (once) to become the owner.
3200 * Return value: %TRUE if the operation succeeded, and
3201 * this thread is now the owner of @context.
3203 gboolean
3204 g_main_context_wait (GMainContext *context,
3205 GCond *cond,
3206 GMutex *mutex)
3208 gboolean result = FALSE;
3209 GThread *self = G_THREAD_SELF;
3210 gboolean loop_internal_waiter;
3212 if (context == NULL)
3213 context = g_main_context_default ();
3215 loop_internal_waiter = (mutex == &context->mutex);
3217 if (!loop_internal_waiter)
3218 LOCK_CONTEXT (context);
3220 if (context->owner && context->owner != self)
3222 GMainWaiter waiter;
3224 waiter.cond = cond;
3225 waiter.mutex = mutex;
3227 context->waiters = g_slist_append (context->waiters, &waiter);
3229 if (!loop_internal_waiter)
3230 UNLOCK_CONTEXT (context);
3231 g_cond_wait (cond, mutex);
3232 if (!loop_internal_waiter)
3233 LOCK_CONTEXT (context);
3235 context->waiters = g_slist_remove (context->waiters, &waiter);
3238 if (!context->owner)
3240 context->owner = self;
3241 g_assert (context->owner_count == 0);
3244 if (context->owner == self)
3246 context->owner_count++;
3247 result = TRUE;
3250 if (!loop_internal_waiter)
3251 UNLOCK_CONTEXT (context);
3253 return result;
3257 * g_main_context_prepare:
3258 * @context: a #GMainContext
3259 * @priority: location to store priority of highest priority
3260 * source already ready.
3262 * Prepares to poll sources within a main loop. The resulting information
3263 * for polling is determined by calling g_main_context_query ().
3265 * Return value: %TRUE if some source is ready to be dispatched
3266 * prior to polling.
3268 gboolean
3269 g_main_context_prepare (GMainContext *context,
3270 gint *priority)
3272 gint i;
3273 gint n_ready = 0;
3274 gint current_priority = G_MAXINT;
3275 GSource *source;
3276 GSourceIter iter;
3278 if (context == NULL)
3279 context = g_main_context_default ();
3281 LOCK_CONTEXT (context);
3283 context->time_is_fresh = FALSE;
3285 if (context->in_check_or_prepare)
3287 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
3288 "prepare() member.");
3289 UNLOCK_CONTEXT (context);
3290 return FALSE;
3293 #if 0
3294 /* If recursing, finish up current dispatch, before starting over */
3295 if (context->pending_dispatches)
3297 if (dispatch)
3298 g_main_dispatch (context, &current_time);
3300 UNLOCK_CONTEXT (context);
3301 return TRUE;
3303 #endif
3305 /* If recursing, clear list of pending dispatches */
3307 for (i = 0; i < context->pending_dispatches->len; i++)
3309 if (context->pending_dispatches->pdata[i])
3310 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
3312 g_ptr_array_set_size (context->pending_dispatches, 0);
3314 /* Prepare all sources */
3316 context->timeout = -1;
3318 g_source_iter_init (&iter, context, TRUE);
3319 while (g_source_iter_next (&iter, &source))
3321 gint source_timeout = -1;
3323 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3324 continue;
3325 if ((n_ready > 0) && (source->priority > current_priority))
3326 break;
3328 if (!(source->flags & G_SOURCE_READY))
3330 gboolean result;
3331 gboolean (* prepare) (GSource *source,
3332 gint *timeout);
3334 prepare = source->source_funcs->prepare;
3336 if (prepare)
3338 context->in_check_or_prepare++;
3339 UNLOCK_CONTEXT (context);
3341 result = (* prepare) (source, &source_timeout);
3343 LOCK_CONTEXT (context);
3344 context->in_check_or_prepare--;
3346 else
3348 source_timeout = -1;
3349 result = FALSE;
3352 if (result == FALSE && source->priv->ready_time != -1)
3354 if (!context->time_is_fresh)
3356 context->time = g_get_monotonic_time ();
3357 context->time_is_fresh = TRUE;
3360 if (source->priv->ready_time <= context->time)
3362 source_timeout = 0;
3363 result = TRUE;
3365 else
3367 gint timeout;
3369 /* rounding down will lead to spinning, so always round up */
3370 timeout = (source->priv->ready_time - context->time + 999) / 1000;
3372 if (source_timeout < 0 || timeout < source_timeout)
3373 source_timeout = timeout;
3377 if (result)
3379 GSource *ready_source = source;
3381 while (ready_source)
3383 ready_source->flags |= G_SOURCE_READY;
3384 ready_source = ready_source->priv->parent_source;
3389 if (source->flags & G_SOURCE_READY)
3391 n_ready++;
3392 current_priority = source->priority;
3393 context->timeout = 0;
3396 if (source_timeout >= 0)
3398 if (context->timeout < 0)
3399 context->timeout = source_timeout;
3400 else
3401 context->timeout = MIN (context->timeout, source_timeout);
3404 g_source_iter_clear (&iter);
3406 UNLOCK_CONTEXT (context);
3408 if (priority)
3409 *priority = current_priority;
3411 return (n_ready > 0);
3415 * g_main_context_query:
3416 * @context: a #GMainContext
3417 * @max_priority: maximum priority source to check
3418 * @timeout_: (out): location to store timeout to be used in polling
3419 * @fds: (out caller-allocates) (array length=n_fds): location to
3420 * store #GPollFD records that need to be polled.
3421 * @n_fds: length of @fds.
3423 * Determines information necessary to poll this main loop.
3425 * Return value: the number of records actually stored in @fds,
3426 * or, if more than @n_fds records need to be stored, the number
3427 * of records that need to be stored.
3429 gint
3430 g_main_context_query (GMainContext *context,
3431 gint max_priority,
3432 gint *timeout,
3433 GPollFD *fds,
3434 gint n_fds)
3436 gint n_poll;
3437 GPollRec *pollrec;
3439 LOCK_CONTEXT (context);
3441 pollrec = context->poll_records;
3442 n_poll = 0;
3443 while (pollrec && max_priority >= pollrec->priority)
3445 /* We need to include entries with fd->events == 0 in the array because
3446 * otherwise if the application changes fd->events behind our back and
3447 * makes it non-zero, we'll be out of sync when we check the fds[] array.
3448 * (Changing fd->events after adding an FD wasn't an anticipated use of
3449 * this API, but it occurs in practice.) */
3450 if (n_poll < n_fds)
3452 fds[n_poll].fd = pollrec->fd->fd;
3453 /* In direct contradiction to the Unix98 spec, IRIX runs into
3454 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
3455 * flags in the events field of the pollfd while it should
3456 * just ignoring them. So we mask them out here.
3458 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
3459 fds[n_poll].revents = 0;
3462 pollrec = pollrec->next;
3463 n_poll++;
3466 context->poll_changed = FALSE;
3468 if (timeout)
3470 *timeout = context->timeout;
3471 if (*timeout != 0)
3472 context->time_is_fresh = FALSE;
3475 UNLOCK_CONTEXT (context);
3477 return n_poll;
3481 * g_main_context_check:
3482 * @context: a #GMainContext
3483 * @max_priority: the maximum numerical priority of sources to check
3484 * @fds: (array length=n_fds): array of #GPollFD's that was passed to
3485 * the last call to g_main_context_query()
3486 * @n_fds: return value of g_main_context_query()
3488 * Passes the results of polling back to the main loop.
3490 * Return value: %TRUE if some sources are ready to be dispatched.
3492 gboolean
3493 g_main_context_check (GMainContext *context,
3494 gint max_priority,
3495 GPollFD *fds,
3496 gint n_fds)
3498 GSource *source;
3499 GSourceIter iter;
3500 GPollRec *pollrec;
3501 gint n_ready = 0;
3502 gint i;
3504 LOCK_CONTEXT (context);
3506 if (context->in_check_or_prepare)
3508 g_warning ("g_main_context_check() called recursively from within a source's check() or "
3509 "prepare() member.");
3510 UNLOCK_CONTEXT (context);
3511 return FALSE;
3514 if (context->wake_up_rec.revents)
3515 g_wakeup_acknowledge (context->wakeup);
3517 /* If the set of poll file descriptors changed, bail out
3518 * and let the main loop rerun
3520 if (context->poll_changed)
3522 UNLOCK_CONTEXT (context);
3523 return FALSE;
3526 pollrec = context->poll_records;
3527 i = 0;
3528 while (i < n_fds)
3530 if (pollrec->fd->events)
3531 pollrec->fd->revents = fds[i].revents;
3533 pollrec = pollrec->next;
3534 i++;
3537 g_source_iter_init (&iter, context, TRUE);
3538 while (g_source_iter_next (&iter, &source))
3540 if (SOURCE_DESTROYED (source) || SOURCE_BLOCKED (source))
3541 continue;
3542 if ((n_ready > 0) && (source->priority > max_priority))
3543 break;
3545 if (!(source->flags & G_SOURCE_READY))
3547 gboolean result;
3548 gboolean (* check) (GSource *source);
3550 check = source->source_funcs->check;
3552 if (check)
3554 /* If the check function is set, call it. */
3555 context->in_check_or_prepare++;
3556 UNLOCK_CONTEXT (context);
3558 result = (* check) (source);
3560 LOCK_CONTEXT (context);
3561 context->in_check_or_prepare--;
3563 else
3564 result = FALSE;
3566 if (result == FALSE)
3568 GSList *tmp_list;
3570 /* If not already explicitly flagged ready by ->check()
3571 * (or if we have no check) then we can still be ready if
3572 * any of our fds poll as ready.
3574 for (tmp_list = source->priv->fds; tmp_list; tmp_list = tmp_list->next)
3576 GPollFD *pollfd = tmp_list->data;
3578 if (pollfd->revents)
3580 result = TRUE;
3581 break;
3586 if (result == FALSE && source->priv->ready_time != -1)
3588 if (!context->time_is_fresh)
3590 context->time = g_get_monotonic_time ();
3591 context->time_is_fresh = TRUE;
3594 if (source->priv->ready_time <= context->time)
3595 result = TRUE;
3598 if (result)
3600 GSource *ready_source = source;
3602 while (ready_source)
3604 ready_source->flags |= G_SOURCE_READY;
3605 ready_source = ready_source->priv->parent_source;
3610 if (source->flags & G_SOURCE_READY)
3612 source->ref_count++;
3613 g_ptr_array_add (context->pending_dispatches, source);
3615 n_ready++;
3617 /* never dispatch sources with less priority than the first
3618 * one we choose to dispatch
3620 max_priority = source->priority;
3623 g_source_iter_clear (&iter);
3625 UNLOCK_CONTEXT (context);
3627 return n_ready > 0;
3631 * g_main_context_dispatch:
3632 * @context: a #GMainContext
3634 * Dispatches all pending sources.
3636 void
3637 g_main_context_dispatch (GMainContext *context)
3639 LOCK_CONTEXT (context);
3641 if (context->pending_dispatches->len > 0)
3643 g_main_dispatch (context);
3646 UNLOCK_CONTEXT (context);
3649 /* HOLDS context lock */
3650 static gboolean
3651 g_main_context_iterate (GMainContext *context,
3652 gboolean block,
3653 gboolean dispatch,
3654 GThread *self)
3656 gint max_priority;
3657 gint timeout;
3658 gboolean some_ready;
3659 gint nfds, allocated_nfds;
3660 GPollFD *fds = NULL;
3662 UNLOCK_CONTEXT (context);
3664 if (!g_main_context_acquire (context))
3666 gboolean got_ownership;
3668 LOCK_CONTEXT (context);
3670 if (!block)
3671 return FALSE;
3673 got_ownership = g_main_context_wait (context,
3674 &context->cond,
3675 &context->mutex);
3677 if (!got_ownership)
3678 return FALSE;
3680 else
3681 LOCK_CONTEXT (context);
3683 if (!context->cached_poll_array)
3685 context->cached_poll_array_size = context->n_poll_records;
3686 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
3689 allocated_nfds = context->cached_poll_array_size;
3690 fds = context->cached_poll_array;
3692 UNLOCK_CONTEXT (context);
3694 g_main_context_prepare (context, &max_priority);
3696 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
3697 allocated_nfds)) > allocated_nfds)
3699 LOCK_CONTEXT (context);
3700 g_free (fds);
3701 context->cached_poll_array_size = allocated_nfds = nfds;
3702 context->cached_poll_array = fds = g_new (GPollFD, nfds);
3703 UNLOCK_CONTEXT (context);
3706 if (!block)
3707 timeout = 0;
3709 g_main_context_poll (context, timeout, max_priority, fds, nfds);
3711 some_ready = g_main_context_check (context, max_priority, fds, nfds);
3713 if (dispatch)
3714 g_main_context_dispatch (context);
3716 g_main_context_release (context);
3718 LOCK_CONTEXT (context);
3720 return some_ready;
3724 * g_main_context_pending:
3725 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
3727 * Checks if any sources have pending events for the given context.
3729 * Return value: %TRUE if events are pending.
3731 gboolean
3732 g_main_context_pending (GMainContext *context)
3734 gboolean retval;
3736 if (!context)
3737 context = g_main_context_default();
3739 LOCK_CONTEXT (context);
3740 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3741 UNLOCK_CONTEXT (context);
3743 return retval;
3747 * g_main_context_iteration:
3748 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used)
3749 * @may_block: whether the call may block.
3751 * Runs a single iteration for the given main loop. This involves
3752 * checking to see if any event sources are ready to be processed,
3753 * then if no events sources are ready and @may_block is %TRUE, waiting
3754 * for a source to become ready, then dispatching the highest priority
3755 * events sources that are ready. Otherwise, if @may_block is %FALSE
3756 * sources are not waited to become ready, only those highest priority
3757 * events sources will be dispatched (if any), that are ready at this
3758 * given moment without further waiting.
3760 * Note that even when @may_block is %TRUE, it is still possible for
3761 * g_main_context_iteration() to return %FALSE, since the wait may
3762 * be interrupted for other reasons than an event source becoming ready.
3764 * Return value: %TRUE if events were dispatched.
3766 gboolean
3767 g_main_context_iteration (GMainContext *context, gboolean may_block)
3769 gboolean retval;
3771 if (!context)
3772 context = g_main_context_default();
3774 LOCK_CONTEXT (context);
3775 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3776 UNLOCK_CONTEXT (context);
3778 return retval;
3782 * g_main_loop_new:
3783 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
3784 * @is_running: set to %TRUE to indicate that the loop is running. This
3785 * is not very important since calling g_main_loop_run() will set this to
3786 * %TRUE anyway.
3788 * Creates a new #GMainLoop structure.
3790 * Return value: a new #GMainLoop.
3792 GMainLoop *
3793 g_main_loop_new (GMainContext *context,
3794 gboolean is_running)
3796 GMainLoop *loop;
3798 if (!context)
3799 context = g_main_context_default();
3801 g_main_context_ref (context);
3803 loop = g_new0 (GMainLoop, 1);
3804 loop->context = context;
3805 loop->is_running = is_running != FALSE;
3806 loop->ref_count = 1;
3808 return loop;
3812 * g_main_loop_ref:
3813 * @loop: a #GMainLoop
3815 * Increases the reference count on a #GMainLoop object by one.
3817 * Return value: @loop
3819 GMainLoop *
3820 g_main_loop_ref (GMainLoop *loop)
3822 g_return_val_if_fail (loop != NULL, NULL);
3823 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3825 g_atomic_int_inc (&loop->ref_count);
3827 return loop;
3831 * g_main_loop_unref:
3832 * @loop: a #GMainLoop
3834 * Decreases the reference count on a #GMainLoop object by one. If
3835 * the result is zero, free the loop and free all associated memory.
3837 void
3838 g_main_loop_unref (GMainLoop *loop)
3840 g_return_if_fail (loop != NULL);
3841 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3843 if (!g_atomic_int_dec_and_test (&loop->ref_count))
3844 return;
3846 g_main_context_unref (loop->context);
3847 g_free (loop);
3851 * g_main_loop_run:
3852 * @loop: a #GMainLoop
3854 * Runs a main loop until g_main_loop_quit() is called on the loop.
3855 * If this is called for the thread of the loop's #GMainContext,
3856 * it will process events from the loop, otherwise it will
3857 * simply wait.
3859 void
3860 g_main_loop_run (GMainLoop *loop)
3862 GThread *self = G_THREAD_SELF;
3864 g_return_if_fail (loop != NULL);
3865 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3867 if (!g_main_context_acquire (loop->context))
3869 gboolean got_ownership = FALSE;
3871 /* Another thread owns this context */
3872 LOCK_CONTEXT (loop->context);
3874 g_atomic_int_inc (&loop->ref_count);
3876 if (!loop->is_running)
3877 loop->is_running = TRUE;
3879 while (loop->is_running && !got_ownership)
3880 got_ownership = g_main_context_wait (loop->context,
3881 &loop->context->cond,
3882 &loop->context->mutex);
3884 if (!loop->is_running)
3886 UNLOCK_CONTEXT (loop->context);
3887 if (got_ownership)
3888 g_main_context_release (loop->context);
3889 g_main_loop_unref (loop);
3890 return;
3893 g_assert (got_ownership);
3895 else
3896 LOCK_CONTEXT (loop->context);
3898 if (loop->context->in_check_or_prepare)
3900 g_warning ("g_main_loop_run(): called recursively from within a source's "
3901 "check() or prepare() member, iteration not possible.");
3902 return;
3905 g_atomic_int_inc (&loop->ref_count);
3906 loop->is_running = TRUE;
3907 while (loop->is_running)
3908 g_main_context_iterate (loop->context, TRUE, TRUE, self);
3910 UNLOCK_CONTEXT (loop->context);
3912 g_main_context_release (loop->context);
3914 g_main_loop_unref (loop);
3918 * g_main_loop_quit:
3919 * @loop: a #GMainLoop
3921 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3922 * for the loop will return.
3924 * Note that sources that have already been dispatched when
3925 * g_main_loop_quit() is called will still be executed.
3927 void
3928 g_main_loop_quit (GMainLoop *loop)
3930 g_return_if_fail (loop != NULL);
3931 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3933 LOCK_CONTEXT (loop->context);
3934 loop->is_running = FALSE;
3935 g_wakeup_signal (loop->context->wakeup);
3937 g_cond_broadcast (&loop->context->cond);
3939 UNLOCK_CONTEXT (loop->context);
3943 * g_main_loop_is_running:
3944 * @loop: a #GMainLoop.
3946 * Checks to see if the main loop is currently being run via g_main_loop_run().
3948 * Return value: %TRUE if the mainloop is currently being run.
3950 gboolean
3951 g_main_loop_is_running (GMainLoop *loop)
3953 g_return_val_if_fail (loop != NULL, FALSE);
3954 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3956 return loop->is_running;
3960 * g_main_loop_get_context:
3961 * @loop: a #GMainLoop.
3963 * Returns the #GMainContext of @loop.
3965 * Return value: (transfer none): the #GMainContext of @loop
3967 GMainContext *
3968 g_main_loop_get_context (GMainLoop *loop)
3970 g_return_val_if_fail (loop != NULL, NULL);
3971 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3973 return loop->context;
3976 /* HOLDS: context's lock */
3977 static void
3978 g_main_context_poll (GMainContext *context,
3979 gint timeout,
3980 gint priority,
3981 GPollFD *fds,
3982 gint n_fds)
3984 #ifdef G_MAIN_POLL_DEBUG
3985 GTimer *poll_timer;
3986 GPollRec *pollrec;
3987 gint i;
3988 #endif
3990 GPollFunc poll_func;
3992 if (n_fds || timeout != 0)
3994 #ifdef G_MAIN_POLL_DEBUG
3995 if (_g_main_poll_debug)
3997 g_print ("polling context=%p n=%d timeout=%d\n",
3998 context, n_fds, timeout);
3999 poll_timer = g_timer_new ();
4001 #endif
4003 LOCK_CONTEXT (context);
4005 poll_func = context->poll_func;
4007 UNLOCK_CONTEXT (context);
4008 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
4010 #ifndef G_OS_WIN32
4011 g_warning ("poll(2) failed due to: %s.",
4012 g_strerror (errno));
4013 #else
4014 /* If g_poll () returns -1, it has already called g_warning() */
4015 #endif
4018 #ifdef G_MAIN_POLL_DEBUG
4019 if (_g_main_poll_debug)
4021 LOCK_CONTEXT (context);
4023 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
4024 n_fds,
4025 timeout,
4026 g_timer_elapsed (poll_timer, NULL));
4027 g_timer_destroy (poll_timer);
4028 pollrec = context->poll_records;
4030 while (pollrec != NULL)
4032 i = 0;
4033 while (i < n_fds)
4035 if (fds[i].fd == pollrec->fd->fd &&
4036 pollrec->fd->events &&
4037 fds[i].revents)
4039 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
4040 if (fds[i].revents & G_IO_IN)
4041 g_print ("i");
4042 if (fds[i].revents & G_IO_OUT)
4043 g_print ("o");
4044 if (fds[i].revents & G_IO_PRI)
4045 g_print ("p");
4046 if (fds[i].revents & G_IO_ERR)
4047 g_print ("e");
4048 if (fds[i].revents & G_IO_HUP)
4049 g_print ("h");
4050 if (fds[i].revents & G_IO_NVAL)
4051 g_print ("n");
4052 g_print ("]");
4054 i++;
4056 pollrec = pollrec->next;
4058 g_print ("\n");
4060 UNLOCK_CONTEXT (context);
4062 #endif
4063 } /* if (n_fds || timeout != 0) */
4067 * g_main_context_add_poll:
4068 * @context: (allow-none): a #GMainContext (or %NULL for the default context)
4069 * @fd: a #GPollFD structure holding information about a file
4070 * descriptor to watch.
4071 * @priority: the priority for this file descriptor which should be
4072 * the same as the priority used for g_source_attach() to ensure that the
4073 * file descriptor is polled whenever the results may be needed.
4075 * Adds a file descriptor to the set of file descriptors polled for
4076 * this context. This will very seldom be used directly. Instead
4077 * a typical event source will use g_source_add_unix_fd() instead.
4079 void
4080 g_main_context_add_poll (GMainContext *context,
4081 GPollFD *fd,
4082 gint priority)
4084 if (!context)
4085 context = g_main_context_default ();
4087 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4088 g_return_if_fail (fd);
4090 LOCK_CONTEXT (context);
4091 g_main_context_add_poll_unlocked (context, priority, fd);
4092 UNLOCK_CONTEXT (context);
4095 /* HOLDS: main_loop_lock */
4096 static void
4097 g_main_context_add_poll_unlocked (GMainContext *context,
4098 gint priority,
4099 GPollFD *fd)
4101 GPollRec *prevrec, *nextrec;
4102 GPollRec *newrec = g_slice_new (GPollRec);
4104 /* This file descriptor may be checked before we ever poll */
4105 fd->revents = 0;
4106 newrec->fd = fd;
4107 newrec->priority = priority;
4109 prevrec = context->poll_records_tail;
4110 nextrec = NULL;
4111 while (prevrec && priority < prevrec->priority)
4113 nextrec = prevrec;
4114 prevrec = prevrec->prev;
4117 if (prevrec)
4118 prevrec->next = newrec;
4119 else
4120 context->poll_records = newrec;
4122 newrec->prev = prevrec;
4123 newrec->next = nextrec;
4125 if (nextrec)
4126 nextrec->prev = newrec;
4127 else
4128 context->poll_records_tail = newrec;
4130 context->n_poll_records++;
4132 context->poll_changed = TRUE;
4134 /* Now wake up the main loop if it is waiting in the poll() */
4135 g_wakeup_signal (context->wakeup);
4139 * g_main_context_remove_poll:
4140 * @context:a #GMainContext
4141 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
4143 * Removes file descriptor from the set of file descriptors to be
4144 * polled for a particular context.
4146 void
4147 g_main_context_remove_poll (GMainContext *context,
4148 GPollFD *fd)
4150 if (!context)
4151 context = g_main_context_default ();
4153 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4154 g_return_if_fail (fd);
4156 LOCK_CONTEXT (context);
4157 g_main_context_remove_poll_unlocked (context, fd);
4158 UNLOCK_CONTEXT (context);
4161 static void
4162 g_main_context_remove_poll_unlocked (GMainContext *context,
4163 GPollFD *fd)
4165 GPollRec *pollrec, *prevrec, *nextrec;
4167 prevrec = NULL;
4168 pollrec = context->poll_records;
4170 while (pollrec)
4172 nextrec = pollrec->next;
4173 if (pollrec->fd == fd)
4175 if (prevrec != NULL)
4176 prevrec->next = nextrec;
4177 else
4178 context->poll_records = nextrec;
4180 if (nextrec != NULL)
4181 nextrec->prev = prevrec;
4182 else
4183 context->poll_records_tail = prevrec;
4185 g_slice_free (GPollRec, pollrec);
4187 context->n_poll_records--;
4188 break;
4190 prevrec = pollrec;
4191 pollrec = nextrec;
4194 context->poll_changed = TRUE;
4196 /* Now wake up the main loop if it is waiting in the poll() */
4197 g_wakeup_signal (context->wakeup);
4201 * g_source_get_current_time:
4202 * @source: a #GSource
4203 * @timeval: #GTimeVal structure in which to store current time.
4205 * This function ignores @source and is otherwise the same as
4206 * g_get_current_time().
4208 * Deprecated: 2.28: use g_source_get_time() instead
4210 void
4211 g_source_get_current_time (GSource *source,
4212 GTimeVal *timeval)
4214 g_get_current_time (timeval);
4218 * g_source_get_time:
4219 * @source: a #GSource
4221 * Gets the time to be used when checking this source. The advantage of
4222 * calling this function over calling g_get_monotonic_time() directly is
4223 * that when checking multiple sources, GLib can cache a single value
4224 * instead of having to repeatedly get the system monotonic time.
4226 * The time here is the system monotonic time, if available, or some
4227 * other reasonable alternative otherwise. See g_get_monotonic_time().
4229 * Returns: the monotonic time in microseconds
4231 * Since: 2.28
4233 gint64
4234 g_source_get_time (GSource *source)
4236 GMainContext *context;
4237 gint64 result;
4239 g_return_val_if_fail (source->context != NULL, 0);
4241 context = source->context;
4243 LOCK_CONTEXT (context);
4245 if (!context->time_is_fresh)
4247 context->time = g_get_monotonic_time ();
4248 context->time_is_fresh = TRUE;
4251 result = context->time;
4253 UNLOCK_CONTEXT (context);
4255 return result;
4259 * g_main_context_set_poll_func:
4260 * @context: a #GMainContext
4261 * @func: the function to call to poll all file descriptors
4263 * Sets the function to use to handle polling of file descriptors. It
4264 * will be used instead of the poll() system call
4265 * (or GLib's replacement function, which is used where
4266 * poll() isn't available).
4268 * This function could possibly be used to integrate the GLib event
4269 * loop with an external event loop.
4271 void
4272 g_main_context_set_poll_func (GMainContext *context,
4273 GPollFunc func)
4275 if (!context)
4276 context = g_main_context_default ();
4278 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4280 LOCK_CONTEXT (context);
4282 if (func)
4283 context->poll_func = func;
4284 else
4285 context->poll_func = g_poll;
4287 UNLOCK_CONTEXT (context);
4291 * g_main_context_get_poll_func:
4292 * @context: a #GMainContext
4294 * Gets the poll function set by g_main_context_set_poll_func().
4296 * Return value: the poll function
4298 GPollFunc
4299 g_main_context_get_poll_func (GMainContext *context)
4301 GPollFunc result;
4303 if (!context)
4304 context = g_main_context_default ();
4306 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
4308 LOCK_CONTEXT (context);
4309 result = context->poll_func;
4310 UNLOCK_CONTEXT (context);
4312 return result;
4316 * g_main_context_wakeup:
4317 * @context: a #GMainContext
4319 * If @context is currently blocking in g_main_context_iteration()
4320 * waiting for a source to become ready, cause it to stop blocking
4321 * and return. Otherwise, cause the next invocation of
4322 * g_main_context_iteration() to return without blocking.
4324 * This API is useful for low-level control over #GMainContext; for
4325 * example, integrating it with main loop implementations such as
4326 * #GMainLoop.
4328 * Another related use for this function is when implementing a main
4329 * loop with a termination condition, computed from multiple threads:
4331 * |[
4332 * #define NUM_TASKS 10
4333 * static volatile gint tasks_remaining = NUM_TASKS;
4334 * ...
4336 * while (g_atomic_int_get (&tasks_remaining) != 0)
4337 * g_main_context_iteration (NULL, TRUE);
4338 * ]|
4340 * Then in a thread:
4341 * |[
4342 * perform_work();
4344 * if (g_atomic_int_dec_and_test (&tasks_remaining))
4345 * g_main_context_wakeup (NULL);
4346 * ]|
4348 void
4349 g_main_context_wakeup (GMainContext *context)
4351 if (!context)
4352 context = g_main_context_default ();
4354 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
4356 g_wakeup_signal (context->wakeup);
4360 * g_main_context_is_owner:
4361 * @context: a #GMainContext
4363 * Determines whether this thread holds the (recursive)
4364 * ownership of this #GMainContext. This is useful to
4365 * know before waiting on another thread that may be
4366 * blocking to get ownership of @context.
4368 * Returns: %TRUE if current thread is owner of @context.
4370 * Since: 2.10
4372 gboolean
4373 g_main_context_is_owner (GMainContext *context)
4375 gboolean is_owner;
4377 if (!context)
4378 context = g_main_context_default ();
4380 LOCK_CONTEXT (context);
4381 is_owner = context->owner == G_THREAD_SELF;
4382 UNLOCK_CONTEXT (context);
4384 return is_owner;
4387 /* Timeouts */
4389 static void
4390 g_timeout_set_expiration (GTimeoutSource *timeout_source,
4391 gint64 current_time)
4393 gint64 expiration;
4395 expiration = current_time + (guint64) timeout_source->interval * 1000;
4397 if (timeout_source->seconds)
4399 gint64 remainder;
4400 static gint timer_perturb = -1;
4402 if (timer_perturb == -1)
4405 * we want a per machine/session unique 'random' value; try the dbus
4406 * address first, that has a UUID in it. If there is no dbus, use the
4407 * hostname for hashing.
4409 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
4410 if (!session_bus_address)
4411 session_bus_address = g_getenv ("HOSTNAME");
4412 if (session_bus_address)
4413 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
4414 else
4415 timer_perturb = 0;
4418 /* We want the microseconds part of the timeout to land on the
4419 * 'timer_perturb' mark, but we need to make sure we don't try to
4420 * set the timeout in the past. We do this by ensuring that we
4421 * always only *increase* the expiration time by adding a full
4422 * second in the case that the microsecond portion decreases.
4424 expiration -= timer_perturb;
4426 remainder = expiration % 1000000;
4427 if (remainder >= 1000000/4)
4428 expiration += 1000000;
4430 expiration -= remainder;
4431 expiration += timer_perturb;
4434 g_source_set_ready_time ((GSource *) timeout_source, expiration);
4437 static gboolean
4438 g_timeout_dispatch (GSource *source,
4439 GSourceFunc callback,
4440 gpointer user_data)
4442 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4443 gboolean again;
4445 if (!callback)
4447 g_warning ("Timeout source dispatched without callback\n"
4448 "You must call g_source_set_callback().");
4449 return FALSE;
4452 again = callback (user_data);
4454 if (again)
4455 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
4457 return again;
4461 * g_timeout_source_new:
4462 * @interval: the timeout interval in milliseconds.
4464 * Creates a new timeout source.
4466 * The source will not initially be associated with any #GMainContext
4467 * and must be added to one with g_source_attach() before it will be
4468 * executed.
4470 * The interval given is in terms of monotonic time, not wall clock
4471 * time. See g_get_monotonic_time().
4473 * Return value: the newly-created timeout source
4475 GSource *
4476 g_timeout_source_new (guint interval)
4478 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4479 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4481 timeout_source->interval = interval;
4482 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4484 return source;
4488 * g_timeout_source_new_seconds:
4489 * @interval: the timeout interval in seconds
4491 * Creates a new timeout source.
4493 * The source will not initially be associated with any #GMainContext
4494 * and must be added to one with g_source_attach() before it will be
4495 * executed.
4497 * The scheduling granularity/accuracy of this timeout source will be
4498 * in seconds.
4500 * The interval given in terms of monotonic time, not wall clock time.
4501 * See g_get_monotonic_time().
4503 * Return value: the newly-created timeout source
4505 * Since: 2.14
4507 GSource *
4508 g_timeout_source_new_seconds (guint interval)
4510 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4511 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4513 timeout_source->interval = 1000 * interval;
4514 timeout_source->seconds = TRUE;
4516 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4518 return source;
4523 * g_timeout_add_full:
4524 * @priority: the priority of the timeout source. Typically this will be in
4525 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4526 * @interval: the time between calls to the function, in milliseconds
4527 * (1/1000ths of a second)
4528 * @function: function to call
4529 * @data: data to pass to @function
4530 * @notify: (allow-none): function to call when the timeout is removed, or %NULL
4532 * Sets a function to be called at regular intervals, with the given
4533 * priority. The function is called repeatedly until it returns
4534 * %FALSE, at which point the timeout is automatically destroyed and
4535 * the function will not be called again. The @notify function is
4536 * called when the timeout is destroyed. The first call to the
4537 * function will be at the end of the first @interval.
4539 * Note that timeout functions may be delayed, due to the processing of other
4540 * event sources. Thus they should not be relied on for precise timing.
4541 * After each call to the timeout function, the time of the next
4542 * timeout is recalculated based on the current time and the given interval
4543 * (it does not try to 'catch up' time lost in delays).
4545 * This internally creates a main loop source using g_timeout_source_new()
4546 * and attaches it to the main loop context using g_source_attach(). You can
4547 * do these steps manually if you need greater control.
4549 * The interval given in terms of monotonic time, not wall clock time.
4550 * See g_get_monotonic_time().
4552 * Return value: the ID (greater than 0) of the event source.
4553 * Rename to: g_timeout_add
4555 guint
4556 g_timeout_add_full (gint priority,
4557 guint interval,
4558 GSourceFunc function,
4559 gpointer data,
4560 GDestroyNotify notify)
4562 GSource *source;
4563 guint id;
4565 g_return_val_if_fail (function != NULL, 0);
4567 source = g_timeout_source_new (interval);
4569 if (priority != G_PRIORITY_DEFAULT)
4570 g_source_set_priority (source, priority);
4572 g_source_set_callback (source, function, data, notify);
4573 id = g_source_attach (source, NULL);
4574 g_source_unref (source);
4576 return id;
4580 * g_timeout_add:
4581 * @interval: the time between calls to the function, in milliseconds
4582 * (1/1000ths of a second)
4583 * @function: function to call
4584 * @data: data to pass to @function
4586 * Sets a function to be called at regular intervals, with the default
4587 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
4588 * until it returns %FALSE, at which point the timeout is automatically
4589 * destroyed and the function will not be called again. The first call
4590 * to the function will be at the end of the first @interval.
4592 * Note that timeout functions may be delayed, due to the processing of other
4593 * event sources. Thus they should not be relied on for precise timing.
4594 * After each call to the timeout function, the time of the next
4595 * timeout is recalculated based on the current time and the given interval
4596 * (it does not try to 'catch up' time lost in delays).
4598 * If you want to have a timer in the "seconds" range and do not care
4599 * about the exact time of the first call of the timer, use the
4600 * g_timeout_add_seconds() function; this function allows for more
4601 * optimizations and more efficient system power usage.
4603 * This internally creates a main loop source using g_timeout_source_new()
4604 * and attaches it to the main loop context using g_source_attach(). You can
4605 * do these steps manually if you need greater control.
4607 * The interval given is in terms of monotonic time, not wall clock
4608 * time. See g_get_monotonic_time().
4610 * Return value: the ID (greater than 0) of the event source.
4612 guint
4613 g_timeout_add (guint32 interval,
4614 GSourceFunc function,
4615 gpointer data)
4617 return g_timeout_add_full (G_PRIORITY_DEFAULT,
4618 interval, function, data, NULL);
4622 * g_timeout_add_seconds_full:
4623 * @priority: the priority of the timeout source. Typically this will be in
4624 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4625 * @interval: the time between calls to the function, in seconds
4626 * @function: function to call
4627 * @data: data to pass to @function
4628 * @notify: (allow-none): function to call when the timeout is removed, or %NULL
4630 * Sets a function to be called at regular intervals, with @priority.
4631 * The function is called repeatedly until it returns %FALSE, at which
4632 * point the timeout is automatically destroyed and the function will
4633 * not be called again.
4635 * Unlike g_timeout_add(), this function operates at whole second granularity.
4636 * The initial starting point of the timer is determined by the implementation
4637 * and the implementation is expected to group multiple timers together so that
4638 * they fire all at the same time.
4639 * To allow this grouping, the @interval to the first timer is rounded
4640 * and can deviate up to one second from the specified interval.
4641 * Subsequent timer iterations will generally run at the specified interval.
4643 * Note that timeout functions may be delayed, due to the processing of other
4644 * event sources. Thus they should not be relied on for precise timing.
4645 * After each call to the timeout function, the time of the next
4646 * timeout is recalculated based on the current time and the given @interval
4648 * If you want timing more precise than whole seconds, use g_timeout_add()
4649 * instead.
4651 * The grouping of timers to fire at the same time results in a more power
4652 * and CPU efficient behavior so if your timer is in multiples of seconds
4653 * and you don't require the first timer exactly one second from now, the
4654 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
4656 * This internally creates a main loop source using
4657 * g_timeout_source_new_seconds() and attaches it to the main loop context
4658 * using g_source_attach(). You can do these steps manually if you need
4659 * greater control.
4661 * The interval given is in terms of monotonic time, not wall clock
4662 * time. See g_get_monotonic_time().
4664 * Return value: the ID (greater than 0) of the event source.
4666 * Rename to: g_timeout_add_seconds
4667 * Since: 2.14
4669 guint
4670 g_timeout_add_seconds_full (gint priority,
4671 guint32 interval,
4672 GSourceFunc function,
4673 gpointer data,
4674 GDestroyNotify notify)
4676 GSource *source;
4677 guint id;
4679 g_return_val_if_fail (function != NULL, 0);
4681 source = g_timeout_source_new_seconds (interval);
4683 if (priority != G_PRIORITY_DEFAULT)
4684 g_source_set_priority (source, priority);
4686 g_source_set_callback (source, function, data, notify);
4687 id = g_source_attach (source, NULL);
4688 g_source_unref (source);
4690 return id;
4694 * g_timeout_add_seconds:
4695 * @interval: the time between calls to the function, in seconds
4696 * @function: function to call
4697 * @data: data to pass to @function
4699 * Sets a function to be called at regular intervals with the default
4700 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4701 * it returns %FALSE, at which point the timeout is automatically destroyed
4702 * and the function will not be called again.
4704 * This internally creates a main loop source using
4705 * g_timeout_source_new_seconds() and attaches it to the main loop context
4706 * using g_source_attach(). You can do these steps manually if you need
4707 * greater control. Also see g_timeout_add_seconds_full().
4709 * Note that the first call of the timer may not be precise for timeouts
4710 * of one second. If you need finer precision and have such a timeout,
4711 * you may want to use g_timeout_add() instead.
4713 * The interval given is in terms of monotonic time, not wall clock
4714 * time. See g_get_monotonic_time().
4716 * Return value: the ID (greater than 0) of the event source.
4718 * Since: 2.14
4720 guint
4721 g_timeout_add_seconds (guint interval,
4722 GSourceFunc function,
4723 gpointer data)
4725 g_return_val_if_fail (function != NULL, 0);
4727 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4730 /* Child watch functions */
4732 #ifdef G_OS_WIN32
4734 static gboolean
4735 g_child_watch_prepare (GSource *source,
4736 gint *timeout)
4738 *timeout = -1;
4739 return FALSE;
4742 static gboolean
4743 g_child_watch_check (GSource *source)
4745 GChildWatchSource *child_watch_source;
4746 gboolean child_exited;
4748 child_watch_source = (GChildWatchSource *) source;
4750 child_exited = child_watch_source->poll.revents & G_IO_IN;
4752 if (child_exited)
4754 DWORD child_status;
4757 * Note: We do _not_ check for the special value of STILL_ACTIVE
4758 * since we know that the process has exited and doing so runs into
4759 * problems if the child process "happens to return STILL_ACTIVE(259)"
4760 * as Microsoft's Platform SDK puts it.
4762 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4764 gchar *emsg = g_win32_error_message (GetLastError ());
4765 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4766 g_free (emsg);
4768 child_watch_source->child_status = -1;
4770 else
4771 child_watch_source->child_status = child_status;
4774 return child_exited;
4777 static void
4778 g_child_watch_finalize (GSource *source)
4782 #else /* G_OS_WIN32 */
4784 static void
4785 wake_source (GSource *source)
4787 GMainContext *context;
4789 /* This should be thread-safe:
4791 * - if the source is currently being added to a context, that
4792 * context will be woken up anyway
4794 * - if the source is currently being destroyed, we simply need not
4795 * to crash:
4797 * - the memory for the source will remain valid until after the
4798 * source finalize function was called (which would remove the
4799 * source from the global list which we are currently holding the
4800 * lock for)
4802 * - the GMainContext will either be NULL or point to a live
4803 * GMainContext
4805 * - the GMainContext will remain valid since we hold the
4806 * main_context_list lock
4808 * Since we are holding a lot of locks here, don't try to enter any
4809 * more GMainContext functions for fear of dealock -- just hit the
4810 * GWakeup and run. Even if that's safe now, it could easily become
4811 * unsafe with some very minor changes in the future, and signal
4812 * handling is not the most well-tested codepath.
4814 G_LOCK(main_context_list);
4815 context = source->context;
4816 if (context)
4817 g_wakeup_signal (context->wakeup);
4818 G_UNLOCK(main_context_list);
4821 static void
4822 dispatch_unix_signals (void)
4824 GSList *node;
4826 /* clear this first incase another one arrives while we're processing */
4827 any_unix_signal_pending = FALSE;
4829 G_LOCK(unix_signal_lock);
4831 /* handle GChildWatchSource instances */
4832 if (unix_signal_pending[SIGCHLD])
4834 /* The only way we can do this is to scan all of the children.
4836 * The docs promise that we will not reap children that we are not
4837 * explicitly watching, so that ties our hands from calling
4838 * waitpid(-1). We also can't use siginfo's si_pid field since if
4839 * multiple SIGCHLD arrive at the same time, one of them can be
4840 * dropped (since a given UNIX signal can only be pending once).
4842 for (node = unix_child_watches; node; node = node->next)
4844 GChildWatchSource *source = node->data;
4846 if (!source->child_exited)
4848 pid_t pid;
4851 pid = waitpid (source->pid, &source->child_status, WNOHANG);
4852 if (pid > 0)
4854 source->child_exited = TRUE;
4855 wake_source ((GSource *) source);
4857 else if (pid == -1 && errno == ECHILD)
4859 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.");
4860 source->child_exited = TRUE;
4861 source->child_status = 0;
4862 wake_source ((GSource *) source);
4865 while (pid == -1 && errno == EINTR);
4870 /* handle GUnixSignalWatchSource instances */
4871 for (node = unix_signal_watches; node; node = node->next)
4873 GUnixSignalWatchSource *source = node->data;
4875 if (!source->pending)
4877 if (unix_signal_pending[source->signum])
4879 source->pending = TRUE;
4881 wake_source ((GSource *) source);
4886 memset ((void*)unix_signal_pending, 0, sizeof (unix_signal_pending));
4888 G_UNLOCK(unix_signal_lock);
4891 static gboolean
4892 g_child_watch_prepare (GSource *source,
4893 gint *timeout)
4895 GChildWatchSource *child_watch_source;
4897 child_watch_source = (GChildWatchSource *) source;
4899 return child_watch_source->child_exited;
4902 static gboolean
4903 g_child_watch_check (GSource *source)
4905 GChildWatchSource *child_watch_source;
4907 child_watch_source = (GChildWatchSource *) source;
4909 return child_watch_source->child_exited;
4912 static gboolean
4913 g_unix_signal_watch_prepare (GSource *source,
4914 gint *timeout)
4916 GUnixSignalWatchSource *unix_signal_source;
4918 unix_signal_source = (GUnixSignalWatchSource *) source;
4920 return unix_signal_source->pending;
4923 static gboolean
4924 g_unix_signal_watch_check (GSource *source)
4926 GUnixSignalWatchSource *unix_signal_source;
4928 unix_signal_source = (GUnixSignalWatchSource *) source;
4930 return unix_signal_source->pending;
4933 static gboolean
4934 g_unix_signal_watch_dispatch (GSource *source,
4935 GSourceFunc callback,
4936 gpointer user_data)
4938 GUnixSignalWatchSource *unix_signal_source;
4939 gboolean again;
4941 unix_signal_source = (GUnixSignalWatchSource *) source;
4943 if (!callback)
4945 g_warning ("Unix signal source dispatched without callback\n"
4946 "You must call g_source_set_callback().");
4947 return FALSE;
4950 again = (callback) (user_data);
4952 unix_signal_source->pending = FALSE;
4954 return again;
4957 static void
4958 ref_unix_signal_handler_unlocked (int signum)
4960 /* Ensure we have the worker context */
4961 g_get_worker_context ();
4962 unix_signal_refcount[signum]++;
4963 if (unix_signal_refcount[signum] == 1)
4965 struct sigaction action;
4966 action.sa_handler = g_unix_signal_handler;
4967 sigemptyset (&action.sa_mask);
4968 #ifdef SA_RESTART
4969 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4970 #else
4971 action.sa_flags = SA_NOCLDSTOP;
4972 #endif
4973 sigaction (signum, &action, NULL);
4977 static void
4978 unref_unix_signal_handler_unlocked (int signum)
4980 unix_signal_refcount[signum]--;
4981 if (unix_signal_refcount[signum] == 0)
4983 struct sigaction action;
4984 memset (&action, 0, sizeof (action));
4985 action.sa_handler = SIG_DFL;
4986 sigemptyset (&action.sa_mask);
4987 sigaction (signum, &action, NULL);
4991 GSource *
4992 _g_main_create_unix_signal_watch (int signum)
4994 GSource *source;
4995 GUnixSignalWatchSource *unix_signal_source;
4997 source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
4998 unix_signal_source = (GUnixSignalWatchSource *) source;
5000 unix_signal_source->signum = signum;
5001 unix_signal_source->pending = FALSE;
5003 G_LOCK (unix_signal_lock);
5004 ref_unix_signal_handler_unlocked (signum);
5005 unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
5006 if (unix_signal_pending[signum])
5007 unix_signal_source->pending = TRUE;
5008 G_UNLOCK (unix_signal_lock);
5010 return source;
5013 static void
5014 g_unix_signal_watch_finalize (GSource *source)
5016 GUnixSignalWatchSource *unix_signal_source;
5018 unix_signal_source = (GUnixSignalWatchSource *) source;
5020 G_LOCK (unix_signal_lock);
5021 unref_unix_signal_handler_unlocked (unix_signal_source->signum);
5022 unix_signal_watches = g_slist_remove (unix_signal_watches, source);
5023 G_UNLOCK (unix_signal_lock);
5026 static void
5027 g_child_watch_finalize (GSource *source)
5029 G_LOCK (unix_signal_lock);
5030 unix_child_watches = g_slist_remove (unix_child_watches, source);
5031 unref_unix_signal_handler_unlocked (SIGCHLD);
5032 G_UNLOCK (unix_signal_lock);
5035 #endif /* G_OS_WIN32 */
5037 static gboolean
5038 g_child_watch_dispatch (GSource *source,
5039 GSourceFunc callback,
5040 gpointer user_data)
5042 GChildWatchSource *child_watch_source;
5043 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
5045 child_watch_source = (GChildWatchSource *) source;
5047 if (!callback)
5049 g_warning ("Child watch source dispatched without callback\n"
5050 "You must call g_source_set_callback().");
5051 return FALSE;
5054 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
5056 /* We never keep a child watch source around as the child is gone */
5057 return FALSE;
5060 #ifndef G_OS_WIN32
5062 static void
5063 g_unix_signal_handler (int signum)
5065 unix_signal_pending[signum] = TRUE;
5066 any_unix_signal_pending = TRUE;
5068 g_wakeup_signal (glib_worker_context->wakeup);
5071 #endif /* !G_OS_WIN32 */
5074 * g_child_watch_source_new:
5075 * @pid: process to watch. On POSIX the pid of a child process. On
5076 * Windows a handle for a process (which doesn't have to be a child).
5078 * Creates a new child_watch source.
5080 * The source will not initially be associated with any #GMainContext
5081 * and must be added to one with g_source_attach() before it will be
5082 * executed.
5084 * Note that child watch sources can only be used in conjunction with
5085 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
5086 * flag is used.
5088 * Note that on platforms where #GPid must be explicitly closed
5089 * (see g_spawn_close_pid()) @pid must not be closed while the
5090 * source is still active. Typically, you will want to call
5091 * g_spawn_close_pid() in the callback function for the source.
5093 * Note further that using g_child_watch_source_new() is not
5094 * compatible with calling <literal>waitpid</literal> with a
5095 * nonpositive first argument in the application. Calling waitpid()
5096 * for individual pids will still work fine.
5098 * Return value: the newly-created child watch source
5100 * Since: 2.4
5102 GSource *
5103 g_child_watch_source_new (GPid pid)
5105 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
5106 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
5108 child_watch_source->pid = pid;
5110 #ifdef G_OS_WIN32
5111 child_watch_source->poll.fd = (gintptr) pid;
5112 child_watch_source->poll.events = G_IO_IN;
5114 g_source_add_poll (source, &child_watch_source->poll);
5115 #else /* G_OS_WIN32 */
5116 G_LOCK (unix_signal_lock);
5117 ref_unix_signal_handler_unlocked (SIGCHLD);
5118 unix_child_watches = g_slist_prepend (unix_child_watches, child_watch_source);
5119 if (waitpid (pid, &child_watch_source->child_status, WNOHANG) > 0)
5120 child_watch_source->child_exited = TRUE;
5121 G_UNLOCK (unix_signal_lock);
5122 #endif /* G_OS_WIN32 */
5124 return source;
5128 * g_child_watch_add_full:
5129 * @priority: the priority of the idle source. Typically this will be in the
5130 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
5131 * @pid: process to watch. On POSIX the pid of a child process. On
5132 * Windows a handle for a process (which doesn't have to be a child).
5133 * @function: function to call
5134 * @data: data to pass to @function
5135 * @notify: (allow-none): function to call when the idle is removed, or %NULL
5137 * Sets a function to be called when the child indicated by @pid
5138 * exits, at the priority @priority.
5140 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
5141 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
5142 * the spawn function for the child watching to work.
5144 * In many programs, you will want to call g_spawn_check_exit_status()
5145 * in the callback to determine whether or not the child exited
5146 * successfully.
5148 * Also, note that on platforms where #GPid must be explicitly closed
5149 * (see g_spawn_close_pid()) @pid must not be closed while the source
5150 * is still active. Typically, you should invoke g_spawn_close_pid()
5151 * in the callback function for the source.
5153 * GLib supports only a single callback per process id.
5155 * This internally creates a main loop source using
5156 * g_child_watch_source_new() and attaches it to the main loop context
5157 * using g_source_attach(). You can do these steps manually if you
5158 * need greater control.
5160 * Return value: the ID (greater than 0) of the event source.
5162 * Rename to: g_child_watch_add
5163 * Since: 2.4
5165 guint
5166 g_child_watch_add_full (gint priority,
5167 GPid pid,
5168 GChildWatchFunc function,
5169 gpointer data,
5170 GDestroyNotify notify)
5172 GSource *source;
5173 guint id;
5175 g_return_val_if_fail (function != NULL, 0);
5177 source = g_child_watch_source_new (pid);
5179 if (priority != G_PRIORITY_DEFAULT)
5180 g_source_set_priority (source, priority);
5182 g_source_set_callback (source, (GSourceFunc) function, data, notify);
5183 id = g_source_attach (source, NULL);
5184 g_source_unref (source);
5186 return id;
5190 * g_child_watch_add:
5191 * @pid: process id to watch. On POSIX the pid of a child process. On
5192 * Windows a handle for a process (which doesn't have to be a child).
5193 * @function: function to call
5194 * @data: data to pass to @function
5196 * Sets a function to be called when the child indicated by @pid
5197 * exits, at a default priority, #G_PRIORITY_DEFAULT.
5199 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
5200 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
5201 * the spawn function for the child watching to work.
5203 * Note that on platforms where #GPid must be explicitly closed
5204 * (see g_spawn_close_pid()) @pid must not be closed while the
5205 * source is still active. Typically, you will want to call
5206 * g_spawn_close_pid() in the callback function for the source.
5208 * GLib supports only a single callback per process id.
5210 * This internally creates a main loop source using
5211 * g_child_watch_source_new() and attaches it to the main loop context
5212 * using g_source_attach(). You can do these steps manually if you
5213 * need greater control.
5215 * Return value: the ID (greater than 0) of the event source.
5217 * Since: 2.4
5219 guint
5220 g_child_watch_add (GPid pid,
5221 GChildWatchFunc function,
5222 gpointer data)
5224 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
5228 /* Idle functions */
5230 static gboolean
5231 g_idle_prepare (GSource *source,
5232 gint *timeout)
5234 *timeout = 0;
5236 return TRUE;
5239 static gboolean
5240 g_idle_check (GSource *source)
5242 return TRUE;
5245 static gboolean
5246 g_idle_dispatch (GSource *source,
5247 GSourceFunc callback,
5248 gpointer user_data)
5250 if (!callback)
5252 g_warning ("Idle source dispatched without callback\n"
5253 "You must call g_source_set_callback().");
5254 return FALSE;
5257 return callback (user_data);
5261 * g_idle_source_new:
5263 * Creates a new idle source.
5265 * The source will not initially be associated with any #GMainContext
5266 * and must be added to one with g_source_attach() before it will be
5267 * executed. Note that the default priority for idle sources is
5268 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
5269 * have a default priority of %G_PRIORITY_DEFAULT.
5271 * Return value: the newly-created idle source
5273 GSource *
5274 g_idle_source_new (void)
5276 GSource *source;
5278 source = g_source_new (&g_idle_funcs, sizeof (GSource));
5279 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
5281 return source;
5285 * g_idle_add_full:
5286 * @priority: the priority of the idle source. Typically this will be in the
5287 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
5288 * @function: function to call
5289 * @data: data to pass to @function
5290 * @notify: (allow-none): function to call when the idle is removed, or %NULL
5292 * Adds a function to be called whenever there are no higher priority
5293 * events pending. If the function returns %FALSE it is automatically
5294 * removed from the list of event sources and will not be called again.
5296 * This internally creates a main loop source using g_idle_source_new()
5297 * and attaches it to the main loop context using g_source_attach().
5298 * You can do these steps manually if you need greater control.
5300 * Return value: the ID (greater than 0) of the event source.
5301 * Rename to: g_idle_add
5303 guint
5304 g_idle_add_full (gint priority,
5305 GSourceFunc function,
5306 gpointer data,
5307 GDestroyNotify notify)
5309 GSource *source;
5310 guint id;
5312 g_return_val_if_fail (function != NULL, 0);
5314 source = g_idle_source_new ();
5316 if (priority != G_PRIORITY_DEFAULT_IDLE)
5317 g_source_set_priority (source, priority);
5319 g_source_set_callback (source, function, data, notify);
5320 id = g_source_attach (source, NULL);
5321 g_source_unref (source);
5323 return id;
5327 * g_idle_add:
5328 * @function: function to call
5329 * @data: data to pass to @function.
5331 * Adds a function to be called whenever there are no higher priority
5332 * events pending to the default main loop. The function is given the
5333 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
5334 * returns %FALSE it is automatically removed from the list of event
5335 * sources and will not be called again.
5337 * This internally creates a main loop source using g_idle_source_new()
5338 * and attaches it to the main loop context using g_source_attach().
5339 * You can do these steps manually if you need greater control.
5341 * Return value: the ID (greater than 0) of the event source.
5343 guint
5344 g_idle_add (GSourceFunc function,
5345 gpointer data)
5347 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
5351 * g_idle_remove_by_data:
5352 * @data: the data for the idle source's callback.
5354 * Removes the idle function with the given data.
5356 * Return value: %TRUE if an idle source was found and removed.
5358 gboolean
5359 g_idle_remove_by_data (gpointer data)
5361 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
5365 * g_main_context_invoke:
5366 * @context: (allow-none): a #GMainContext, or %NULL
5367 * @function: function to call
5368 * @data: data to pass to @function
5370 * Invokes a function in such a way that @context is owned during the
5371 * invocation of @function.
5373 * If @context is %NULL then the global default main context — as
5374 * returned by g_main_context_default() — is used.
5376 * If @context is owned by the current thread, @function is called
5377 * directly. Otherwise, if @context is the thread-default main context
5378 * of the current thread and g_main_context_acquire() succeeds, then
5379 * @function is called and g_main_context_release() is called
5380 * afterwards.
5382 * In any other case, an idle source is created to call @function and
5383 * that source is attached to @context (presumably to be run in another
5384 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
5385 * priority. If you want a different priority, use
5386 * g_main_context_invoke_full().
5388 * Note that, as with normal idle functions, @function should probably
5389 * return %FALSE. If it returns %TRUE, it will be continuously run in a
5390 * loop (and may prevent this call from returning).
5392 * Since: 2.28
5394 void
5395 g_main_context_invoke (GMainContext *context,
5396 GSourceFunc function,
5397 gpointer data)
5399 g_main_context_invoke_full (context,
5400 G_PRIORITY_DEFAULT,
5401 function, data, NULL);
5405 * g_main_context_invoke_full:
5406 * @context: (allow-none): a #GMainContext, or %NULL
5407 * @priority: the priority at which to run @function
5408 * @function: function to call
5409 * @data: data to pass to @function
5410 * @notify: (allow-none): a function to call when @data is no longer in use, or %NULL.
5412 * Invokes a function in such a way that @context is owned during the
5413 * invocation of @function.
5415 * This function is the same as g_main_context_invoke() except that it
5416 * lets you specify the priority incase @function ends up being
5417 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
5419 * @notify should not assume that it is called from any particular
5420 * thread or with any particular context acquired.
5422 * Since: 2.28
5424 void
5425 g_main_context_invoke_full (GMainContext *context,
5426 gint priority,
5427 GSourceFunc function,
5428 gpointer data,
5429 GDestroyNotify notify)
5431 g_return_if_fail (function != NULL);
5433 if (!context)
5434 context = g_main_context_default ();
5436 if (g_main_context_is_owner (context))
5438 while (function (data));
5439 if (notify != NULL)
5440 notify (data);
5443 else
5445 GMainContext *thread_default;
5447 thread_default = g_main_context_get_thread_default ();
5449 if (!thread_default)
5450 thread_default = g_main_context_default ();
5452 if (thread_default == context && g_main_context_acquire (context))
5454 while (function (data));
5456 g_main_context_release (context);
5458 if (notify != NULL)
5459 notify (data);
5461 else
5463 GSource *source;
5465 source = g_idle_source_new ();
5466 g_source_set_priority (source, priority);
5467 g_source_set_callback (source, function, data, notify);
5468 g_source_attach (source, context);
5469 g_source_unref (source);
5474 static gpointer
5475 glib_worker_main (gpointer data)
5477 while (TRUE)
5479 g_main_context_iteration (glib_worker_context, TRUE);
5481 #ifdef G_OS_UNIX
5482 if (any_unix_signal_pending)
5483 dispatch_unix_signals ();
5484 #endif
5487 return NULL; /* worst GCC warning message ever... */
5490 GMainContext *
5491 g_get_worker_context (void)
5493 static gsize initialised;
5495 if (g_once_init_enter (&initialised))
5497 /* mask all signals in the worker thread */
5498 #ifdef G_OS_UNIX
5499 sigset_t prev_mask;
5500 sigset_t all;
5502 sigfillset (&all);
5503 pthread_sigmask (SIG_SETMASK, &all, &prev_mask);
5504 #endif
5505 glib_worker_context = g_main_context_new ();
5506 g_thread_new ("gmain", glib_worker_main, NULL);
5507 #ifdef G_OS_UNIX
5508 pthread_sigmask (SIG_SETMASK, &prev_mask, NULL);
5509 #endif
5510 g_once_init_leave (&initialised, TRUE);
5513 return glib_worker_context;