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/.
36 /* Uncomment the next line (and the corresponding line in gpoll.c) to
37 * enable debugging printouts if the environment variable
38 * G_MAIN_POLL_DEBUG is set to some value.
40 /* #define G_MAIN_POLL_DEBUG */
43 /* Always enable debugging printout on Windows, as it is more often
46 #define G_MAIN_POLL_DEBUG
49 #define _GNU_SOURCE /* for pipe2 */
52 #include "gthreadprivate.h"
54 #include <sys/types.h>
57 #ifdef HAVE_SYS_TIME_H
59 #endif /* HAVE_SYS_TIME_H */
62 #endif /* HAVE_UNISTD_H */
68 #endif /* G_OS_WIN32 */
71 #include <sys/socket.h>
73 #endif /* G_OS_BEOS */
84 typedef struct _GTimeoutSource GTimeoutSource;
85 typedef struct _GChildWatchSource GChildWatchSource;
86 typedef struct _GPollRec GPollRec;
87 typedef struct _GSourceCallback GSourceCallback;
91 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
92 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
95 #ifdef G_THREADS_ENABLED
96 typedef struct _GMainWaiter GMainWaiter;
105 typedef struct _GMainDispatch GMainDispatch;
107 struct _GMainDispatch
110 GSList *dispatching_sources; /* stack of current sources */
113 #ifdef G_MAIN_POLL_DEBUG
114 gboolean _g_main_poll_debug = FALSE;
119 #ifdef G_THREADS_ENABLED
120 /* The following lock is used for both the list of sources
121 * and the list of poll records
132 GPtrArray *pending_dispatches;
133 gint timeout; /* Timeout for current iteration */
136 GSource *source_list;
137 gint in_check_or_prepare;
139 GPollRec *poll_records;
140 guint n_poll_records;
141 GPollFD *cached_poll_array;
142 guint cached_poll_array_size;
144 #ifdef G_THREADS_ENABLED
146 /* this pipe is used to wake up the main loop when a source is added.
148 gint wake_up_pipe[2];
149 #else /* G_OS_WIN32 */
150 HANDLE wake_up_semaphore;
151 #endif /* G_OS_WIN32 */
154 gboolean poll_waiting;
156 /* Flag indicating whether the set of fd's changed during a poll */
157 gboolean poll_changed;
158 #endif /* G_THREADS_ENABLED */
162 GTimeVal current_time;
163 gboolean time_is_current;
166 struct _GSourceCallback
171 GDestroyNotify notify;
176 GMainContext *context;
181 struct _GTimeoutSource
189 struct _GChildWatchSource
196 #else /* G_OS_WIN32 */
198 gboolean child_exited;
199 #endif /* G_OS_WIN32 */
209 #ifdef G_THREADS_ENABLED
210 #define LOCK_CONTEXT(context) g_static_mutex_lock (&context->mutex)
211 #define UNLOCK_CONTEXT(context) g_static_mutex_unlock (&context->mutex)
212 #define G_THREAD_SELF g_thread_self ()
214 #define LOCK_CONTEXT(context) (void)0
215 #define UNLOCK_CONTEXT(context) (void)0
216 #define G_THREAD_SELF NULL
219 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
220 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
221 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
223 #define SOURCE_UNREF(source, context) \
225 if ((source)->ref_count > 1) \
226 (source)->ref_count--; \
228 g_source_unref_internal ((source), (context), TRUE); \
232 /* Forward declarations */
234 static void g_source_unref_internal (GSource *source,
235 GMainContext *context,
237 static void g_source_destroy_internal (GSource *source,
238 GMainContext *context,
240 static void g_main_context_poll (GMainContext *context,
245 static void g_main_context_add_poll_unlocked (GMainContext *context,
248 static void g_main_context_remove_poll_unlocked (GMainContext *context,
250 static void g_main_context_wakeup_unlocked (GMainContext *context);
252 static gboolean g_timeout_prepare (GSource *source,
254 static gboolean g_timeout_check (GSource *source);
255 static gboolean g_timeout_dispatch (GSource *source,
256 GSourceFunc callback,
258 static gboolean g_child_watch_prepare (GSource *source,
260 static gboolean g_child_watch_check (GSource *source);
261 static gboolean g_child_watch_dispatch (GSource *source,
262 GSourceFunc callback,
264 static gboolean g_idle_prepare (GSource *source,
266 static gboolean g_idle_check (GSource *source);
267 static gboolean g_idle_dispatch (GSource *source,
268 GSourceFunc callback,
271 G_LOCK_DEFINE_STATIC (main_loop);
272 static GMainContext *default_main_context;
273 static GSList *main_contexts_without_pipe = NULL;
276 /* Child status monitoring code */
278 CHILD_WATCH_UNINITIALIZED,
279 CHILD_WATCH_INITIALIZED_SINGLE,
280 CHILD_WATCH_INITIALIZED_THREADED
282 static gint child_watch_init_state = CHILD_WATCH_UNINITIALIZED;
283 static gint child_watch_count = 1;
284 static gint child_watch_wake_up_pipe[2] = {0, 0};
285 #endif /* !G_OS_WIN32 */
286 G_LOCK_DEFINE_STATIC (main_context_list);
287 static GSList *main_context_list = NULL;
289 static gint timer_perturb = -1;
291 GSourceFuncs g_timeout_funcs =
299 GSourceFuncs g_child_watch_funcs =
301 g_child_watch_prepare,
303 g_child_watch_dispatch,
307 GSourceFuncs g_idle_funcs =
316 * g_main_context_ref:
317 * @context: a #GMainContext
319 * Increases the reference count on a #GMainContext object by one.
321 * Returns: the @context that was passed in (since 2.6)
324 g_main_context_ref (GMainContext *context)
326 g_return_val_if_fail (context != NULL, NULL);
327 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
329 g_atomic_int_inc (&context->ref_count);
335 poll_rec_list_free (GMainContext *context,
338 g_slice_free_chain (GPollRec, list, next);
342 * g_main_context_unref:
343 * @context: a #GMainContext
345 * Decreases the reference count on a #GMainContext object by one. If
346 * the result is zero, free the context and free all associated memory.
349 g_main_context_unref (GMainContext *context)
352 g_return_if_fail (context != NULL);
353 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
355 if (!g_atomic_int_dec_and_test (&context->ref_count))
358 G_LOCK (main_context_list);
359 main_context_list = g_slist_remove (main_context_list, context);
360 G_UNLOCK (main_context_list);
362 source = context->source_list;
365 GSource *next = source->next;
366 g_source_destroy_internal (source, context, FALSE);
370 #ifdef G_THREADS_ENABLED
371 g_static_mutex_free (&context->mutex);
374 g_ptr_array_free (context->pending_dispatches, TRUE);
375 g_free (context->cached_poll_array);
377 poll_rec_list_free (context, context->poll_records);
379 #ifdef G_THREADS_ENABLED
380 if (g_thread_supported())
383 close (context->wake_up_pipe[0]);
384 close (context->wake_up_pipe[1]);
386 CloseHandle (context->wake_up_semaphore);
390 main_contexts_without_pipe = g_slist_remove (main_contexts_without_pipe,
393 if (context->cond != NULL)
394 g_cond_free (context->cond);
400 #ifdef G_THREADS_ENABLED
402 g_main_context_init_pipe (GMainContext *context)
405 if (context->wake_up_pipe[0] != -1)
409 /* if this fails, we fall through and try pipe */
410 pipe2 (context->wake_up_pipe, O_CLOEXEC);
412 if (context->wake_up_pipe[0] == -1)
414 if (pipe (context->wake_up_pipe) < 0)
415 g_error ("Cannot create pipe main loop wake-up: %s\n",
418 fcntl (context->wake_up_pipe[0], F_SETFD, FD_CLOEXEC);
419 fcntl (context->wake_up_pipe[1], F_SETFD, FD_CLOEXEC);
422 context->wake_up_rec.fd = context->wake_up_pipe[0];
423 context->wake_up_rec.events = G_IO_IN;
425 if (context->wake_up_semaphore != NULL)
427 context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
428 if (context->wake_up_semaphore == NULL)
429 g_error ("Cannot create wake-up semaphore: %s",
430 g_win32_error_message (GetLastError ()));
431 context->wake_up_rec.fd = (gintptr) context->wake_up_semaphore;
432 context->wake_up_rec.events = G_IO_IN;
434 if (_g_main_poll_debug)
435 g_print ("wake-up semaphore: %p\n", context->wake_up_semaphore);
437 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
441 _g_main_thread_init (void)
443 GSList *curr = main_contexts_without_pipe;
446 g_main_context_init_pipe ((GMainContext *)curr->data);
449 g_slist_free (main_contexts_without_pipe);
450 main_contexts_without_pipe = NULL;
452 #endif /* G_THREADS_ENABLED */
455 * g_main_context_new:
457 * Creates a new #GMainContext structure.
459 * Return value: the new #GMainContext
462 g_main_context_new (void)
464 GMainContext *context = g_new0 (GMainContext, 1);
466 #ifdef G_MAIN_POLL_DEBUG
468 static gboolean beenhere = FALSE;
472 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
473 _g_main_poll_debug = TRUE;
479 #ifdef G_THREADS_ENABLED
480 g_static_mutex_init (&context->mutex);
482 context->owner = NULL;
483 context->waiters = NULL;
486 context->wake_up_pipe[0] = -1;
487 context->wake_up_pipe[1] = -1;
489 context->wake_up_semaphore = NULL;
493 context->ref_count = 1;
495 context->next_id = 1;
497 context->source_list = NULL;
499 context->poll_func = g_poll;
501 context->cached_poll_array = NULL;
502 context->cached_poll_array_size = 0;
504 context->pending_dispatches = g_ptr_array_new ();
506 context->time_is_current = FALSE;
508 #ifdef G_THREADS_ENABLED
509 if (g_thread_supported ())
510 g_main_context_init_pipe (context);
512 main_contexts_without_pipe = g_slist_prepend (main_contexts_without_pipe,
516 G_LOCK (main_context_list);
517 main_context_list = g_slist_append (main_context_list, context);
519 #ifdef G_MAIN_POLL_DEBUG
520 if (_g_main_poll_debug)
521 g_print ("created context=%p\n", context);
524 G_UNLOCK (main_context_list);
530 * g_main_context_default:
532 * Returns the default main context. This is the main context used
533 * for main loop functions when a main loop is not explicitly
536 * Return value: the default main context.
539 g_main_context_default (void)
545 if (!default_main_context)
547 default_main_context = g_main_context_new ();
548 #ifdef G_MAIN_POLL_DEBUG
549 if (_g_main_poll_debug)
550 g_print ("default context=%p\n", default_main_context);
554 G_UNLOCK (main_loop);
556 return default_main_context;
559 /* Hooks for adding to the main loop */
563 * @source_funcs: structure containing functions that implement
564 * the sources behavior.
565 * @struct_size: size of the #GSource structure to create.
567 * Creates a new #GSource structure. The size is specified to
568 * allow creating structures derived from #GSource that contain
569 * additional data. The size passed in must be at least
570 * <literal>sizeof (GSource)</literal>.
572 * The source will not initially be associated with any #GMainContext
573 * and must be added to one with g_source_attach() before it will be
576 * Return value: the newly-created #GSource.
579 g_source_new (GSourceFuncs *source_funcs,
584 g_return_val_if_fail (source_funcs != NULL, NULL);
585 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
587 source = (GSource*) g_malloc0 (struct_size);
589 source->source_funcs = source_funcs;
590 source->ref_count = 1;
592 source->priority = G_PRIORITY_DEFAULT;
594 source->flags = G_HOOK_FLAG_ACTIVE;
596 /* NULL/0 initialization for all other fields */
601 /* Holds context's lock
604 g_source_list_add (GSource *source,
605 GMainContext *context)
607 GSource *tmp_source, *last_source;
610 tmp_source = context->source_list;
611 while (tmp_source && tmp_source->priority <= source->priority)
613 last_source = tmp_source;
614 tmp_source = tmp_source->next;
617 source->next = tmp_source;
619 tmp_source->prev = source;
621 source->prev = last_source;
623 last_source->next = source;
625 context->source_list = source;
628 /* Holds context's lock
631 g_source_list_remove (GSource *source,
632 GMainContext *context)
635 source->prev->next = source->next;
637 context->source_list = source->next;
640 source->next->prev = source->prev;
648 * @source: a #GSource
649 * @context: a #GMainContext (if %NULL, the default context will be used)
651 * Adds a #GSource to a @context so that it will be executed within
652 * that context. Remove it by calling g_source_destroy().
654 * Return value: the ID (greater than 0) for the source within the
658 g_source_attach (GSource *source,
659 GMainContext *context)
664 g_return_val_if_fail (source->context == NULL, 0);
665 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
668 context = g_main_context_default ();
670 LOCK_CONTEXT (context);
672 source->context = context;
673 result = source->source_id = context->next_id++;
676 g_source_list_add (source, context);
678 tmp_list = source->poll_fds;
681 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
682 tmp_list = tmp_list->next;
685 #ifdef G_THREADS_ENABLED
686 /* Now wake up the main loop if it is waiting in the poll() */
687 g_main_context_wakeup_unlocked (context);
690 UNLOCK_CONTEXT (context);
696 g_source_destroy_internal (GSource *source,
697 GMainContext *context,
701 LOCK_CONTEXT (context);
703 if (!SOURCE_DESTROYED (source))
706 gpointer old_cb_data;
707 GSourceCallbackFuncs *old_cb_funcs;
709 source->flags &= ~G_HOOK_FLAG_ACTIVE;
711 old_cb_data = source->callback_data;
712 old_cb_funcs = source->callback_funcs;
714 source->callback_data = NULL;
715 source->callback_funcs = NULL;
719 UNLOCK_CONTEXT (context);
720 old_cb_funcs->unref (old_cb_data);
721 LOCK_CONTEXT (context);
724 if (!SOURCE_BLOCKED (source))
726 tmp_list = source->poll_fds;
729 g_main_context_remove_poll_unlocked (context, tmp_list->data);
730 tmp_list = tmp_list->next;
734 g_source_unref_internal (source, context, TRUE);
738 UNLOCK_CONTEXT (context);
743 * @source: a #GSource
745 * Removes a source from its #GMainContext, if any, and mark it as
746 * destroyed. The source cannot be subsequently added to another
750 g_source_destroy (GSource *source)
752 GMainContext *context;
754 g_return_if_fail (source != NULL);
756 context = source->context;
759 g_source_destroy_internal (source, context, FALSE);
761 source->flags &= ~G_HOOK_FLAG_ACTIVE;
766 * @source: a #GSource
768 * Returns the numeric ID for a particular source. The ID of a source
769 * is a positive integer which is unique within a particular main loop
770 * context. The reverse
771 * mapping from ID to source is done by g_main_context_find_source_by_id().
773 * Return value: the ID (greater than 0) for the source
776 g_source_get_id (GSource *source)
780 g_return_val_if_fail (source != NULL, 0);
781 g_return_val_if_fail (source->context != NULL, 0);
783 LOCK_CONTEXT (source->context);
784 result = source->source_id;
785 UNLOCK_CONTEXT (source->context);
791 * g_source_get_context:
792 * @source: a #GSource
794 * Gets the #GMainContext with which the source is associated.
795 * Calling this function on a destroyed source is an error.
797 * Return value: the #GMainContext with which the source is associated,
798 * or %NULL if the context has not yet been added
802 g_source_get_context (GSource *source)
804 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
806 return source->context;
812 * @fd: a #GPollFD structure holding information about a file
813 * descriptor to watch.
815 * Adds a file descriptor to the set of file descriptors polled for
816 * this source. This is usually combined with g_source_new() to add an
817 * event source. The event source's check function will typically test
818 * the @revents field in the #GPollFD struct and return %TRUE if events need
822 g_source_add_poll (GSource *source,
825 GMainContext *context;
827 g_return_if_fail (source != NULL);
828 g_return_if_fail (fd != NULL);
829 g_return_if_fail (!SOURCE_DESTROYED (source));
831 context = source->context;
834 LOCK_CONTEXT (context);
836 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
840 if (!SOURCE_BLOCKED (source))
841 g_main_context_add_poll_unlocked (context, source->priority, fd);
842 UNLOCK_CONTEXT (context);
847 * g_source_remove_poll:
849 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
851 * Removes a file descriptor from the set of file descriptors polled for
855 g_source_remove_poll (GSource *source,
858 GMainContext *context;
860 g_return_if_fail (source != NULL);
861 g_return_if_fail (fd != NULL);
862 g_return_if_fail (!SOURCE_DESTROYED (source));
864 context = source->context;
867 LOCK_CONTEXT (context);
869 source->poll_fds = g_slist_remove (source->poll_fds, fd);
873 if (!SOURCE_BLOCKED (source))
874 g_main_context_remove_poll_unlocked (context, fd);
875 UNLOCK_CONTEXT (context);
880 * g_source_set_callback_indirect:
881 * @source: the source
882 * @callback_data: pointer to callback data "object"
883 * @callback_funcs: functions for reference counting @callback_data
884 * and getting the callback and data
886 * Sets the callback function storing the data as a refcounted callback
887 * "object". This is used internally. Note that calling
888 * g_source_set_callback_indirect() assumes
889 * an initial reference count on @callback_data, and thus
890 * @callback_funcs->unref will eventually be called once more
891 * than @callback_funcs->ref.
894 g_source_set_callback_indirect (GSource *source,
895 gpointer callback_data,
896 GSourceCallbackFuncs *callback_funcs)
898 GMainContext *context;
899 gpointer old_cb_data;
900 GSourceCallbackFuncs *old_cb_funcs;
902 g_return_if_fail (source != NULL);
903 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
905 context = source->context;
908 LOCK_CONTEXT (context);
910 old_cb_data = source->callback_data;
911 old_cb_funcs = source->callback_funcs;
913 source->callback_data = callback_data;
914 source->callback_funcs = callback_funcs;
917 UNLOCK_CONTEXT (context);
920 old_cb_funcs->unref (old_cb_data);
924 g_source_callback_ref (gpointer cb_data)
926 GSourceCallback *callback = cb_data;
928 callback->ref_count++;
933 g_source_callback_unref (gpointer cb_data)
935 GSourceCallback *callback = cb_data;
937 callback->ref_count--;
938 if (callback->ref_count == 0)
940 if (callback->notify)
941 callback->notify (callback->data);
947 g_source_callback_get (gpointer cb_data,
952 GSourceCallback *callback = cb_data;
954 *func = callback->func;
955 *data = callback->data;
958 static GSourceCallbackFuncs g_source_callback_funcs = {
959 g_source_callback_ref,
960 g_source_callback_unref,
961 g_source_callback_get,
965 * g_source_set_callback:
966 * @source: the source
967 * @func: a callback function
968 * @data: the data to pass to callback function
969 * @notify: a function to call when @data is no longer in use, or %NULL.
971 * Sets the callback function for a source. The callback for a source is
972 * called from the source's dispatch function.
974 * The exact type of @func depends on the type of source; ie. you
975 * should not count on @func being called with @data as its first
978 * Typically, you won't use this function. Instead use functions specific
979 * to the type of source you are using.
982 g_source_set_callback (GSource *source,
985 GDestroyNotify notify)
987 GSourceCallback *new_callback;
989 g_return_if_fail (source != NULL);
991 new_callback = g_new (GSourceCallback, 1);
993 new_callback->ref_count = 1;
994 new_callback->func = func;
995 new_callback->data = data;
996 new_callback->notify = notify;
998 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1003 * g_source_set_funcs:
1004 * @source: a #GSource
1005 * @funcs: the new #GSourceFuncs
1007 * Sets the source functions (can be used to override
1008 * default implementations) of an unattached source.
1013 g_source_set_funcs (GSource *source,
1014 GSourceFuncs *funcs)
1016 g_return_if_fail (source != NULL);
1017 g_return_if_fail (source->context == NULL);
1018 g_return_if_fail (source->ref_count > 0);
1019 g_return_if_fail (funcs != NULL);
1021 source->source_funcs = funcs;
1025 * g_source_set_priority:
1026 * @source: a #GSource
1027 * @priority: the new priority.
1029 * Sets the priority of a source. While the main loop is being
1030 * run, a source will be dispatched if it is ready to be dispatched and no sources
1031 * at a higher (numerically smaller) priority are ready to be dispatched.
1034 g_source_set_priority (GSource *source,
1038 GMainContext *context;
1040 g_return_if_fail (source != NULL);
1042 context = source->context;
1045 LOCK_CONTEXT (context);
1047 source->priority = priority;
1051 /* Remove the source from the context's source and then
1052 * add it back so it is sorted in the correct plcae
1054 g_source_list_remove (source, source->context);
1055 g_source_list_add (source, source->context);
1057 if (!SOURCE_BLOCKED (source))
1059 tmp_list = source->poll_fds;
1062 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1063 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1065 tmp_list = tmp_list->next;
1069 UNLOCK_CONTEXT (source->context);
1074 * g_source_get_priority:
1075 * @source: a #GSource
1077 * Gets the priority of a source.
1079 * Return value: the priority of the source
1082 g_source_get_priority (GSource *source)
1084 g_return_val_if_fail (source != NULL, 0);
1086 return source->priority;
1090 * g_source_set_can_recurse:
1091 * @source: a #GSource
1092 * @can_recurse: whether recursion is allowed for this source
1094 * Sets whether a source can be called recursively. If @can_recurse is
1095 * %TRUE, then while the source is being dispatched then this source
1096 * will be processed normally. Otherwise, all processing of this
1097 * source is blocked until the dispatch function returns.
1100 g_source_set_can_recurse (GSource *source,
1101 gboolean can_recurse)
1103 GMainContext *context;
1105 g_return_if_fail (source != NULL);
1107 context = source->context;
1110 LOCK_CONTEXT (context);
1113 source->flags |= G_SOURCE_CAN_RECURSE;
1115 source->flags &= ~G_SOURCE_CAN_RECURSE;
1118 UNLOCK_CONTEXT (context);
1122 * g_source_get_can_recurse:
1123 * @source: a #GSource
1125 * Checks whether a source is allowed to be called recursively.
1126 * see g_source_set_can_recurse().
1128 * Return value: whether recursion is allowed.
1131 g_source_get_can_recurse (GSource *source)
1133 g_return_val_if_fail (source != NULL, FALSE);
1135 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1140 * @source: a #GSource
1142 * Increases the reference count on a source by one.
1144 * Return value: @source
1147 g_source_ref (GSource *source)
1149 GMainContext *context;
1151 g_return_val_if_fail (source != NULL, NULL);
1153 context = source->context;
1156 LOCK_CONTEXT (context);
1158 source->ref_count++;
1161 UNLOCK_CONTEXT (context);
1166 /* g_source_unref() but possible to call within context lock
1169 g_source_unref_internal (GSource *source,
1170 GMainContext *context,
1173 gpointer old_cb_data = NULL;
1174 GSourceCallbackFuncs *old_cb_funcs = NULL;
1176 g_return_if_fail (source != NULL);
1178 if (!have_lock && context)
1179 LOCK_CONTEXT (context);
1181 source->ref_count--;
1182 if (source->ref_count == 0)
1184 old_cb_data = source->callback_data;
1185 old_cb_funcs = source->callback_funcs;
1187 source->callback_data = NULL;
1188 source->callback_funcs = NULL;
1190 if (context && !SOURCE_DESTROYED (source))
1192 g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1193 source->ref_count++;
1196 g_source_list_remove (source, context);
1198 if (source->source_funcs->finalize)
1199 source->source_funcs->finalize (source);
1201 g_slist_free (source->poll_fds);
1202 source->poll_fds = NULL;
1206 if (!have_lock && context)
1207 UNLOCK_CONTEXT (context);
1212 UNLOCK_CONTEXT (context);
1214 old_cb_funcs->unref (old_cb_data);
1217 LOCK_CONTEXT (context);
1223 * @source: a #GSource
1225 * Decreases the reference count of a source by one. If the
1226 * resulting reference count is zero the source and associated
1227 * memory will be destroyed.
1230 g_source_unref (GSource *source)
1232 g_return_if_fail (source != NULL);
1234 g_source_unref_internal (source, source->context, FALSE);
1238 * g_main_context_find_source_by_id:
1239 * @context: a #GMainContext (if %NULL, the default context will be used)
1240 * @source_id: the source ID, as returned by g_source_get_id().
1242 * Finds a #GSource given a pair of context and ID.
1244 * Return value: the #GSource if found, otherwise, %NULL
1247 g_main_context_find_source_by_id (GMainContext *context,
1252 g_return_val_if_fail (source_id > 0, NULL);
1254 if (context == NULL)
1255 context = g_main_context_default ();
1257 LOCK_CONTEXT (context);
1259 source = context->source_list;
1262 if (!SOURCE_DESTROYED (source) &&
1263 source->source_id == source_id)
1265 source = source->next;
1268 UNLOCK_CONTEXT (context);
1274 * g_main_context_find_source_by_funcs_user_data:
1275 * @context: a #GMainContext (if %NULL, the default context will be used).
1276 * @funcs: the @source_funcs passed to g_source_new().
1277 * @user_data: the user data from the callback.
1279 * Finds a source with the given source functions and user data. If
1280 * multiple sources exist with the same source function and user data,
1281 * the first one found will be returned.
1283 * Return value: the source, if one was found, otherwise %NULL
1286 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1287 GSourceFuncs *funcs,
1292 g_return_val_if_fail (funcs != NULL, NULL);
1294 if (context == NULL)
1295 context = g_main_context_default ();
1297 LOCK_CONTEXT (context);
1299 source = context->source_list;
1302 if (!SOURCE_DESTROYED (source) &&
1303 source->source_funcs == funcs &&
1304 source->callback_funcs)
1306 GSourceFunc callback;
1307 gpointer callback_data;
1309 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1311 if (callback_data == user_data)
1314 source = source->next;
1317 UNLOCK_CONTEXT (context);
1323 * g_main_context_find_source_by_user_data:
1324 * @context: a #GMainContext
1325 * @user_data: the user_data for the callback.
1327 * Finds a source with the given user data for the callback. If
1328 * multiple sources exist with the same user data, the first
1329 * one found will be returned.
1331 * Return value: the source, if one was found, otherwise %NULL
1334 g_main_context_find_source_by_user_data (GMainContext *context,
1339 if (context == NULL)
1340 context = g_main_context_default ();
1342 LOCK_CONTEXT (context);
1344 source = context->source_list;
1347 if (!SOURCE_DESTROYED (source) &&
1348 source->callback_funcs)
1350 GSourceFunc callback;
1351 gpointer callback_data = NULL;
1353 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1355 if (callback_data == user_data)
1358 source = source->next;
1361 UNLOCK_CONTEXT (context);
1368 * @tag: the ID of the source to remove.
1370 * Removes the source with the given id from the default main context.
1372 * a #GSource is given by g_source_get_id(), or will be returned by the
1373 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1374 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1375 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1377 * See also g_source_destroy(). You must use g_source_destroy() for sources
1378 * added to a non-default main context.
1380 * Return value: %TRUE if the source was found and removed.
1383 g_source_remove (guint tag)
1387 g_return_val_if_fail (tag > 0, FALSE);
1389 source = g_main_context_find_source_by_id (NULL, tag);
1391 g_source_destroy (source);
1393 return source != NULL;
1397 * g_source_remove_by_user_data:
1398 * @user_data: the user_data for the callback.
1400 * Removes a source from the default main loop context given the user
1401 * data for the callback. If multiple sources exist with the same user
1402 * data, only one will be destroyed.
1404 * Return value: %TRUE if a source was found and removed.
1407 g_source_remove_by_user_data (gpointer user_data)
1411 source = g_main_context_find_source_by_user_data (NULL, user_data);
1414 g_source_destroy (source);
1422 * g_source_remove_by_funcs_user_data:
1423 * @funcs: The @source_funcs passed to g_source_new()
1424 * @user_data: the user data for the callback
1426 * Removes a source from the default main loop context given the
1427 * source functions and user data. If multiple sources exist with the
1428 * same source functions and user data, only one will be destroyed.
1430 * Return value: %TRUE if a source was found and removed.
1433 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1438 g_return_val_if_fail (funcs != NULL, FALSE);
1440 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1443 g_source_destroy (source);
1451 * g_get_current_time:
1452 * @result: #GTimeVal structure in which to store current time.
1454 * Equivalent to the UNIX gettimeofday() function, but portable.
1457 g_get_current_time (GTimeVal *result)
1462 g_return_if_fail (result != NULL);
1464 /*this is required on alpha, there the timeval structs are int's
1465 not longs and a cast only would fail horribly*/
1466 gettimeofday (&r, NULL);
1467 result->tv_sec = r.tv_sec;
1468 result->tv_usec = r.tv_usec;
1473 g_return_if_fail (result != NULL);
1475 GetSystemTimeAsFileTime (&ft);
1476 memmove (&time64, &ft, sizeof (FILETIME));
1478 /* Convert from 100s of nanoseconds since 1601-01-01
1479 * to Unix epoch. Yes, this is Y2038 unsafe.
1481 time64 -= G_GINT64_CONSTANT (116444736000000000);
1484 result->tv_sec = time64 / 1000000;
1485 result->tv_usec = time64 % 1000000;
1490 g_main_dispatch_free (gpointer dispatch)
1492 g_slice_free (GMainDispatch, dispatch);
1495 /* Running the main loop */
1497 static GMainDispatch *
1500 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
1501 GMainDispatch *dispatch = g_static_private_get (&depth_private);
1504 dispatch = g_slice_new0 (GMainDispatch);
1505 g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
1514 * Returns the depth of the stack of calls to
1515 * g_main_context_dispatch() on any #GMainContext in the current thread.
1516 * That is, when called from the toplevel, it gives 0. When
1517 * called from within a callback from g_main_context_iteration()
1518 * (or g_main_loop_run(), etc.) it returns 1. When called from within
1519 * a callback to a recursive call to g_main_context_iterate(),
1520 * it returns 2. And so forth.
1522 * This function is useful in a situation like the following:
1523 * Imagine an extremely simple "garbage collected" system.
1526 * static GList *free_list;
1529 * allocate_memory (gsize size)
1531 * gpointer result = g_malloc (size);
1532 * free_list = g_list_prepend (free_list, result);
1537 * free_allocated_memory (void)
1540 * for (l = free_list; l; l = l->next);
1542 * g_list_free (free_list);
1550 * g_main_context_iteration (NULL, TRUE);
1551 * free_allocated_memory();
1555 * This works from an application, however, if you want to do the same
1556 * thing from a library, it gets more difficult, since you no longer
1557 * control the main loop. You might think you can simply use an idle
1558 * function to make the call to free_allocated_memory(), but that
1559 * doesn't work, since the idle function could be called from a
1560 * recursive callback. This can be fixed by using g_main_depth()
1564 * allocate_memory (gsize size)
1566 * FreeListBlock *block = g_new (FreeListBlock, 1);
1567 * block->mem = g_malloc (size);
1568 * block->depth = g_main_depth ();
1569 * free_list = g_list_prepend (free_list, block);
1570 * return block->mem;
1574 * free_allocated_memory (void)
1578 * int depth = g_main_depth ();
1579 * for (l = free_list; l; );
1581 * GList *next = l->next;
1582 * FreeListBlock *block = l->data;
1583 * if (block->depth > depth)
1585 * g_free (block->mem);
1587 * free_list = g_list_delete_link (free_list, l);
1595 * There is a temptation to use g_main_depth() to solve
1596 * problems with reentrancy. For instance, while waiting for data
1597 * to be received from the network in response to a menu item,
1598 * the menu item might be selected again. It might seem that
1599 * one could make the menu item's callback return immediately
1600 * and do nothing if g_main_depth() returns a value greater than 1.
1601 * However, this should be avoided since the user then sees selecting
1602 * the menu item do nothing. Furthermore, you'll find yourself adding
1603 * these checks all over your code, since there are doubtless many,
1604 * many things that the user could do. Instead, you can use the
1605 * following techniques:
1610 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
1611 * the user from interacting with elements while the main
1612 * loop is recursing.
1617 * Avoid main loop recursion in situations where you can't handle
1618 * arbitrary callbacks. Instead, structure your code so that you
1619 * simply return to the main loop and then get called again when
1620 * there is more work to do.
1625 * Return value: The main loop recursion level in the current thread
1630 GMainDispatch *dispatch = get_dispatch ();
1631 return dispatch->depth;
1635 * g_main_current_source:
1637 * Returns the currently firing source for this thread.
1639 * Return value: The currently firing source or %NULL.
1644 g_main_current_source (void)
1646 GMainDispatch *dispatch = get_dispatch ();
1647 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
1651 * g_source_is_destroyed:
1652 * @source: a #GSource
1654 * Returns whether @source has been destroyed.
1656 * This is important when you operate upon your objects
1657 * from within idle handlers, but may have freed the object
1658 * before the dispatch of your idle handler.
1662 * idle_callback (gpointer data)
1664 * SomeWidget *self = data;
1666 * GDK_THREADS_ENTER (<!-- -->);
1667 * /<!-- -->* do stuff with self *<!-- -->/
1668 * self->idle_id = 0;
1669 * GDK_THREADS_LEAVE (<!-- -->);
1675 * some_widget_do_stuff_later (SomeWidget *self)
1677 * self->idle_id = g_idle_add (idle_callback, self);
1681 * some_widget_finalize (GObject *object)
1683 * SomeWidget *self = SOME_WIDGET (object);
1685 * if (self->idle_id)
1686 * g_source_remove (self->idle_id);
1688 * G_OBJECT_CLASS (parent_class)->finalize (object);
1692 * This will fail in a multi-threaded application if the
1693 * widget is destroyed before the idle handler fires due
1694 * to the use after free in the callback. A solution, to
1695 * this particular problem, is to check to if the source
1696 * has already been destroy within the callback.
1700 * idle_callback (gpointer data)
1702 * SomeWidget *self = data;
1704 * GDK_THREADS_ENTER ();
1705 * if (!g_source_is_destroyed (g_main_current_source ()))
1707 * /<!-- -->* do stuff with self *<!-- -->/
1709 * GDK_THREADS_LEAVE ();
1715 * Return value: %TRUE if the source has been destroyed
1720 g_source_is_destroyed (GSource *source)
1722 return SOURCE_DESTROYED (source);
1726 /* Temporarily remove all this source's file descriptors from the
1727 * poll(), so that if data comes available for one of the file descriptors
1728 * we don't continually spin in the poll()
1730 /* HOLDS: source->context's lock */
1732 block_source (GSource *source)
1736 g_return_if_fail (!SOURCE_BLOCKED (source));
1738 tmp_list = source->poll_fds;
1741 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
1742 tmp_list = tmp_list->next;
1746 /* HOLDS: source->context's lock */
1748 unblock_source (GSource *source)
1752 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
1753 g_return_if_fail (!SOURCE_DESTROYED (source));
1755 tmp_list = source->poll_fds;
1758 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
1759 tmp_list = tmp_list->next;
1763 /* HOLDS: context's lock */
1765 g_main_dispatch (GMainContext *context)
1767 GMainDispatch *current = get_dispatch ();
1770 for (i = 0; i < context->pending_dispatches->len; i++)
1772 GSource *source = context->pending_dispatches->pdata[i];
1774 context->pending_dispatches->pdata[i] = NULL;
1777 source->flags &= ~G_SOURCE_READY;
1779 if (!SOURCE_DESTROYED (source))
1781 gboolean was_in_call;
1782 gpointer user_data = NULL;
1783 GSourceFunc callback = NULL;
1784 GSourceCallbackFuncs *cb_funcs;
1786 gboolean need_destroy;
1788 gboolean (*dispatch) (GSource *,
1791 GSList current_source_link;
1793 dispatch = source->source_funcs->dispatch;
1794 cb_funcs = source->callback_funcs;
1795 cb_data = source->callback_data;
1798 cb_funcs->ref (cb_data);
1800 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
1801 block_source (source);
1803 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
1804 source->flags |= G_HOOK_FLAG_IN_CALL;
1807 cb_funcs->get (cb_data, source, &callback, &user_data);
1809 UNLOCK_CONTEXT (context);
1812 /* The on-stack allocation of the GSList is unconventional, but
1813 * we know that the lifetime of the link is bounded to this
1814 * function as the link is kept in a thread specific list and
1815 * not manipulated outside of this function and its descendants.
1816 * Avoiding the overhead of a g_slist_alloc() is useful as many
1817 * applications do little more than dispatch events.
1819 * This is a performance hack - do not revert to g_slist_prepend()!
1821 current_source_link.data = source;
1822 current_source_link.next = current->dispatching_sources;
1823 current->dispatching_sources = ¤t_source_link;
1824 need_destroy = ! dispatch (source,
1827 g_assert (current->dispatching_sources == ¤t_source_link);
1828 current->dispatching_sources = current_source_link.next;
1832 cb_funcs->unref (cb_data);
1834 LOCK_CONTEXT (context);
1837 source->flags &= ~G_HOOK_FLAG_IN_CALL;
1839 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
1840 !SOURCE_DESTROYED (source))
1841 unblock_source (source);
1843 /* Note: this depends on the fact that we can't switch
1844 * sources from one main context to another
1846 if (need_destroy && !SOURCE_DESTROYED (source))
1848 g_assert (source->context == context);
1849 g_source_destroy_internal (source, context, TRUE);
1853 SOURCE_UNREF (source, context);
1856 g_ptr_array_set_size (context->pending_dispatches, 0);
1859 /* Holds context's lock */
1860 static inline GSource *
1861 next_valid_source (GMainContext *context,
1864 GSource *new_source = source ? source->next : context->source_list;
1868 if (!SOURCE_DESTROYED (new_source))
1870 new_source->ref_count++;
1874 new_source = new_source->next;
1878 SOURCE_UNREF (source, context);
1884 * g_main_context_acquire:
1885 * @context: a #GMainContext
1887 * Tries to become the owner of the specified context.
1888 * If some other thread is the owner of the context,
1889 * returns %FALSE immediately. Ownership is properly
1890 * recursive: the owner can require ownership again
1891 * and will release ownership when g_main_context_release()
1892 * is called as many times as g_main_context_acquire().
1894 * You must be the owner of a context before you
1895 * can call g_main_context_prepare(), g_main_context_query(),
1896 * g_main_context_check(), g_main_context_dispatch().
1898 * Return value: %TRUE if the operation succeeded, and
1899 * this thread is now the owner of @context.
1902 g_main_context_acquire (GMainContext *context)
1904 #ifdef G_THREADS_ENABLED
1905 gboolean result = FALSE;
1906 GThread *self = G_THREAD_SELF;
1908 if (context == NULL)
1909 context = g_main_context_default ();
1911 LOCK_CONTEXT (context);
1913 if (!context->owner)
1915 context->owner = self;
1916 g_assert (context->owner_count == 0);
1919 if (context->owner == self)
1921 context->owner_count++;
1925 UNLOCK_CONTEXT (context);
1928 #else /* !G_THREADS_ENABLED */
1930 #endif /* G_THREADS_ENABLED */
1934 * g_main_context_release:
1935 * @context: a #GMainContext
1937 * Releases ownership of a context previously acquired by this thread
1938 * with g_main_context_acquire(). If the context was acquired multiple
1939 * times, the ownership will be released only when g_main_context_release()
1940 * is called as many times as it was acquired.
1943 g_main_context_release (GMainContext *context)
1945 #ifdef G_THREADS_ENABLED
1946 if (context == NULL)
1947 context = g_main_context_default ();
1949 LOCK_CONTEXT (context);
1951 context->owner_count--;
1952 if (context->owner_count == 0)
1954 context->owner = NULL;
1956 if (context->waiters)
1958 GMainWaiter *waiter = context->waiters->data;
1959 gboolean loop_internal_waiter =
1960 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
1961 context->waiters = g_slist_delete_link (context->waiters,
1963 if (!loop_internal_waiter)
1964 g_mutex_lock (waiter->mutex);
1966 g_cond_signal (waiter->cond);
1968 if (!loop_internal_waiter)
1969 g_mutex_unlock (waiter->mutex);
1973 UNLOCK_CONTEXT (context);
1974 #endif /* G_THREADS_ENABLED */
1978 * g_main_context_wait:
1979 * @context: a #GMainContext
1980 * @cond: a condition variable
1981 * @mutex: a mutex, currently held
1983 * Tries to become the owner of the specified context,
1984 * as with g_main_context_acquire(). But if another thread
1985 * is the owner, atomically drop @mutex and wait on @cond until
1986 * that owner releases ownership or until @cond is signaled, then
1987 * try again (once) to become the owner.
1989 * Return value: %TRUE if the operation succeeded, and
1990 * this thread is now the owner of @context.
1993 g_main_context_wait (GMainContext *context,
1997 #ifdef G_THREADS_ENABLED
1998 gboolean result = FALSE;
1999 GThread *self = G_THREAD_SELF;
2000 gboolean loop_internal_waiter;
2002 if (context == NULL)
2003 context = g_main_context_default ();
2005 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2007 if (!loop_internal_waiter)
2008 LOCK_CONTEXT (context);
2010 if (context->owner && context->owner != self)
2015 waiter.mutex = mutex;
2017 context->waiters = g_slist_append (context->waiters, &waiter);
2019 if (!loop_internal_waiter)
2020 UNLOCK_CONTEXT (context);
2021 g_cond_wait (cond, mutex);
2022 if (!loop_internal_waiter)
2023 LOCK_CONTEXT (context);
2025 context->waiters = g_slist_remove (context->waiters, &waiter);
2028 if (!context->owner)
2030 context->owner = self;
2031 g_assert (context->owner_count == 0);
2034 if (context->owner == self)
2036 context->owner_count++;
2040 if (!loop_internal_waiter)
2041 UNLOCK_CONTEXT (context);
2044 #else /* !G_THREADS_ENABLED */
2046 #endif /* G_THREADS_ENABLED */
2050 * g_main_context_prepare:
2051 * @context: a #GMainContext
2052 * @priority: location to store priority of highest priority
2053 * source already ready.
2055 * Prepares to poll sources within a main loop. The resulting information
2056 * for polling is determined by calling g_main_context_query ().
2058 * Return value: %TRUE if some source is ready to be dispatched
2062 g_main_context_prepare (GMainContext *context,
2067 gint current_priority = G_MAXINT;
2070 if (context == NULL)
2071 context = g_main_context_default ();
2073 LOCK_CONTEXT (context);
2075 context->time_is_current = FALSE;
2077 if (context->in_check_or_prepare)
2079 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2080 "prepare() member.");
2081 UNLOCK_CONTEXT (context);
2085 #ifdef G_THREADS_ENABLED
2086 if (context->poll_waiting)
2088 g_warning("g_main_context_prepare(): main loop already active in another thread");
2089 UNLOCK_CONTEXT (context);
2093 context->poll_waiting = TRUE;
2094 #endif /* G_THREADS_ENABLED */
2097 /* If recursing, finish up current dispatch, before starting over */
2098 if (context->pending_dispatches)
2101 g_main_dispatch (context, ¤t_time);
2103 UNLOCK_CONTEXT (context);
2108 /* If recursing, clear list of pending dispatches */
2110 for (i = 0; i < context->pending_dispatches->len; i++)
2112 if (context->pending_dispatches->pdata[i])
2113 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2115 g_ptr_array_set_size (context->pending_dispatches, 0);
2117 /* Prepare all sources */
2119 context->timeout = -1;
2121 source = next_valid_source (context, NULL);
2124 gint source_timeout = -1;
2126 if ((n_ready > 0) && (source->priority > current_priority))
2128 SOURCE_UNREF (source, context);
2131 if (SOURCE_BLOCKED (source))
2134 if (!(source->flags & G_SOURCE_READY))
2137 gboolean (*prepare) (GSource *source,
2140 prepare = source->source_funcs->prepare;
2141 context->in_check_or_prepare++;
2142 UNLOCK_CONTEXT (context);
2144 result = (*prepare) (source, &source_timeout);
2146 LOCK_CONTEXT (context);
2147 context->in_check_or_prepare--;
2150 source->flags |= G_SOURCE_READY;
2153 if (source->flags & G_SOURCE_READY)
2156 current_priority = source->priority;
2157 context->timeout = 0;
2160 if (source_timeout >= 0)
2162 if (context->timeout < 0)
2163 context->timeout = source_timeout;
2165 context->timeout = MIN (context->timeout, source_timeout);
2169 source = next_valid_source (context, source);
2172 UNLOCK_CONTEXT (context);
2175 *priority = current_priority;
2177 return (n_ready > 0);
2181 * g_main_context_query:
2182 * @context: a #GMainContext
2183 * @max_priority: maximum priority source to check
2184 * @timeout_: location to store timeout to be used in polling
2185 * @fds: location to store #GPollFD records that need to be polled.
2186 * @n_fds: length of @fds.
2188 * Determines information necessary to poll this main loop.
2190 * Return value: the number of records actually stored in @fds,
2191 * or, if more than @n_fds records need to be stored, the number
2192 * of records that need to be stored.
2195 g_main_context_query (GMainContext *context,
2204 LOCK_CONTEXT (context);
2206 pollrec = context->poll_records;
2208 while (pollrec && max_priority >= pollrec->priority)
2210 /* We need to include entries with fd->events == 0 in the array because
2211 * otherwise if the application changes fd->events behind our back and
2212 * makes it non-zero, we'll be out of sync when we check the fds[] array.
2213 * (Changing fd->events after adding an FD wasn't an anticipated use of
2214 * this API, but it occurs in practice.) */
2217 fds[n_poll].fd = pollrec->fd->fd;
2218 /* In direct contradiction to the Unix98 spec, IRIX runs into
2219 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2220 * flags in the events field of the pollfd while it should
2221 * just ignoring them. So we mask them out here.
2223 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2224 fds[n_poll].revents = 0;
2227 pollrec = pollrec->next;
2231 #ifdef G_THREADS_ENABLED
2232 context->poll_changed = FALSE;
2237 *timeout = context->timeout;
2239 context->time_is_current = FALSE;
2242 UNLOCK_CONTEXT (context);
2248 * g_main_context_check:
2249 * @context: a #GMainContext
2250 * @max_priority: the maximum numerical priority of sources to check
2251 * @fds: array of #GPollFD's that was passed to the last call to
2252 * g_main_context_query()
2253 * @n_fds: return value of g_main_context_query()
2255 * Passes the results of polling back to the main loop.
2257 * Return value: %TRUE if some sources are ready to be dispatched.
2260 g_main_context_check (GMainContext *context,
2270 LOCK_CONTEXT (context);
2272 if (context->in_check_or_prepare)
2274 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2275 "prepare() member.");
2276 UNLOCK_CONTEXT (context);
2280 #ifdef G_THREADS_ENABLED
2281 if (!context->poll_waiting)
2285 read (context->wake_up_pipe[0], &a, 1);
2289 context->poll_waiting = FALSE;
2291 /* If the set of poll file descriptors changed, bail out
2292 * and let the main loop rerun
2294 if (context->poll_changed)
2296 UNLOCK_CONTEXT (context);
2299 #endif /* G_THREADS_ENABLED */
2301 pollrec = context->poll_records;
2305 if (pollrec->fd->events)
2306 pollrec->fd->revents = fds[i].revents;
2308 pollrec = pollrec->next;
2312 source = next_valid_source (context, NULL);
2315 if ((n_ready > 0) && (source->priority > max_priority))
2317 SOURCE_UNREF (source, context);
2320 if (SOURCE_BLOCKED (source))
2323 if (!(source->flags & G_SOURCE_READY))
2326 gboolean (*check) (GSource *source);
2328 check = source->source_funcs->check;
2330 context->in_check_or_prepare++;
2331 UNLOCK_CONTEXT (context);
2333 result = (*check) (source);
2335 LOCK_CONTEXT (context);
2336 context->in_check_or_prepare--;
2339 source->flags |= G_SOURCE_READY;
2342 if (source->flags & G_SOURCE_READY)
2344 source->ref_count++;
2345 g_ptr_array_add (context->pending_dispatches, source);
2349 /* never dispatch sources with less priority than the first
2350 * one we choose to dispatch
2352 max_priority = source->priority;
2356 source = next_valid_source (context, source);
2359 UNLOCK_CONTEXT (context);
2365 * g_main_context_dispatch:
2366 * @context: a #GMainContext
2368 * Dispatches all pending sources.
2371 g_main_context_dispatch (GMainContext *context)
2373 LOCK_CONTEXT (context);
2375 if (context->pending_dispatches->len > 0)
2377 g_main_dispatch (context);
2380 UNLOCK_CONTEXT (context);
2383 /* HOLDS context lock */
2385 g_main_context_iterate (GMainContext *context,
2392 gboolean some_ready;
2393 gint nfds, allocated_nfds;
2394 GPollFD *fds = NULL;
2396 UNLOCK_CONTEXT (context);
2398 #ifdef G_THREADS_ENABLED
2399 if (!g_main_context_acquire (context))
2401 gboolean got_ownership;
2403 LOCK_CONTEXT (context);
2405 g_return_val_if_fail (g_thread_supported (), FALSE);
2411 context->cond = g_cond_new ();
2413 got_ownership = g_main_context_wait (context,
2415 g_static_mutex_get_mutex (&context->mutex));
2421 LOCK_CONTEXT (context);
2422 #endif /* G_THREADS_ENABLED */
2424 if (!context->cached_poll_array)
2426 context->cached_poll_array_size = context->n_poll_records;
2427 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2430 allocated_nfds = context->cached_poll_array_size;
2431 fds = context->cached_poll_array;
2433 UNLOCK_CONTEXT (context);
2435 g_main_context_prepare (context, &max_priority);
2437 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
2438 allocated_nfds)) > allocated_nfds)
2440 LOCK_CONTEXT (context);
2442 context->cached_poll_array_size = allocated_nfds = nfds;
2443 context->cached_poll_array = fds = g_new (GPollFD, nfds);
2444 UNLOCK_CONTEXT (context);
2450 g_main_context_poll (context, timeout, max_priority, fds, nfds);
2452 some_ready = g_main_context_check (context, max_priority, fds, nfds);
2455 g_main_context_dispatch (context);
2457 #ifdef G_THREADS_ENABLED
2458 g_main_context_release (context);
2459 #endif /* G_THREADS_ENABLED */
2461 LOCK_CONTEXT (context);
2467 * g_main_context_pending:
2468 * @context: a #GMainContext (if %NULL, the default context will be used)
2470 * Checks if any sources have pending events for the given context.
2472 * Return value: %TRUE if events are pending.
2475 g_main_context_pending (GMainContext *context)
2480 context = g_main_context_default();
2482 LOCK_CONTEXT (context);
2483 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
2484 UNLOCK_CONTEXT (context);
2490 * g_main_context_iteration:
2491 * @context: a #GMainContext (if %NULL, the default context will be used)
2492 * @may_block: whether the call may block.
2494 * Runs a single iteration for the given main loop. This involves
2495 * checking to see if any event sources are ready to be processed,
2496 * then if no events sources are ready and @may_block is %TRUE, waiting
2497 * for a source to become ready, then dispatching the highest priority
2498 * events sources that are ready. Otherwise, if @may_block is %FALSE
2499 * sources are not waited to become ready, only those highest priority
2500 * events sources will be dispatched (if any), that are ready at this
2501 * given moment without further waiting.
2503 * Note that even when @may_block is %TRUE, it is still possible for
2504 * g_main_context_iteration() to return %FALSE, since the the wait may
2505 * be interrupted for other reasons than an event source becoming ready.
2507 * Return value: %TRUE if events were dispatched.
2510 g_main_context_iteration (GMainContext *context, gboolean may_block)
2515 context = g_main_context_default();
2517 LOCK_CONTEXT (context);
2518 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
2519 UNLOCK_CONTEXT (context);
2526 * @context: a #GMainContext (if %NULL, the default context will be used).
2527 * @is_running: set to %TRUE to indicate that the loop is running. This
2528 * is not very important since calling g_main_loop_run() will set this to
2531 * Creates a new #GMainLoop structure.
2533 * Return value: a new #GMainLoop.
2536 g_main_loop_new (GMainContext *context,
2537 gboolean is_running)
2542 context = g_main_context_default();
2544 g_main_context_ref (context);
2546 loop = g_new0 (GMainLoop, 1);
2547 loop->context = context;
2548 loop->is_running = is_running != FALSE;
2549 loop->ref_count = 1;
2556 * @loop: a #GMainLoop
2558 * Increases the reference count on a #GMainLoop object by one.
2560 * Return value: @loop
2563 g_main_loop_ref (GMainLoop *loop)
2565 g_return_val_if_fail (loop != NULL, NULL);
2566 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2568 g_atomic_int_inc (&loop->ref_count);
2574 * g_main_loop_unref:
2575 * @loop: a #GMainLoop
2577 * Decreases the reference count on a #GMainLoop object by one. If
2578 * the result is zero, free the loop and free all associated memory.
2581 g_main_loop_unref (GMainLoop *loop)
2583 g_return_if_fail (loop != NULL);
2584 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2586 if (!g_atomic_int_dec_and_test (&loop->ref_count))
2589 g_main_context_unref (loop->context);
2595 * @loop: a #GMainLoop
2597 * Runs a main loop until g_main_loop_quit() is called on the loop.
2598 * If this is called for the thread of the loop's #GMainContext,
2599 * it will process events from the loop, otherwise it will
2603 g_main_loop_run (GMainLoop *loop)
2605 GThread *self = G_THREAD_SELF;
2607 g_return_if_fail (loop != NULL);
2608 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2610 #ifdef G_THREADS_ENABLED
2611 if (!g_main_context_acquire (loop->context))
2613 gboolean got_ownership = FALSE;
2615 /* Another thread owns this context */
2616 if (!g_thread_supported ())
2618 g_warning ("g_main_loop_run() was called from second thread but "
2619 "g_thread_init() was never called.");
2623 LOCK_CONTEXT (loop->context);
2625 g_atomic_int_inc (&loop->ref_count);
2627 if (!loop->is_running)
2628 loop->is_running = TRUE;
2630 if (!loop->context->cond)
2631 loop->context->cond = g_cond_new ();
2633 while (loop->is_running && !got_ownership)
2634 got_ownership = g_main_context_wait (loop->context,
2635 loop->context->cond,
2636 g_static_mutex_get_mutex (&loop->context->mutex));
2638 if (!loop->is_running)
2640 UNLOCK_CONTEXT (loop->context);
2642 g_main_context_release (loop->context);
2643 g_main_loop_unref (loop);
2647 g_assert (got_ownership);
2650 LOCK_CONTEXT (loop->context);
2651 #endif /* G_THREADS_ENABLED */
2653 if (loop->context->in_check_or_prepare)
2655 g_warning ("g_main_loop_run(): called recursively from within a source's "
2656 "check() or prepare() member, iteration not possible.");
2660 g_atomic_int_inc (&loop->ref_count);
2661 loop->is_running = TRUE;
2662 while (loop->is_running)
2663 g_main_context_iterate (loop->context, TRUE, TRUE, self);
2665 UNLOCK_CONTEXT (loop->context);
2667 #ifdef G_THREADS_ENABLED
2668 g_main_context_release (loop->context);
2669 #endif /* G_THREADS_ENABLED */
2671 g_main_loop_unref (loop);
2676 * @loop: a #GMainLoop
2678 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
2679 * for the loop will return.
2681 * Note that sources that have already been dispatched when
2682 * g_main_loop_quit() is called will still be executed.
2685 g_main_loop_quit (GMainLoop *loop)
2687 g_return_if_fail (loop != NULL);
2688 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2690 LOCK_CONTEXT (loop->context);
2691 loop->is_running = FALSE;
2692 g_main_context_wakeup_unlocked (loop->context);
2694 #ifdef G_THREADS_ENABLED
2695 if (loop->context->cond)
2696 g_cond_broadcast (loop->context->cond);
2697 #endif /* G_THREADS_ENABLED */
2699 UNLOCK_CONTEXT (loop->context);
2703 * g_main_loop_is_running:
2704 * @loop: a #GMainLoop.
2706 * Checks to see if the main loop is currently being run via g_main_loop_run().
2708 * Return value: %TRUE if the mainloop is currently being run.
2711 g_main_loop_is_running (GMainLoop *loop)
2713 g_return_val_if_fail (loop != NULL, FALSE);
2714 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
2716 return loop->is_running;
2720 * g_main_loop_get_context:
2721 * @loop: a #GMainLoop.
2723 * Returns the #GMainContext of @loop.
2725 * Return value: the #GMainContext of @loop
2728 g_main_loop_get_context (GMainLoop *loop)
2730 g_return_val_if_fail (loop != NULL, NULL);
2731 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2733 return loop->context;
2736 /* HOLDS: context's lock */
2738 g_main_context_poll (GMainContext *context,
2744 #ifdef G_MAIN_POLL_DEBUG
2750 GPollFunc poll_func;
2752 if (n_fds || timeout != 0)
2754 #ifdef G_MAIN_POLL_DEBUG
2755 if (_g_main_poll_debug)
2757 g_print ("polling context=%p n=%d timeout=%d\n",
2758 context, n_fds, timeout);
2759 poll_timer = g_timer_new ();
2763 LOCK_CONTEXT (context);
2765 poll_func = context->poll_func;
2767 UNLOCK_CONTEXT (context);
2768 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
2771 g_warning ("poll(2) failed due to: %s.",
2772 g_strerror (errno));
2774 /* If g_poll () returns -1, it has already called g_warning() */
2778 #ifdef G_MAIN_POLL_DEBUG
2779 if (_g_main_poll_debug)
2781 LOCK_CONTEXT (context);
2783 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
2786 g_timer_elapsed (poll_timer, NULL));
2787 g_timer_destroy (poll_timer);
2788 pollrec = context->poll_records;
2790 while (pollrec != NULL)
2795 if (fds[i].fd == pollrec->fd->fd &&
2796 pollrec->fd->events &&
2799 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
2800 if (fds[i].revents & G_IO_IN)
2802 if (fds[i].revents & G_IO_OUT)
2804 if (fds[i].revents & G_IO_PRI)
2806 if (fds[i].revents & G_IO_ERR)
2808 if (fds[i].revents & G_IO_HUP)
2810 if (fds[i].revents & G_IO_NVAL)
2816 pollrec = pollrec->next;
2820 UNLOCK_CONTEXT (context);
2823 } /* if (n_fds || timeout != 0) */
2827 * g_main_context_add_poll:
2828 * @context: a #GMainContext (or %NULL for the default context)
2829 * @fd: a #GPollFD structure holding information about a file
2830 * descriptor to watch.
2831 * @priority: the priority for this file descriptor which should be
2832 * the same as the priority used for g_source_attach() to ensure that the
2833 * file descriptor is polled whenever the results may be needed.
2835 * Adds a file descriptor to the set of file descriptors polled for
2836 * this context. This will very seldomly be used directly. Instead
2837 * a typical event source will use g_source_add_poll() instead.
2840 g_main_context_add_poll (GMainContext *context,
2845 context = g_main_context_default ();
2847 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
2848 g_return_if_fail (fd);
2850 LOCK_CONTEXT (context);
2851 g_main_context_add_poll_unlocked (context, priority, fd);
2852 UNLOCK_CONTEXT (context);
2855 /* HOLDS: main_loop_lock */
2857 g_main_context_add_poll_unlocked (GMainContext *context,
2861 GPollRec *lastrec, *pollrec;
2862 GPollRec *newrec = g_slice_new (GPollRec);
2864 /* This file descriptor may be checked before we ever poll */
2867 newrec->priority = priority;
2870 pollrec = context->poll_records;
2871 while (pollrec && priority >= pollrec->priority)
2874 pollrec = pollrec->next;
2878 lastrec->next = newrec;
2880 context->poll_records = newrec;
2882 newrec->next = pollrec;
2884 context->n_poll_records++;
2886 #ifdef G_THREADS_ENABLED
2887 context->poll_changed = TRUE;
2889 /* Now wake up the main loop if it is waiting in the poll() */
2890 g_main_context_wakeup_unlocked (context);
2895 * g_main_context_remove_poll:
2896 * @context:a #GMainContext
2897 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
2899 * Removes file descriptor from the set of file descriptors to be
2900 * polled for a particular context.
2903 g_main_context_remove_poll (GMainContext *context,
2907 context = g_main_context_default ();
2909 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
2910 g_return_if_fail (fd);
2912 LOCK_CONTEXT (context);
2913 g_main_context_remove_poll_unlocked (context, fd);
2914 UNLOCK_CONTEXT (context);
2918 g_main_context_remove_poll_unlocked (GMainContext *context,
2921 GPollRec *pollrec, *lastrec;
2924 pollrec = context->poll_records;
2928 if (pollrec->fd == fd)
2930 if (lastrec != NULL)
2931 lastrec->next = pollrec->next;
2933 context->poll_records = pollrec->next;
2935 g_slice_free (GPollRec, pollrec);
2937 context->n_poll_records--;
2941 pollrec = pollrec->next;
2944 #ifdef G_THREADS_ENABLED
2945 context->poll_changed = TRUE;
2947 /* Now wake up the main loop if it is waiting in the poll() */
2948 g_main_context_wakeup_unlocked (context);
2953 * g_source_get_current_time:
2954 * @source: a #GSource
2955 * @timeval: #GTimeVal structure in which to store current time.
2957 * Gets the "current time" to be used when checking
2958 * this source. The advantage of calling this function over
2959 * calling g_get_current_time() directly is that when
2960 * checking multiple sources, GLib can cache a single value
2961 * instead of having to repeatedly get the system time.
2964 g_source_get_current_time (GSource *source,
2967 GMainContext *context;
2969 g_return_if_fail (source->context != NULL);
2971 context = source->context;
2973 LOCK_CONTEXT (context);
2975 if (!context->time_is_current)
2977 g_get_current_time (&context->current_time);
2978 context->time_is_current = TRUE;
2981 *timeval = context->current_time;
2983 UNLOCK_CONTEXT (context);
2987 * g_main_context_set_poll_func:
2988 * @context: a #GMainContext
2989 * @func: the function to call to poll all file descriptors
2991 * Sets the function to use to handle polling of file descriptors. It
2992 * will be used instead of the poll() system call
2993 * (or GLib's replacement function, which is used where
2994 * poll() isn't available).
2996 * This function could possibly be used to integrate the GLib event
2997 * loop with an external event loop.
3000 g_main_context_set_poll_func (GMainContext *context,
3004 context = g_main_context_default ();
3006 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3008 LOCK_CONTEXT (context);
3011 context->poll_func = func;
3013 context->poll_func = g_poll;
3015 UNLOCK_CONTEXT (context);
3019 * g_main_context_get_poll_func:
3020 * @context: a #GMainContext
3022 * Gets the poll function set by g_main_context_set_poll_func().
3024 * Return value: the poll function
3027 g_main_context_get_poll_func (GMainContext *context)
3032 context = g_main_context_default ();
3034 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3036 LOCK_CONTEXT (context);
3037 result = context->poll_func;
3038 UNLOCK_CONTEXT (context);
3043 /* HOLDS: context's lock */
3044 /* Wake the main loop up from a poll() */
3046 g_main_context_wakeup_unlocked (GMainContext *context)
3048 #ifdef G_THREADS_ENABLED
3049 if (g_thread_supported() && context->poll_waiting)
3051 context->poll_waiting = FALSE;
3053 write (context->wake_up_pipe[1], "A", 1);
3055 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
3062 * g_main_context_wakeup:
3063 * @context: a #GMainContext
3065 * If @context is currently waiting in a poll(), interrupt
3066 * the poll(), and continue the iteration process.
3069 g_main_context_wakeup (GMainContext *context)
3072 context = g_main_context_default ();
3074 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3076 LOCK_CONTEXT (context);
3077 g_main_context_wakeup_unlocked (context);
3078 UNLOCK_CONTEXT (context);
3082 * g_main_context_is_owner:
3083 * @context: a #GMainContext
3085 * Determines whether this thread holds the (recursive)
3086 * ownership of this #GMaincontext. This is useful to
3087 * know before waiting on another thread that may be
3088 * blocking to get ownership of @context.
3090 * Returns: %TRUE if current thread is owner of @context.
3095 g_main_context_is_owner (GMainContext *context)
3100 context = g_main_context_default ();
3102 #ifdef G_THREADS_ENABLED
3103 LOCK_CONTEXT (context);
3104 is_owner = context->owner == G_THREAD_SELF;
3105 UNLOCK_CONTEXT (context);
3116 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3117 GTimeVal *current_time)
3119 guint seconds = timeout_source->interval / 1000;
3120 guint msecs = timeout_source->interval - seconds * 1000;
3122 timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
3123 timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
3124 if (timeout_source->expiration.tv_usec >= 1000000)
3126 timeout_source->expiration.tv_usec -= 1000000;
3127 timeout_source->expiration.tv_sec++;
3129 if (timer_perturb==-1)
3132 * we want a per machine/session unique 'random' value; try the dbus
3133 * address first, that has a UUID in it. If there is no dbus, use the
3134 * hostname for hashing.
3136 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3137 if (!session_bus_address)
3138 session_bus_address = g_getenv ("HOSTNAME");
3139 if (session_bus_address)
3140 timer_perturb = ABS ((gint) g_str_hash (session_bus_address));
3144 if (timeout_source->granularity)
3147 gint gran; /* in usecs */
3150 gran = timeout_source->granularity * 1000;
3151 perturb = timer_perturb % gran;
3153 * We want to give each machine a per machine pertubation;
3154 * shift time back first, and forward later after the rounding
3157 timeout_source->expiration.tv_usec -= perturb;
3158 if (timeout_source->expiration.tv_usec < 0)
3160 timeout_source->expiration.tv_usec += 1000000;
3161 timeout_source->expiration.tv_sec--;
3164 remainder = timeout_source->expiration.tv_usec % gran;
3165 if (remainder >= gran/4) /* round up */
3166 timeout_source->expiration.tv_usec += gran;
3167 timeout_source->expiration.tv_usec -= remainder;
3169 timeout_source->expiration.tv_usec += perturb;
3171 /* the rounding may have overflown tv_usec */
3172 while (timeout_source->expiration.tv_usec > 1000000)
3174 timeout_source->expiration.tv_usec -= 1000000;
3175 timeout_source->expiration.tv_sec++;
3181 g_timeout_prepare (GSource *source,
3186 GTimeVal current_time;
3188 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3190 g_source_get_current_time (source, ¤t_time);
3192 sec = timeout_source->expiration.tv_sec - current_time.tv_sec;
3193 msec = (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000;
3195 /* We do the following in a rather convoluted fashion to deal with
3196 * the fact that we don't have an integral type big enough to hold
3197 * the difference of two timevals in millseconds.
3199 if (sec < 0 || (sec == 0 && msec < 0))
3203 glong interval_sec = timeout_source->interval / 1000;
3204 glong interval_msec = timeout_source->interval % 1000;
3212 if (sec > interval_sec ||
3213 (sec == interval_sec && msec > interval_msec))
3215 /* The system time has been set backwards, so we
3216 * reset the expiration time to now + timeout_source->interval;
3217 * this at least avoids hanging for long periods of time.
3219 g_timeout_set_expiration (timeout_source, ¤t_time);
3220 msec = MIN (G_MAXINT, timeout_source->interval);
3224 msec = MIN (G_MAXINT, (guint)msec + 1000 * (guint)sec);
3228 *timeout = (gint)msec;
3234 g_timeout_check (GSource *source)
3236 GTimeVal current_time;
3237 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3239 g_source_get_current_time (source, ¤t_time);
3241 return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
3242 ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
3243 (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
3247 g_timeout_dispatch (GSource *source,
3248 GSourceFunc callback,
3251 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3255 g_warning ("Timeout source dispatched without callback\n"
3256 "You must call g_source_set_callback().");
3260 if (callback (user_data))
3262 GTimeVal current_time;
3264 g_source_get_current_time (source, ¤t_time);
3265 g_timeout_set_expiration (timeout_source, ¤t_time);
3274 * g_timeout_source_new:
3275 * @interval: the timeout interval in milliseconds.
3277 * Creates a new timeout source.
3279 * The source will not initially be associated with any #GMainContext
3280 * and must be added to one with g_source_attach() before it will be
3283 * Return value: the newly-created timeout source
3286 g_timeout_source_new (guint interval)
3288 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3289 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3290 GTimeVal current_time;
3292 timeout_source->interval = interval;
3294 g_get_current_time (¤t_time);
3295 g_timeout_set_expiration (timeout_source, ¤t_time);
3301 * g_timeout_source_new_seconds:
3302 * @interval: the timeout interval in seconds
3304 * Creates a new timeout source.
3306 * The source will not initially be associated with any #GMainContext
3307 * and must be added to one with g_source_attach() before it will be
3310 * The scheduling granularity/accuracy of this timeout source will be
3313 * Return value: the newly-created timeout source
3318 g_timeout_source_new_seconds (guint interval)
3320 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3321 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3322 GTimeVal current_time;
3324 timeout_source->interval = 1000*interval;
3325 timeout_source->granularity = 1000;
3327 g_get_current_time (¤t_time);
3328 g_timeout_set_expiration (timeout_source, ¤t_time);
3335 * g_timeout_add_full:
3336 * @priority: the priority of the timeout source. Typically this will be in
3337 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3338 * @interval: the time between calls to the function, in milliseconds
3339 * (1/1000ths of a second)
3340 * @function: function to call
3341 * @data: data to pass to @function
3342 * @notify: function to call when the timeout is removed, or %NULL
3344 * Sets a function to be called at regular intervals, with the given
3345 * priority. The function is called repeatedly until it returns
3346 * %FALSE, at which point the timeout is automatically destroyed and
3347 * the function will not be called again. The @notify function is
3348 * called when the timeout is destroyed. The first call to the
3349 * function will be at the end of the first @interval.
3351 * Note that timeout functions may be delayed, due to the processing of other
3352 * event sources. Thus they should not be relied on for precise timing.
3353 * After each call to the timeout function, the time of the next
3354 * timeout is recalculated based on the current time and the given interval
3355 * (it does not try to 'catch up' time lost in delays).
3357 * This internally creates a main loop source using g_timeout_source_new()
3358 * and attaches it to the main loop context using g_source_attach(). You can
3359 * do these steps manually if you need greater control.
3361 * Return value: the ID (greater than 0) of the event source.
3364 g_timeout_add_full (gint priority,
3366 GSourceFunc function,
3368 GDestroyNotify notify)
3373 g_return_val_if_fail (function != NULL, 0);
3375 source = g_timeout_source_new (interval);
3377 if (priority != G_PRIORITY_DEFAULT)
3378 g_source_set_priority (source, priority);
3380 g_source_set_callback (source, function, data, notify);
3381 id = g_source_attach (source, NULL);
3382 g_source_unref (source);
3389 * @interval: the time between calls to the function, in milliseconds
3390 * (1/1000ths of a second)
3391 * @function: function to call
3392 * @data: data to pass to @function
3394 * Sets a function to be called at regular intervals, with the default
3395 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
3396 * until it returns %FALSE, at which point the timeout is automatically
3397 * destroyed and the function will not be called again. The first call
3398 * to the function will be at the end of the first @interval.
3400 * Note that timeout functions may be delayed, due to the processing of other
3401 * event sources. Thus they should not be relied on for precise timing.
3402 * After each call to the timeout function, the time of the next
3403 * timeout is recalculated based on the current time and the given interval
3404 * (it does not try to 'catch up' time lost in delays).
3406 * If you want to have a timer in the "seconds" range and do not care
3407 * about the exact time of the first call of the timer, use the
3408 * g_timeout_add_seconds() function; this function allows for more
3409 * optimizations and more efficient system power usage.
3411 * This internally creates a main loop source using g_timeout_source_new()
3412 * and attaches it to the main loop context using g_source_attach(). You can
3413 * do these steps manually if you need greater control.
3415 * Return value: the ID (greater than 0) of the event source.
3418 g_timeout_add (guint32 interval,
3419 GSourceFunc function,
3422 return g_timeout_add_full (G_PRIORITY_DEFAULT,
3423 interval, function, data, NULL);
3427 * g_timeout_add_seconds_full:
3428 * @priority: the priority of the timeout source. Typically this will be in
3429 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3430 * @interval: the time between calls to the function, in seconds
3431 * @function: function to call
3432 * @data: data to pass to @function
3433 * @notify: function to call when the timeout is removed, or %NULL
3435 * Sets a function to be called at regular intervals, with @priority.
3436 * The function is called repeatedly until it returns %FALSE, at which
3437 * point the timeout is automatically destroyed and the function will
3438 * not be called again.
3440 * Unlike g_timeout_add(), this function operates at whole second granularity.
3441 * The initial starting point of the timer is determined by the implementation
3442 * and the implementation is expected to group multiple timers together so that
3443 * they fire all at the same time.
3444 * To allow this grouping, the @interval to the first timer is rounded
3445 * and can deviate up to one second from the specified interval.
3446 * Subsequent timer iterations will generally run at the specified interval.
3448 * Note that timeout functions may be delayed, due to the processing of other
3449 * event sources. Thus they should not be relied on for precise timing.
3450 * After each call to the timeout function, the time of the next
3451 * timeout is recalculated based on the current time and the given @interval
3453 * If you want timing more precise than whole seconds, use g_timeout_add()
3456 * The grouping of timers to fire at the same time results in a more power
3457 * and CPU efficient behavior so if your timer is in multiples of seconds
3458 * and you don't require the first timer exactly one second from now, the
3459 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
3461 * This internally creates a main loop source using
3462 * g_timeout_source_new_seconds() and attaches it to the main loop context
3463 * using g_source_attach(). You can do these steps manually if you need
3466 * Return value: the ID (greater than 0) of the event source.
3471 g_timeout_add_seconds_full (gint priority,
3473 GSourceFunc function,
3475 GDestroyNotify notify)
3480 g_return_val_if_fail (function != NULL, 0);
3482 source = g_timeout_source_new_seconds (interval);
3484 if (priority != G_PRIORITY_DEFAULT)
3485 g_source_set_priority (source, priority);
3487 g_source_set_callback (source, function, data, notify);
3488 id = g_source_attach (source, NULL);
3489 g_source_unref (source);
3495 * g_timeout_add_seconds:
3496 * @interval: the time between calls to the function, in seconds
3497 * @function: function to call
3498 * @data: data to pass to @function
3500 * Sets a function to be called at regular intervals with the default
3501 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
3502 * it returns %FALSE, at which point the timeout is automatically destroyed
3503 * and the function will not be called again.
3505 * This internally creates a main loop source using
3506 * g_timeout_source_new_seconds() and attaches it to the main loop context
3507 * using g_source_attach(). You can do these steps manually if you need
3508 * greater control. Also see g_timout_add_seconds_full().
3510 * Return value: the ID (greater than 0) of the event source.
3515 g_timeout_add_seconds (guint interval,
3516 GSourceFunc function,
3519 g_return_val_if_fail (function != NULL, 0);
3521 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
3524 /* Child watch functions */
3529 g_child_watch_prepare (GSource *source,
3538 g_child_watch_check (GSource *source)
3540 GChildWatchSource *child_watch_source;
3541 gboolean child_exited;
3543 child_watch_source = (GChildWatchSource *) source;
3545 child_exited = child_watch_source->poll.revents & G_IO_IN;
3552 * Note: We do _not_ check for the special value of STILL_ACTIVE
3553 * since we know that the process has exited and doing so runs into
3554 * problems if the child process "happens to return STILL_ACTIVE(259)"
3555 * as Microsoft's Platform SDK puts it.
3557 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
3559 gchar *emsg = g_win32_error_message (GetLastError ());
3560 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
3563 child_watch_source->child_status = -1;
3566 child_watch_source->child_status = child_status;
3569 return child_exited;
3572 #else /* G_OS_WIN32 */
3575 check_for_child_exited (GSource *source)
3577 GChildWatchSource *child_watch_source;
3580 /* protect against another SIGCHLD in the middle of this call */
3581 count = child_watch_count;
3583 child_watch_source = (GChildWatchSource *) source;
3585 if (child_watch_source->child_exited)
3588 if (child_watch_source->count < count)
3592 if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
3594 child_watch_source->child_status = child_status;
3595 child_watch_source->child_exited = TRUE;
3597 child_watch_source->count = count;
3600 return child_watch_source->child_exited;
3604 g_child_watch_prepare (GSource *source,
3609 return check_for_child_exited (source);
3614 g_child_watch_check (GSource *source)
3616 return check_for_child_exited (source);
3619 #endif /* G_OS_WIN32 */
3622 g_child_watch_dispatch (GSource *source,
3623 GSourceFunc callback,
3626 GChildWatchSource *child_watch_source;
3627 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
3629 child_watch_source = (GChildWatchSource *) source;
3633 g_warning ("Child watch source dispatched without callback\n"
3634 "You must call g_source_set_callback().");
3638 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
3640 /* We never keep a child watch source around as the child is gone */
3647 g_child_watch_signal_handler (int signum)
3649 child_watch_count ++;
3651 if (child_watch_init_state == CHILD_WATCH_INITIALIZED_THREADED)
3653 write (child_watch_wake_up_pipe[1], "B", 1);
3657 /* We count on the signal interrupting the poll in the same thread.
3663 g_child_watch_source_init_single (void)
3665 struct sigaction action;
3667 g_assert (! g_thread_supported());
3668 g_assert (child_watch_init_state == CHILD_WATCH_UNINITIALIZED);
3670 child_watch_init_state = CHILD_WATCH_INITIALIZED_SINGLE;
3672 action.sa_handler = g_child_watch_signal_handler;
3673 sigemptyset (&action.sa_mask);
3674 action.sa_flags = SA_NOCLDSTOP;
3675 sigaction (SIGCHLD, &action, NULL);
3678 G_GNUC_NORETURN static gpointer
3679 child_watch_helper_thread (gpointer data)
3686 read (child_watch_wake_up_pipe[0], b, 20);
3688 /* We were woken up. Wake up all other contexts in all other threads */
3689 G_LOCK (main_context_list);
3690 for (list = main_context_list; list; list = list->next)
3692 GMainContext *context;
3694 context = list->data;
3695 if (g_atomic_int_get (&context->ref_count) > 0)
3696 /* Due to racing conditions we can find ref_count == 0, in
3697 * that case, however, the context is still not destroyed
3698 * and no poll can be active, otherwise the ref_count
3700 g_main_context_wakeup (context);
3702 G_UNLOCK (main_context_list);
3707 g_child_watch_source_init_multi_threaded (void)
3709 GError *error = NULL;
3710 struct sigaction action;
3712 g_assert (g_thread_supported());
3714 if (pipe (child_watch_wake_up_pipe) < 0)
3715 g_error ("Cannot create wake up pipe: %s\n", g_strerror (errno));
3716 fcntl (child_watch_wake_up_pipe[1], F_SETFL, O_NONBLOCK | fcntl (child_watch_wake_up_pipe[1], F_GETFL));
3718 /* We create a helper thread that polls on the wakeup pipe indefinitely */
3719 /* FIXME: Think this through for races */
3720 if (g_thread_create (child_watch_helper_thread, NULL, FALSE, &error) == NULL)
3721 g_error ("Cannot create a thread to monitor child exit status: %s\n", error->message);
3722 child_watch_init_state = CHILD_WATCH_INITIALIZED_THREADED;
3724 action.sa_handler = g_child_watch_signal_handler;
3725 sigemptyset (&action.sa_mask);
3726 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
3727 sigaction (SIGCHLD, &action, NULL);
3731 g_child_watch_source_init_promote_single_to_threaded (void)
3733 g_child_watch_source_init_multi_threaded ();
3737 g_child_watch_source_init (void)
3739 if (g_thread_supported())
3741 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
3742 g_child_watch_source_init_multi_threaded ();
3743 else if (child_watch_init_state == CHILD_WATCH_INITIALIZED_SINGLE)
3744 g_child_watch_source_init_promote_single_to_threaded ();
3748 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
3749 g_child_watch_source_init_single ();
3753 #endif /* !G_OS_WIN32 */
3756 * g_child_watch_source_new:
3757 * @pid: process to watch. On POSIX the pid of a child process. On
3758 * Windows a handle for a process (which doesn't have to be a child).
3760 * Creates a new child_watch source.
3762 * The source will not initially be associated with any #GMainContext
3763 * and must be added to one with g_source_attach() before it will be
3766 * Note that child watch sources can only be used in conjunction with
3767 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
3770 * Note that on platforms where #GPid must be explicitly closed
3771 * (see g_spawn_close_pid()) @pid must not be closed while the
3772 * source is still active. Typically, you will want to call
3773 * g_spawn_close_pid() in the callback function for the source.
3775 * Note further that using g_child_watch_source_new() is not
3776 * compatible with calling <literal>waitpid(-1)</literal> in
3777 * the application. Calling waitpid() for individual pids will
3780 * Return value: the newly-created child watch source
3785 g_child_watch_source_new (GPid pid)
3787 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
3788 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
3791 child_watch_source->poll.fd = (gintptr) pid;
3792 child_watch_source->poll.events = G_IO_IN;
3794 g_source_add_poll (source, &child_watch_source->poll);
3795 #else /* G_OS_WIN32 */
3796 g_child_watch_source_init ();
3797 #endif /* G_OS_WIN32 */
3799 child_watch_source->pid = pid;
3805 * g_child_watch_add_full:
3806 * @priority: the priority of the idle source. Typically this will be in the
3807 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3808 * @pid: process to watch. On POSIX the pid of a child process. On
3809 * Windows a handle for a process (which doesn't have to be a child).
3810 * @function: function to call
3811 * @data: data to pass to @function
3812 * @notify: function to call when the idle is removed, or %NULL
3814 * Sets a function to be called when the child indicated by @pid
3815 * exits, at the priority @priority.
3817 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
3818 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
3819 * the spawn function for the child watching to work.
3821 * Note that on platforms where #GPid must be explicitly closed
3822 * (see g_spawn_close_pid()) @pid must not be closed while the
3823 * source is still active. Typically, you will want to call
3824 * g_spawn_close_pid() in the callback function for the source.
3826 * GLib supports only a single callback per process id.
3828 * This internally creates a main loop source using
3829 * g_child_watch_source_new() and attaches it to the main loop context
3830 * using g_source_attach(). You can do these steps manually if you
3831 * need greater control.
3833 * Return value: the ID (greater than 0) of the event source.
3838 g_child_watch_add_full (gint priority,
3840 GChildWatchFunc function,
3842 GDestroyNotify notify)
3847 g_return_val_if_fail (function != NULL, 0);
3849 source = g_child_watch_source_new (pid);
3851 if (priority != G_PRIORITY_DEFAULT)
3852 g_source_set_priority (source, priority);
3854 g_source_set_callback (source, (GSourceFunc) function, data, notify);
3855 id = g_source_attach (source, NULL);
3856 g_source_unref (source);
3862 * g_child_watch_add:
3863 * @pid: process id to watch. On POSIX the pid of a child process. On
3864 * Windows a handle for a process (which doesn't have to be a child).
3865 * @function: function to call
3866 * @data: data to pass to @function
3868 * Sets a function to be called when the child indicated by @pid
3869 * exits, at a default priority, #G_PRIORITY_DEFAULT.
3871 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
3872 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
3873 * the spawn function for the child watching to work.
3875 * Note that on platforms where #GPid must be explicitly closed
3876 * (see g_spawn_close_pid()) @pid must not be closed while the
3877 * source is still active. Typically, you will want to call
3878 * g_spawn_close_pid() in the callback function for the source.
3880 * GLib supports only a single callback per process id.
3882 * This internally creates a main loop source using
3883 * g_child_watch_source_new() and attaches it to the main loop context
3884 * using g_source_attach(). You can do these steps manually if you
3885 * need greater control.
3887 * Return value: the ID (greater than 0) of the event source.
3892 g_child_watch_add (GPid pid,
3893 GChildWatchFunc function,
3896 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
3900 /* Idle functions */
3903 g_idle_prepare (GSource *source,
3912 g_idle_check (GSource *source)
3918 g_idle_dispatch (GSource *source,
3919 GSourceFunc callback,
3924 g_warning ("Idle source dispatched without callback\n"
3925 "You must call g_source_set_callback().");
3929 return callback (user_data);
3933 * g_idle_source_new:
3935 * Creates a new idle source.
3937 * The source will not initially be associated with any #GMainContext
3938 * and must be added to one with g_source_attach() before it will be
3939 * executed. Note that the default priority for idle sources is
3940 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
3941 * have a default priority of %G_PRIORITY_DEFAULT.
3943 * Return value: the newly-created idle source
3946 g_idle_source_new (void)
3950 source = g_source_new (&g_idle_funcs, sizeof (GSource));
3951 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
3958 * @priority: the priority of the idle source. Typically this will be in the
3959 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3960 * @function: function to call
3961 * @data: data to pass to @function
3962 * @notify: function to call when the idle is removed, or %NULL
3964 * Adds a function to be called whenever there are no higher priority
3965 * events pending. If the function returns %FALSE it is automatically
3966 * removed from the list of event sources and will not be called again.
3968 * This internally creates a main loop source using g_idle_source_new()
3969 * and attaches it to the main loop context using g_source_attach().
3970 * You can do these steps manually if you need greater control.
3972 * Return value: the ID (greater than 0) of the event source.
3975 g_idle_add_full (gint priority,
3976 GSourceFunc function,
3978 GDestroyNotify notify)
3983 g_return_val_if_fail (function != NULL, 0);
3985 source = g_idle_source_new ();
3987 if (priority != G_PRIORITY_DEFAULT_IDLE)
3988 g_source_set_priority (source, priority);
3990 g_source_set_callback (source, function, data, notify);
3991 id = g_source_attach (source, NULL);
3992 g_source_unref (source);
3999 * @function: function to call
4000 * @data: data to pass to @function.
4002 * Adds a function to be called whenever there are no higher priority
4003 * events pending to the default main loop. The function is given the
4004 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4005 * returns %FALSE it is automatically removed from the list of event
4006 * sources and will not be called again.
4008 * This internally creates a main loop source using g_idle_source_new()
4009 * and attaches it to the main loop context using g_source_attach().
4010 * You can do these steps manually if you need greater control.
4012 * Return value: the ID (greater than 0) of the event source.
4015 g_idle_add (GSourceFunc function,
4018 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4022 * g_idle_remove_by_data:
4023 * @data: the data for the idle source's callback.
4025 * Removes the idle function with the given data.
4027 * Return value: %TRUE if an idle source was found and removed.
4030 g_idle_remove_by_data (gpointer data)
4032 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4035 #define __G_MAIN_C__
4036 #include "galiasdef.c"