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
50 #include "gthreadprivate.h"
52 #include <sys/types.h>
55 #ifdef HAVE_SYS_TIME_H
57 #endif /* HAVE_SYS_TIME_H */
60 #endif /* HAVE_UNISTD_H */
66 #endif /* G_OS_WIN32 */
69 #include <sys/socket.h>
71 #endif /* G_OS_BEOS */
82 typedef struct _GTimeoutSource GTimeoutSource;
83 typedef struct _GChildWatchSource GChildWatchSource;
84 typedef struct _GPollRec GPollRec;
85 typedef struct _GSourceCallback GSourceCallback;
89 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
90 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
93 #ifdef G_THREADS_ENABLED
94 typedef struct _GMainWaiter GMainWaiter;
103 typedef struct _GMainDispatch GMainDispatch;
105 struct _GMainDispatch
108 GSList *dispatching_sources; /* stack of current sources */
111 #ifdef G_MAIN_POLL_DEBUG
112 gboolean _g_main_poll_debug = FALSE;
117 #ifdef G_THREADS_ENABLED
118 /* The following lock is used for both the list of sources
119 * and the list of poll records
130 GPtrArray *pending_dispatches;
131 gint timeout; /* Timeout for current iteration */
134 GSource *source_list;
135 gint in_check_or_prepare;
137 GPollRec *poll_records;
138 guint n_poll_records;
139 GPollFD *cached_poll_array;
140 guint cached_poll_array_size;
142 #ifdef G_THREADS_ENABLED
144 /* this pipe is used to wake up the main loop when a source is added.
146 gint wake_up_pipe[2];
147 #else /* G_OS_WIN32 */
148 HANDLE wake_up_semaphore;
149 #endif /* G_OS_WIN32 */
152 gboolean poll_waiting;
154 /* Flag indicating whether the set of fd's changed during a poll */
155 gboolean poll_changed;
156 #endif /* G_THREADS_ENABLED */
160 GTimeVal current_time;
161 gboolean time_is_current;
164 struct _GSourceCallback
169 GDestroyNotify notify;
174 GMainContext *context;
179 struct _GTimeoutSource
187 struct _GChildWatchSource
194 #else /* G_OS_WIN32 */
196 gboolean child_exited;
197 #endif /* G_OS_WIN32 */
207 #ifdef G_THREADS_ENABLED
208 #define LOCK_CONTEXT(context) g_static_mutex_lock (&context->mutex)
209 #define UNLOCK_CONTEXT(context) g_static_mutex_unlock (&context->mutex)
210 #define G_THREAD_SELF g_thread_self ()
212 #define LOCK_CONTEXT(context) (void)0
213 #define UNLOCK_CONTEXT(context) (void)0
214 #define G_THREAD_SELF NULL
217 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
218 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
219 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
221 #define SOURCE_UNREF(source, context) \
223 if ((source)->ref_count > 1) \
224 (source)->ref_count--; \
226 g_source_unref_internal ((source), (context), TRUE); \
230 /* Forward declarations */
232 static void g_source_unref_internal (GSource *source,
233 GMainContext *context,
235 static void g_source_destroy_internal (GSource *source,
236 GMainContext *context,
238 static void g_main_context_poll (GMainContext *context,
243 static void g_main_context_add_poll_unlocked (GMainContext *context,
246 static void g_main_context_remove_poll_unlocked (GMainContext *context,
248 static void g_main_context_wakeup_unlocked (GMainContext *context);
250 static gboolean g_timeout_prepare (GSource *source,
252 static gboolean g_timeout_check (GSource *source);
253 static gboolean g_timeout_dispatch (GSource *source,
254 GSourceFunc callback,
256 static gboolean g_child_watch_prepare (GSource *source,
258 static gboolean g_child_watch_check (GSource *source);
259 static gboolean g_child_watch_dispatch (GSource *source,
260 GSourceFunc callback,
262 static gboolean g_idle_prepare (GSource *source,
264 static gboolean g_idle_check (GSource *source);
265 static gboolean g_idle_dispatch (GSource *source,
266 GSourceFunc callback,
269 G_LOCK_DEFINE_STATIC (main_loop);
270 static GMainContext *default_main_context;
271 static GSList *main_contexts_without_pipe = NULL;
274 /* Child status monitoring code */
276 CHILD_WATCH_UNINITIALIZED,
277 CHILD_WATCH_INITIALIZED_SINGLE,
278 CHILD_WATCH_INITIALIZED_THREADED
280 static gint child_watch_init_state = CHILD_WATCH_UNINITIALIZED;
281 static gint child_watch_count = 1;
282 static gint child_watch_wake_up_pipe[2] = {0, 0};
283 #endif /* !G_OS_WIN32 */
284 G_LOCK_DEFINE_STATIC (main_context_list);
285 static GSList *main_context_list = NULL;
287 static gint timer_perturb = -1;
289 GSourceFuncs g_timeout_funcs =
297 GSourceFuncs g_child_watch_funcs =
299 g_child_watch_prepare,
301 g_child_watch_dispatch,
305 GSourceFuncs g_idle_funcs =
314 * g_main_context_ref:
315 * @context: a #GMainContext
317 * Increases the reference count on a #GMainContext object by one.
319 * Returns: the @context that was passed in (since 2.6)
322 g_main_context_ref (GMainContext *context)
324 g_return_val_if_fail (context != NULL, NULL);
325 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
327 g_atomic_int_inc (&context->ref_count);
333 poll_rec_list_free (GMainContext *context,
336 g_slice_free_chain (GPollRec, list, next);
340 * g_main_context_unref:
341 * @context: a #GMainContext
343 * Decreases the reference count on a #GMainContext object by one. If
344 * the result is zero, free the context and free all associated memory.
347 g_main_context_unref (GMainContext *context)
350 g_return_if_fail (context != NULL);
351 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
353 if (!g_atomic_int_dec_and_test (&context->ref_count))
356 G_LOCK (main_context_list);
357 main_context_list = g_slist_remove (main_context_list, context);
358 G_UNLOCK (main_context_list);
360 source = context->source_list;
363 GSource *next = source->next;
364 g_source_destroy_internal (source, context, FALSE);
368 #ifdef G_THREADS_ENABLED
369 g_static_mutex_free (&context->mutex);
372 g_ptr_array_free (context->pending_dispatches, TRUE);
373 g_free (context->cached_poll_array);
375 poll_rec_list_free (context, context->poll_records);
377 #ifdef G_THREADS_ENABLED
378 if (g_thread_supported())
381 close (context->wake_up_pipe[0]);
382 close (context->wake_up_pipe[1]);
384 CloseHandle (context->wake_up_semaphore);
388 main_contexts_without_pipe = g_slist_remove (main_contexts_without_pipe,
391 if (context->cond != NULL)
392 g_cond_free (context->cond);
398 #ifdef G_THREADS_ENABLED
400 g_main_context_init_pipe (GMainContext *context)
403 if (context->wake_up_pipe[0] != -1)
405 if (pipe (context->wake_up_pipe) < 0)
406 g_error ("Cannot create pipe main loop wake-up: %s\n",
409 fcntl (context->wake_up_pipe[0], F_SETFD, FD_CLOEXEC);
410 fcntl (context->wake_up_pipe[1], F_SETFD, FD_CLOEXEC);
412 context->wake_up_rec.fd = context->wake_up_pipe[0];
413 context->wake_up_rec.events = G_IO_IN;
415 if (context->wake_up_semaphore != NULL)
417 context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
418 if (context->wake_up_semaphore == NULL)
419 g_error ("Cannot create wake-up semaphore: %s",
420 g_win32_error_message (GetLastError ()));
421 context->wake_up_rec.fd = (gintptr) context->wake_up_semaphore;
422 context->wake_up_rec.events = G_IO_IN;
424 if (_g_main_poll_debug)
425 g_print ("wake-up semaphore: %p\n", context->wake_up_semaphore);
427 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
431 _g_main_thread_init (void)
433 GSList *curr = main_contexts_without_pipe;
436 g_main_context_init_pipe ((GMainContext *)curr->data);
439 g_slist_free (main_contexts_without_pipe);
440 main_contexts_without_pipe = NULL;
442 #endif /* G_THREADS_ENABLED */
445 * g_main_context_new:
447 * Creates a new #GMainContext structure.
449 * Return value: the new #GMainContext
452 g_main_context_new (void)
454 GMainContext *context = g_new0 (GMainContext, 1);
456 #ifdef G_MAIN_POLL_DEBUG
458 static gboolean beenhere = FALSE;
462 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
463 _g_main_poll_debug = TRUE;
469 #ifdef G_THREADS_ENABLED
470 g_static_mutex_init (&context->mutex);
472 context->owner = NULL;
473 context->waiters = NULL;
476 context->wake_up_pipe[0] = -1;
477 context->wake_up_pipe[1] = -1;
479 context->wake_up_semaphore = NULL;
483 context->ref_count = 1;
485 context->next_id = 1;
487 context->source_list = NULL;
489 context->poll_func = g_poll;
491 context->cached_poll_array = NULL;
492 context->cached_poll_array_size = 0;
494 context->pending_dispatches = g_ptr_array_new ();
496 context->time_is_current = FALSE;
498 #ifdef G_THREADS_ENABLED
499 if (g_thread_supported ())
500 g_main_context_init_pipe (context);
502 main_contexts_without_pipe = g_slist_prepend (main_contexts_without_pipe,
506 G_LOCK (main_context_list);
507 main_context_list = g_slist_append (main_context_list, context);
509 #ifdef G_MAIN_POLL_DEBUG
510 if (_g_main_poll_debug)
511 g_print ("created context=%p\n", context);
514 G_UNLOCK (main_context_list);
520 * g_main_context_default:
522 * Returns the default main context. This is the main context used
523 * for main loop functions when a main loop is not explicitly
526 * Return value: the default main context.
529 g_main_context_default (void)
535 if (!default_main_context)
537 default_main_context = g_main_context_new ();
538 #ifdef G_MAIN_POLL_DEBUG
539 if (_g_main_poll_debug)
540 g_print ("default context=%p\n", default_main_context);
544 G_UNLOCK (main_loop);
546 return default_main_context;
549 /* Hooks for adding to the main loop */
553 * @source_funcs: structure containing functions that implement
554 * the sources behavior.
555 * @struct_size: size of the #GSource structure to create.
557 * Creates a new #GSource structure. The size is specified to
558 * allow creating structures derived from #GSource that contain
559 * additional data. The size passed in must be at least
560 * <literal>sizeof (GSource)</literal>.
562 * The source will not initially be associated with any #GMainContext
563 * and must be added to one with g_source_attach() before it will be
566 * Return value: the newly-created #GSource.
569 g_source_new (GSourceFuncs *source_funcs,
574 g_return_val_if_fail (source_funcs != NULL, NULL);
575 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
577 source = (GSource*) g_malloc0 (struct_size);
579 source->source_funcs = source_funcs;
580 source->ref_count = 1;
582 source->priority = G_PRIORITY_DEFAULT;
584 source->flags = G_HOOK_FLAG_ACTIVE;
586 /* NULL/0 initialization for all other fields */
591 /* Holds context's lock
594 g_source_list_add (GSource *source,
595 GMainContext *context)
597 GSource *tmp_source, *last_source;
600 tmp_source = context->source_list;
601 while (tmp_source && tmp_source->priority <= source->priority)
603 last_source = tmp_source;
604 tmp_source = tmp_source->next;
607 source->next = tmp_source;
609 tmp_source->prev = source;
611 source->prev = last_source;
613 last_source->next = source;
615 context->source_list = source;
618 /* Holds context's lock
621 g_source_list_remove (GSource *source,
622 GMainContext *context)
625 source->prev->next = source->next;
627 context->source_list = source->next;
630 source->next->prev = source->prev;
638 * @source: a #GSource
639 * @context: a #GMainContext (if %NULL, the default context will be used)
641 * Adds a #GSource to a @context so that it will be executed within
642 * that context. Remove it by calling g_source_destroy().
644 * Return value: the ID (greater than 0) for the source within the
648 g_source_attach (GSource *source,
649 GMainContext *context)
654 g_return_val_if_fail (source->context == NULL, 0);
655 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
658 context = g_main_context_default ();
660 LOCK_CONTEXT (context);
662 source->context = context;
663 result = source->source_id = context->next_id++;
666 g_source_list_add (source, context);
668 tmp_list = source->poll_fds;
671 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
672 tmp_list = tmp_list->next;
675 #ifdef G_THREADS_ENABLED
676 /* Now wake up the main loop if it is waiting in the poll() */
677 g_main_context_wakeup_unlocked (context);
680 UNLOCK_CONTEXT (context);
686 g_source_destroy_internal (GSource *source,
687 GMainContext *context,
691 LOCK_CONTEXT (context);
693 if (!SOURCE_DESTROYED (source))
696 gpointer old_cb_data;
697 GSourceCallbackFuncs *old_cb_funcs;
699 source->flags &= ~G_HOOK_FLAG_ACTIVE;
701 old_cb_data = source->callback_data;
702 old_cb_funcs = source->callback_funcs;
704 source->callback_data = NULL;
705 source->callback_funcs = NULL;
709 UNLOCK_CONTEXT (context);
710 old_cb_funcs->unref (old_cb_data);
711 LOCK_CONTEXT (context);
714 if (!SOURCE_BLOCKED (source))
716 tmp_list = source->poll_fds;
719 g_main_context_remove_poll_unlocked (context, tmp_list->data);
720 tmp_list = tmp_list->next;
724 g_source_unref_internal (source, context, TRUE);
728 UNLOCK_CONTEXT (context);
733 * @source: a #GSource
735 * Removes a source from its #GMainContext, if any, and mark it as
736 * destroyed. The source cannot be subsequently added to another
740 g_source_destroy (GSource *source)
742 GMainContext *context;
744 g_return_if_fail (source != NULL);
746 context = source->context;
749 g_source_destroy_internal (source, context, FALSE);
751 source->flags &= ~G_HOOK_FLAG_ACTIVE;
756 * @source: a #GSource
758 * Returns the numeric ID for a particular source. The ID of a source
759 * is a positive integer which is unique within a particular main loop
760 * context. The reverse
761 * mapping from ID to source is done by g_main_context_find_source_by_id().
763 * Return value: the ID (greater than 0) for the source
766 g_source_get_id (GSource *source)
770 g_return_val_if_fail (source != NULL, 0);
771 g_return_val_if_fail (source->context != NULL, 0);
773 LOCK_CONTEXT (source->context);
774 result = source->source_id;
775 UNLOCK_CONTEXT (source->context);
781 * g_source_get_context:
782 * @source: a #GSource
784 * Gets the #GMainContext with which the source is associated.
785 * Calling this function on a destroyed source is an error.
787 * Return value: the #GMainContext with which the source is associated,
788 * or %NULL if the context has not yet been added
792 g_source_get_context (GSource *source)
794 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
796 return source->context;
802 * @fd: a #GPollFD structure holding information about a file
803 * descriptor to watch.
805 * Adds a file descriptor to the set of file descriptors polled for
806 * this source. This is usually combined with g_source_new() to add an
807 * event source. The event source's check function will typically test
808 * the @revents field in the #GPollFD struct and return %TRUE if events need
812 g_source_add_poll (GSource *source,
815 GMainContext *context;
817 g_return_if_fail (source != NULL);
818 g_return_if_fail (fd != NULL);
819 g_return_if_fail (!SOURCE_DESTROYED (source));
821 context = source->context;
824 LOCK_CONTEXT (context);
826 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
830 if (!SOURCE_BLOCKED (source))
831 g_main_context_add_poll_unlocked (context, source->priority, fd);
832 UNLOCK_CONTEXT (context);
837 * g_source_remove_poll:
839 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
841 * Removes a file descriptor from the set of file descriptors polled for
845 g_source_remove_poll (GSource *source,
848 GMainContext *context;
850 g_return_if_fail (source != NULL);
851 g_return_if_fail (fd != NULL);
852 g_return_if_fail (!SOURCE_DESTROYED (source));
854 context = source->context;
857 LOCK_CONTEXT (context);
859 source->poll_fds = g_slist_remove (source->poll_fds, fd);
863 if (!SOURCE_BLOCKED (source))
864 g_main_context_remove_poll_unlocked (context, fd);
865 UNLOCK_CONTEXT (context);
870 * g_source_set_callback_indirect:
871 * @source: the source
872 * @callback_data: pointer to callback data "object"
873 * @callback_funcs: functions for reference counting @callback_data
874 * and getting the callback and data
876 * Sets the callback function storing the data as a refcounted callback
877 * "object". This is used internally. Note that calling
878 * g_source_set_callback_indirect() assumes
879 * an initial reference count on @callback_data, and thus
880 * @callback_funcs->unref will eventually be called once more
881 * than @callback_funcs->ref.
884 g_source_set_callback_indirect (GSource *source,
885 gpointer callback_data,
886 GSourceCallbackFuncs *callback_funcs)
888 GMainContext *context;
889 gpointer old_cb_data;
890 GSourceCallbackFuncs *old_cb_funcs;
892 g_return_if_fail (source != NULL);
893 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
895 context = source->context;
898 LOCK_CONTEXT (context);
900 old_cb_data = source->callback_data;
901 old_cb_funcs = source->callback_funcs;
903 source->callback_data = callback_data;
904 source->callback_funcs = callback_funcs;
907 UNLOCK_CONTEXT (context);
910 old_cb_funcs->unref (old_cb_data);
914 g_source_callback_ref (gpointer cb_data)
916 GSourceCallback *callback = cb_data;
918 callback->ref_count++;
923 g_source_callback_unref (gpointer cb_data)
925 GSourceCallback *callback = cb_data;
927 callback->ref_count--;
928 if (callback->ref_count == 0)
930 if (callback->notify)
931 callback->notify (callback->data);
937 g_source_callback_get (gpointer cb_data,
942 GSourceCallback *callback = cb_data;
944 *func = callback->func;
945 *data = callback->data;
948 static GSourceCallbackFuncs g_source_callback_funcs = {
949 g_source_callback_ref,
950 g_source_callback_unref,
951 g_source_callback_get,
955 * g_source_set_callback:
956 * @source: the source
957 * @func: a callback function
958 * @data: the data to pass to callback function
959 * @notify: a function to call when @data is no longer in use, or %NULL.
961 * Sets the callback function for a source. The callback for a source is
962 * called from the source's dispatch function.
964 * The exact type of @func depends on the type of source; ie. you
965 * should not count on @func being called with @data as its first
968 * Typically, you won't use this function. Instead use functions specific
969 * to the type of source you are using.
972 g_source_set_callback (GSource *source,
975 GDestroyNotify notify)
977 GSourceCallback *new_callback;
979 g_return_if_fail (source != NULL);
981 new_callback = g_new (GSourceCallback, 1);
983 new_callback->ref_count = 1;
984 new_callback->func = func;
985 new_callback->data = data;
986 new_callback->notify = notify;
988 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
993 * g_source_set_funcs:
994 * @source: a #GSource
995 * @funcs: the new #GSourceFuncs
997 * Sets the source functions (can be used to override
998 * default implementations) of an unattached source.
1003 g_source_set_funcs (GSource *source,
1004 GSourceFuncs *funcs)
1006 g_return_if_fail (source != NULL);
1007 g_return_if_fail (source->context == NULL);
1008 g_return_if_fail (source->ref_count > 0);
1009 g_return_if_fail (funcs != NULL);
1011 source->source_funcs = funcs;
1015 * g_source_set_priority:
1016 * @source: a #GSource
1017 * @priority: the new priority.
1019 * Sets the priority of a source. While the main loop is being
1020 * run, a source will be dispatched if it is ready to be dispatched and no sources
1021 * at a higher (numerically smaller) priority are ready to be dispatched.
1024 g_source_set_priority (GSource *source,
1028 GMainContext *context;
1030 g_return_if_fail (source != NULL);
1032 context = source->context;
1035 LOCK_CONTEXT (context);
1037 source->priority = priority;
1041 /* Remove the source from the context's source and then
1042 * add it back so it is sorted in the correct plcae
1044 g_source_list_remove (source, source->context);
1045 g_source_list_add (source, source->context);
1047 if (!SOURCE_BLOCKED (source))
1049 tmp_list = source->poll_fds;
1052 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1053 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1055 tmp_list = tmp_list->next;
1059 UNLOCK_CONTEXT (source->context);
1064 * g_source_get_priority:
1065 * @source: a #GSource
1067 * Gets the priority of a source.
1069 * Return value: the priority of the source
1072 g_source_get_priority (GSource *source)
1074 g_return_val_if_fail (source != NULL, 0);
1076 return source->priority;
1080 * g_source_set_can_recurse:
1081 * @source: a #GSource
1082 * @can_recurse: whether recursion is allowed for this source
1084 * Sets whether a source can be called recursively. If @can_recurse is
1085 * %TRUE, then while the source is being dispatched then this source
1086 * will be processed normally. Otherwise, all processing of this
1087 * source is blocked until the dispatch function returns.
1090 g_source_set_can_recurse (GSource *source,
1091 gboolean can_recurse)
1093 GMainContext *context;
1095 g_return_if_fail (source != NULL);
1097 context = source->context;
1100 LOCK_CONTEXT (context);
1103 source->flags |= G_SOURCE_CAN_RECURSE;
1105 source->flags &= ~G_SOURCE_CAN_RECURSE;
1108 UNLOCK_CONTEXT (context);
1112 * g_source_get_can_recurse:
1113 * @source: a #GSource
1115 * Checks whether a source is allowed to be called recursively.
1116 * see g_source_set_can_recurse().
1118 * Return value: whether recursion is allowed.
1121 g_source_get_can_recurse (GSource *source)
1123 g_return_val_if_fail (source != NULL, FALSE);
1125 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1130 * @source: a #GSource
1132 * Increases the reference count on a source by one.
1134 * Return value: @source
1137 g_source_ref (GSource *source)
1139 GMainContext *context;
1141 g_return_val_if_fail (source != NULL, NULL);
1143 context = source->context;
1146 LOCK_CONTEXT (context);
1148 source->ref_count++;
1151 UNLOCK_CONTEXT (context);
1156 /* g_source_unref() but possible to call within context lock
1159 g_source_unref_internal (GSource *source,
1160 GMainContext *context,
1163 gpointer old_cb_data = NULL;
1164 GSourceCallbackFuncs *old_cb_funcs = NULL;
1166 g_return_if_fail (source != NULL);
1168 if (!have_lock && context)
1169 LOCK_CONTEXT (context);
1171 source->ref_count--;
1172 if (source->ref_count == 0)
1174 old_cb_data = source->callback_data;
1175 old_cb_funcs = source->callback_funcs;
1177 source->callback_data = NULL;
1178 source->callback_funcs = NULL;
1180 if (context && !SOURCE_DESTROYED (source))
1182 g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1183 source->ref_count++;
1186 g_source_list_remove (source, context);
1188 if (source->source_funcs->finalize)
1189 source->source_funcs->finalize (source);
1191 g_slist_free (source->poll_fds);
1192 source->poll_fds = NULL;
1196 if (!have_lock && context)
1197 UNLOCK_CONTEXT (context);
1202 UNLOCK_CONTEXT (context);
1204 old_cb_funcs->unref (old_cb_data);
1207 LOCK_CONTEXT (context);
1213 * @source: a #GSource
1215 * Decreases the reference count of a source by one. If the
1216 * resulting reference count is zero the source and associated
1217 * memory will be destroyed.
1220 g_source_unref (GSource *source)
1222 g_return_if_fail (source != NULL);
1224 g_source_unref_internal (source, source->context, FALSE);
1228 * g_main_context_find_source_by_id:
1229 * @context: a #GMainContext (if %NULL, the default context will be used)
1230 * @source_id: the source ID, as returned by g_source_get_id().
1232 * Finds a #GSource given a pair of context and ID.
1234 * Return value: the #GSource if found, otherwise, %NULL
1237 g_main_context_find_source_by_id (GMainContext *context,
1242 g_return_val_if_fail (source_id > 0, NULL);
1244 if (context == NULL)
1245 context = g_main_context_default ();
1247 LOCK_CONTEXT (context);
1249 source = context->source_list;
1252 if (!SOURCE_DESTROYED (source) &&
1253 source->source_id == source_id)
1255 source = source->next;
1258 UNLOCK_CONTEXT (context);
1264 * g_main_context_find_source_by_funcs_user_data:
1265 * @context: a #GMainContext (if %NULL, the default context will be used).
1266 * @funcs: the @source_funcs passed to g_source_new().
1267 * @user_data: the user data from the callback.
1269 * Finds a source with the given source functions and user data. If
1270 * multiple sources exist with the same source function and user data,
1271 * the first one found will be returned.
1273 * Return value: the source, if one was found, otherwise %NULL
1276 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1277 GSourceFuncs *funcs,
1282 g_return_val_if_fail (funcs != NULL, NULL);
1284 if (context == NULL)
1285 context = g_main_context_default ();
1287 LOCK_CONTEXT (context);
1289 source = context->source_list;
1292 if (!SOURCE_DESTROYED (source) &&
1293 source->source_funcs == funcs &&
1294 source->callback_funcs)
1296 GSourceFunc callback;
1297 gpointer callback_data;
1299 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1301 if (callback_data == user_data)
1304 source = source->next;
1307 UNLOCK_CONTEXT (context);
1313 * g_main_context_find_source_by_user_data:
1314 * @context: a #GMainContext
1315 * @user_data: the user_data for the callback.
1317 * Finds a source with the given user data for the callback. If
1318 * multiple sources exist with the same user data, the first
1319 * one found will be returned.
1321 * Return value: the source, if one was found, otherwise %NULL
1324 g_main_context_find_source_by_user_data (GMainContext *context,
1329 if (context == NULL)
1330 context = g_main_context_default ();
1332 LOCK_CONTEXT (context);
1334 source = context->source_list;
1337 if (!SOURCE_DESTROYED (source) &&
1338 source->callback_funcs)
1340 GSourceFunc callback;
1341 gpointer callback_data = NULL;
1343 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1345 if (callback_data == user_data)
1348 source = source->next;
1351 UNLOCK_CONTEXT (context);
1358 * @tag: the ID of the source to remove.
1360 * Removes the source with the given id from the default main context.
1362 * a #GSource is given by g_source_get_id(), or will be returned by the
1363 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1364 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1365 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1367 * See also g_source_destroy(). You must use g_source_destroy() for sources
1368 * added to a non-default main context.
1370 * Return value: %TRUE if the source was found and removed.
1373 g_source_remove (guint tag)
1377 g_return_val_if_fail (tag > 0, FALSE);
1379 source = g_main_context_find_source_by_id (NULL, tag);
1381 g_source_destroy (source);
1383 return source != NULL;
1387 * g_source_remove_by_user_data:
1388 * @user_data: the user_data for the callback.
1390 * Removes a source from the default main loop context given the user
1391 * data for the callback. If multiple sources exist with the same user
1392 * data, only one will be destroyed.
1394 * Return value: %TRUE if a source was found and removed.
1397 g_source_remove_by_user_data (gpointer user_data)
1401 source = g_main_context_find_source_by_user_data (NULL, user_data);
1404 g_source_destroy (source);
1412 * g_source_remove_by_funcs_user_data:
1413 * @funcs: The @source_funcs passed to g_source_new()
1414 * @user_data: the user data for the callback
1416 * Removes a source from the default main loop context given the
1417 * source functions and user data. If multiple sources exist with the
1418 * same source functions and user data, only one will be destroyed.
1420 * Return value: %TRUE if a source was found and removed.
1423 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1428 g_return_val_if_fail (funcs != NULL, FALSE);
1430 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1433 g_source_destroy (source);
1441 * g_get_current_time:
1442 * @result: #GTimeVal structure in which to store current time.
1444 * Equivalent to the UNIX gettimeofday() function, but portable.
1447 g_get_current_time (GTimeVal *result)
1452 g_return_if_fail (result != NULL);
1454 /*this is required on alpha, there the timeval structs are int's
1455 not longs and a cast only would fail horribly*/
1456 gettimeofday (&r, NULL);
1457 result->tv_sec = r.tv_sec;
1458 result->tv_usec = r.tv_usec;
1463 g_return_if_fail (result != NULL);
1465 GetSystemTimeAsFileTime (&ft);
1466 memmove (&time64, &ft, sizeof (FILETIME));
1468 /* Convert from 100s of nanoseconds since 1601-01-01
1469 * to Unix epoch. Yes, this is Y2038 unsafe.
1471 time64 -= G_GINT64_CONSTANT (116444736000000000);
1474 result->tv_sec = time64 / 1000000;
1475 result->tv_usec = time64 % 1000000;
1480 g_main_dispatch_free (gpointer dispatch)
1482 g_slice_free (GMainDispatch, dispatch);
1485 /* Running the main loop */
1487 static GMainDispatch *
1490 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
1491 GMainDispatch *dispatch = g_static_private_get (&depth_private);
1494 dispatch = g_slice_new0 (GMainDispatch);
1495 g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
1504 * Returns the depth of the stack of calls to
1505 * g_main_context_dispatch() on any #GMainContext in the current thread.
1506 * That is, when called from the toplevel, it gives 0. When
1507 * called from within a callback from g_main_context_iteration()
1508 * (or g_main_loop_run(), etc.) it returns 1. When called from within
1509 * a callback to a recursive call to g_main_context_iterate(),
1510 * it returns 2. And so forth.
1512 * This function is useful in a situation like the following:
1513 * Imagine an extremely simple "garbage collected" system.
1516 * static GList *free_list;
1519 * allocate_memory (gsize size)
1521 * gpointer result = g_malloc (size);
1522 * free_list = g_list_prepend (free_list, result);
1527 * free_allocated_memory (void)
1530 * for (l = free_list; l; l = l->next);
1532 * g_list_free (free_list);
1540 * g_main_context_iteration (NULL, TRUE);
1541 * free_allocated_memory();
1545 * This works from an application, however, if you want to do the same
1546 * thing from a library, it gets more difficult, since you no longer
1547 * control the main loop. You might think you can simply use an idle
1548 * function to make the call to free_allocated_memory(), but that
1549 * doesn't work, since the idle function could be called from a
1550 * recursive callback. This can be fixed by using g_main_depth()
1554 * allocate_memory (gsize size)
1556 * FreeListBlock *block = g_new (FreeListBlock, 1);
1557 * block->mem = g_malloc (size);
1558 * block->depth = g_main_depth ();
1559 * free_list = g_list_prepend (free_list, block);
1560 * return block->mem;
1564 * free_allocated_memory (void)
1568 * int depth = g_main_depth ();
1569 * for (l = free_list; l; );
1571 * GList *next = l->next;
1572 * FreeListBlock *block = l->data;
1573 * if (block->depth > depth)
1575 * g_free (block->mem);
1577 * free_list = g_list_delete_link (free_list, l);
1585 * There is a temptation to use g_main_depth() to solve
1586 * problems with reentrancy. For instance, while waiting for data
1587 * to be received from the network in response to a menu item,
1588 * the menu item might be selected again. It might seem that
1589 * one could make the menu item's callback return immediately
1590 * and do nothing if g_main_depth() returns a value greater than 1.
1591 * However, this should be avoided since the user then sees selecting
1592 * the menu item do nothing. Furthermore, you'll find yourself adding
1593 * these checks all over your code, since there are doubtless many,
1594 * many things that the user could do. Instead, you can use the
1595 * following techniques:
1600 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
1601 * the user from interacting with elements while the main
1602 * loop is recursing.
1607 * Avoid main loop recursion in situations where you can't handle
1608 * arbitrary callbacks. Instead, structure your code so that you
1609 * simply return to the main loop and then get called again when
1610 * there is more work to do.
1615 * Return value: The main loop recursion level in the current thread
1620 GMainDispatch *dispatch = get_dispatch ();
1621 return dispatch->depth;
1625 * g_main_current_source:
1627 * Returns the currently firing source for this thread.
1629 * Return value: The currently firing source or %NULL.
1634 g_main_current_source (void)
1636 GMainDispatch *dispatch = get_dispatch ();
1637 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
1641 * g_source_is_destroyed:
1642 * @source: a #GSource
1644 * Returns whether @source has been destroyed.
1646 * This is important when you operate upon your objects
1647 * from within idle handlers, but may have freed the object
1648 * before the dispatch of your idle handler.
1652 * idle_callback (gpointer data)
1654 * SomeWidget *self = data;
1656 * GDK_THREADS_ENTER (<!-- -->);
1657 * /<!-- -->* do stuff with self *<!-- -->/
1658 * self->idle_id = 0;
1659 * GDK_THREADS_LEAVE (<!-- -->);
1665 * some_widget_do_stuff_later (SomeWidget *self)
1667 * self->idle_id = g_idle_add (idle_callback, self);
1671 * some_widget_finalize (GObject *object)
1673 * SomeWidget *self = SOME_WIDGET (object);
1675 * if (self->idle_id)
1676 * g_source_remove (self->idle_id);
1678 * G_OBJECT_CLASS (parent_class)->finalize (object);
1682 * This will fail in a multi-threaded application if the
1683 * widget is destroyed before the idle handler fires due
1684 * to the use after free in the callback. A solution, to
1685 * this particular problem, is to check to if the source
1686 * has already been destroy within the callback.
1690 * idle_callback (gpointer data)
1692 * SomeWidget *self = data;
1694 * GDK_THREADS_ENTER ();
1695 * if (!g_source_is_destroyed (g_main_current_source ()))
1697 * /<!-- -->* do stuff with self *<!-- -->/
1699 * GDK_THREADS_LEAVE ();
1705 * Return value: %TRUE if the source has been destroyed
1710 g_source_is_destroyed (GSource *source)
1712 return SOURCE_DESTROYED (source);
1716 /* Temporarily remove all this source's file descriptors from the
1717 * poll(), so that if data comes available for one of the file descriptors
1718 * we don't continually spin in the poll()
1720 /* HOLDS: source->context's lock */
1722 block_source (GSource *source)
1726 g_return_if_fail (!SOURCE_BLOCKED (source));
1728 tmp_list = source->poll_fds;
1731 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
1732 tmp_list = tmp_list->next;
1736 /* HOLDS: source->context's lock */
1738 unblock_source (GSource *source)
1742 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
1743 g_return_if_fail (!SOURCE_DESTROYED (source));
1745 tmp_list = source->poll_fds;
1748 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
1749 tmp_list = tmp_list->next;
1753 /* HOLDS: context's lock */
1755 g_main_dispatch (GMainContext *context)
1757 GMainDispatch *current = get_dispatch ();
1760 for (i = 0; i < context->pending_dispatches->len; i++)
1762 GSource *source = context->pending_dispatches->pdata[i];
1764 context->pending_dispatches->pdata[i] = NULL;
1767 source->flags &= ~G_SOURCE_READY;
1769 if (!SOURCE_DESTROYED (source))
1771 gboolean was_in_call;
1772 gpointer user_data = NULL;
1773 GSourceFunc callback = NULL;
1774 GSourceCallbackFuncs *cb_funcs;
1776 gboolean need_destroy;
1778 gboolean (*dispatch) (GSource *,
1781 GSList current_source_link;
1783 dispatch = source->source_funcs->dispatch;
1784 cb_funcs = source->callback_funcs;
1785 cb_data = source->callback_data;
1788 cb_funcs->ref (cb_data);
1790 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
1791 block_source (source);
1793 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
1794 source->flags |= G_HOOK_FLAG_IN_CALL;
1797 cb_funcs->get (cb_data, source, &callback, &user_data);
1799 UNLOCK_CONTEXT (context);
1802 /* The on-stack allocation of the GSList is unconventional, but
1803 * we know that the lifetime of the link is bounded to this
1804 * function as the link is kept in a thread specific list and
1805 * not manipulated outside of this function and its descendants.
1806 * Avoiding the overhead of a g_slist_alloc() is useful as many
1807 * applications do little more than dispatch events.
1809 * This is a performance hack - do not revert to g_slist_prepend()!
1811 current_source_link.data = source;
1812 current_source_link.next = current->dispatching_sources;
1813 current->dispatching_sources = ¤t_source_link;
1814 need_destroy = ! dispatch (source,
1817 g_assert (current->dispatching_sources == ¤t_source_link);
1818 current->dispatching_sources = current_source_link.next;
1822 cb_funcs->unref (cb_data);
1824 LOCK_CONTEXT (context);
1827 source->flags &= ~G_HOOK_FLAG_IN_CALL;
1829 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
1830 !SOURCE_DESTROYED (source))
1831 unblock_source (source);
1833 /* Note: this depends on the fact that we can't switch
1834 * sources from one main context to another
1836 if (need_destroy && !SOURCE_DESTROYED (source))
1838 g_assert (source->context == context);
1839 g_source_destroy_internal (source, context, TRUE);
1843 SOURCE_UNREF (source, context);
1846 g_ptr_array_set_size (context->pending_dispatches, 0);
1849 /* Holds context's lock */
1850 static inline GSource *
1851 next_valid_source (GMainContext *context,
1854 GSource *new_source = source ? source->next : context->source_list;
1858 if (!SOURCE_DESTROYED (new_source))
1860 new_source->ref_count++;
1864 new_source = new_source->next;
1868 SOURCE_UNREF (source, context);
1874 * g_main_context_acquire:
1875 * @context: a #GMainContext
1877 * Tries to become the owner of the specified context.
1878 * If some other thread is the owner of the context,
1879 * returns %FALSE immediately. Ownership is properly
1880 * recursive: the owner can require ownership again
1881 * and will release ownership when g_main_context_release()
1882 * is called as many times as g_main_context_acquire().
1884 * You must be the owner of a context before you
1885 * can call g_main_context_prepare(), g_main_context_query(),
1886 * g_main_context_check(), g_main_context_dispatch().
1888 * Return value: %TRUE if the operation succeeded, and
1889 * this thread is now the owner of @context.
1892 g_main_context_acquire (GMainContext *context)
1894 #ifdef G_THREADS_ENABLED
1895 gboolean result = FALSE;
1896 GThread *self = G_THREAD_SELF;
1898 if (context == NULL)
1899 context = g_main_context_default ();
1901 LOCK_CONTEXT (context);
1903 if (!context->owner)
1905 context->owner = self;
1906 g_assert (context->owner_count == 0);
1909 if (context->owner == self)
1911 context->owner_count++;
1915 UNLOCK_CONTEXT (context);
1918 #else /* !G_THREADS_ENABLED */
1920 #endif /* G_THREADS_ENABLED */
1924 * g_main_context_release:
1925 * @context: a #GMainContext
1927 * Releases ownership of a context previously acquired by this thread
1928 * with g_main_context_acquire(). If the context was acquired multiple
1929 * times, the ownership will be released only when g_main_context_release()
1930 * is called as many times as it was acquired.
1933 g_main_context_release (GMainContext *context)
1935 #ifdef G_THREADS_ENABLED
1936 if (context == NULL)
1937 context = g_main_context_default ();
1939 LOCK_CONTEXT (context);
1941 context->owner_count--;
1942 if (context->owner_count == 0)
1944 context->owner = NULL;
1946 if (context->waiters)
1948 GMainWaiter *waiter = context->waiters->data;
1949 gboolean loop_internal_waiter =
1950 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
1951 context->waiters = g_slist_delete_link (context->waiters,
1953 if (!loop_internal_waiter)
1954 g_mutex_lock (waiter->mutex);
1956 g_cond_signal (waiter->cond);
1958 if (!loop_internal_waiter)
1959 g_mutex_unlock (waiter->mutex);
1963 UNLOCK_CONTEXT (context);
1964 #endif /* G_THREADS_ENABLED */
1968 * g_main_context_wait:
1969 * @context: a #GMainContext
1970 * @cond: a condition variable
1971 * @mutex: a mutex, currently held
1973 * Tries to become the owner of the specified context,
1974 * as with g_main_context_acquire(). But if another thread
1975 * is the owner, atomically drop @mutex and wait on @cond until
1976 * that owner releases ownership or until @cond is signaled, then
1977 * try again (once) to become the owner.
1979 * Return value: %TRUE if the operation succeeded, and
1980 * this thread is now the owner of @context.
1983 g_main_context_wait (GMainContext *context,
1987 #ifdef G_THREADS_ENABLED
1988 gboolean result = FALSE;
1989 GThread *self = G_THREAD_SELF;
1990 gboolean loop_internal_waiter;
1992 if (context == NULL)
1993 context = g_main_context_default ();
1995 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
1997 if (!loop_internal_waiter)
1998 LOCK_CONTEXT (context);
2000 if (context->owner && context->owner != self)
2005 waiter.mutex = mutex;
2007 context->waiters = g_slist_append (context->waiters, &waiter);
2009 if (!loop_internal_waiter)
2010 UNLOCK_CONTEXT (context);
2011 g_cond_wait (cond, mutex);
2012 if (!loop_internal_waiter)
2013 LOCK_CONTEXT (context);
2015 context->waiters = g_slist_remove (context->waiters, &waiter);
2018 if (!context->owner)
2020 context->owner = self;
2021 g_assert (context->owner_count == 0);
2024 if (context->owner == self)
2026 context->owner_count++;
2030 if (!loop_internal_waiter)
2031 UNLOCK_CONTEXT (context);
2034 #else /* !G_THREADS_ENABLED */
2036 #endif /* G_THREADS_ENABLED */
2040 * g_main_context_prepare:
2041 * @context: a #GMainContext
2042 * @priority: location to store priority of highest priority
2043 * source already ready.
2045 * Prepares to poll sources within a main loop. The resulting information
2046 * for polling is determined by calling g_main_context_query ().
2048 * Return value: %TRUE if some source is ready to be dispatched
2052 g_main_context_prepare (GMainContext *context,
2057 gint current_priority = G_MAXINT;
2060 if (context == NULL)
2061 context = g_main_context_default ();
2063 LOCK_CONTEXT (context);
2065 context->time_is_current = FALSE;
2067 if (context->in_check_or_prepare)
2069 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2070 "prepare() member.");
2071 UNLOCK_CONTEXT (context);
2075 #ifdef G_THREADS_ENABLED
2076 if (context->poll_waiting)
2078 g_warning("g_main_context_prepare(): main loop already active in another thread");
2079 UNLOCK_CONTEXT (context);
2083 context->poll_waiting = TRUE;
2084 #endif /* G_THREADS_ENABLED */
2087 /* If recursing, finish up current dispatch, before starting over */
2088 if (context->pending_dispatches)
2091 g_main_dispatch (context, ¤t_time);
2093 UNLOCK_CONTEXT (context);
2098 /* If recursing, clear list of pending dispatches */
2100 for (i = 0; i < context->pending_dispatches->len; i++)
2102 if (context->pending_dispatches->pdata[i])
2103 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2105 g_ptr_array_set_size (context->pending_dispatches, 0);
2107 /* Prepare all sources */
2109 context->timeout = -1;
2111 source = next_valid_source (context, NULL);
2114 gint source_timeout = -1;
2116 if ((n_ready > 0) && (source->priority > current_priority))
2118 SOURCE_UNREF (source, context);
2121 if (SOURCE_BLOCKED (source))
2124 if (!(source->flags & G_SOURCE_READY))
2127 gboolean (*prepare) (GSource *source,
2130 prepare = source->source_funcs->prepare;
2131 context->in_check_or_prepare++;
2132 UNLOCK_CONTEXT (context);
2134 result = (*prepare) (source, &source_timeout);
2136 LOCK_CONTEXT (context);
2137 context->in_check_or_prepare--;
2140 source->flags |= G_SOURCE_READY;
2143 if (source->flags & G_SOURCE_READY)
2146 current_priority = source->priority;
2147 context->timeout = 0;
2150 if (source_timeout >= 0)
2152 if (context->timeout < 0)
2153 context->timeout = source_timeout;
2155 context->timeout = MIN (context->timeout, source_timeout);
2159 source = next_valid_source (context, source);
2162 UNLOCK_CONTEXT (context);
2165 *priority = current_priority;
2167 return (n_ready > 0);
2171 * g_main_context_query:
2172 * @context: a #GMainContext
2173 * @max_priority: maximum priority source to check
2174 * @timeout_: location to store timeout to be used in polling
2175 * @fds: location to store #GPollFD records that need to be polled.
2176 * @n_fds: length of @fds.
2178 * Determines information necessary to poll this main loop.
2180 * Return value: the number of records actually stored in @fds,
2181 * or, if more than @n_fds records need to be stored, the number
2182 * of records that need to be stored.
2185 g_main_context_query (GMainContext *context,
2194 LOCK_CONTEXT (context);
2196 pollrec = context->poll_records;
2198 while (pollrec && max_priority >= pollrec->priority)
2200 /* We need to include entries with fd->events == 0 in the array because
2201 * otherwise if the application changes fd->events behind our back and
2202 * makes it non-zero, we'll be out of sync when we check the fds[] array.
2203 * (Changing fd->events after adding an FD wasn't an anticipated use of
2204 * this API, but it occurs in practice.) */
2207 fds[n_poll].fd = pollrec->fd->fd;
2208 /* In direct contradiction to the Unix98 spec, IRIX runs into
2209 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2210 * flags in the events field of the pollfd while it should
2211 * just ignoring them. So we mask them out here.
2213 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2214 fds[n_poll].revents = 0;
2217 pollrec = pollrec->next;
2221 #ifdef G_THREADS_ENABLED
2222 context->poll_changed = FALSE;
2227 *timeout = context->timeout;
2229 context->time_is_current = FALSE;
2232 UNLOCK_CONTEXT (context);
2238 * g_main_context_check:
2239 * @context: a #GMainContext
2240 * @max_priority: the maximum numerical priority of sources to check
2241 * @fds: array of #GPollFD's that was passed to the last call to
2242 * g_main_context_query()
2243 * @n_fds: return value of g_main_context_query()
2245 * Passes the results of polling back to the main loop.
2247 * Return value: %TRUE if some sources are ready to be dispatched.
2250 g_main_context_check (GMainContext *context,
2260 LOCK_CONTEXT (context);
2262 if (context->in_check_or_prepare)
2264 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2265 "prepare() member.");
2266 UNLOCK_CONTEXT (context);
2270 #ifdef G_THREADS_ENABLED
2271 if (!context->poll_waiting)
2275 read (context->wake_up_pipe[0], &a, 1);
2279 context->poll_waiting = FALSE;
2281 /* If the set of poll file descriptors changed, bail out
2282 * and let the main loop rerun
2284 if (context->poll_changed)
2286 UNLOCK_CONTEXT (context);
2289 #endif /* G_THREADS_ENABLED */
2291 pollrec = context->poll_records;
2295 if (pollrec->fd->events)
2296 pollrec->fd->revents = fds[i].revents;
2298 pollrec = pollrec->next;
2302 source = next_valid_source (context, NULL);
2305 if ((n_ready > 0) && (source->priority > max_priority))
2307 SOURCE_UNREF (source, context);
2310 if (SOURCE_BLOCKED (source))
2313 if (!(source->flags & G_SOURCE_READY))
2316 gboolean (*check) (GSource *source);
2318 check = source->source_funcs->check;
2320 context->in_check_or_prepare++;
2321 UNLOCK_CONTEXT (context);
2323 result = (*check) (source);
2325 LOCK_CONTEXT (context);
2326 context->in_check_or_prepare--;
2329 source->flags |= G_SOURCE_READY;
2332 if (source->flags & G_SOURCE_READY)
2334 source->ref_count++;
2335 g_ptr_array_add (context->pending_dispatches, source);
2339 /* never dispatch sources with less priority than the first
2340 * one we choose to dispatch
2342 max_priority = source->priority;
2346 source = next_valid_source (context, source);
2349 UNLOCK_CONTEXT (context);
2355 * g_main_context_dispatch:
2356 * @context: a #GMainContext
2358 * Dispatches all pending sources.
2361 g_main_context_dispatch (GMainContext *context)
2363 LOCK_CONTEXT (context);
2365 if (context->pending_dispatches->len > 0)
2367 g_main_dispatch (context);
2370 UNLOCK_CONTEXT (context);
2373 /* HOLDS context lock */
2375 g_main_context_iterate (GMainContext *context,
2382 gboolean some_ready;
2383 gint nfds, allocated_nfds;
2384 GPollFD *fds = NULL;
2386 UNLOCK_CONTEXT (context);
2388 #ifdef G_THREADS_ENABLED
2389 if (!g_main_context_acquire (context))
2391 gboolean got_ownership;
2393 g_return_val_if_fail (g_thread_supported (), FALSE);
2398 LOCK_CONTEXT (context);
2401 context->cond = g_cond_new ();
2403 got_ownership = g_main_context_wait (context,
2405 g_static_mutex_get_mutex (&context->mutex));
2409 UNLOCK_CONTEXT (context);
2414 LOCK_CONTEXT (context);
2415 #endif /* G_THREADS_ENABLED */
2417 if (!context->cached_poll_array)
2419 context->cached_poll_array_size = context->n_poll_records;
2420 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2423 allocated_nfds = context->cached_poll_array_size;
2424 fds = context->cached_poll_array;
2426 UNLOCK_CONTEXT (context);
2428 g_main_context_prepare (context, &max_priority);
2430 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
2431 allocated_nfds)) > allocated_nfds)
2433 LOCK_CONTEXT (context);
2435 context->cached_poll_array_size = allocated_nfds = nfds;
2436 context->cached_poll_array = fds = g_new (GPollFD, nfds);
2437 UNLOCK_CONTEXT (context);
2443 g_main_context_poll (context, timeout, max_priority, fds, nfds);
2445 some_ready = g_main_context_check (context, max_priority, fds, nfds);
2448 g_main_context_dispatch (context);
2450 #ifdef G_THREADS_ENABLED
2451 g_main_context_release (context);
2452 #endif /* G_THREADS_ENABLED */
2454 LOCK_CONTEXT (context);
2460 * g_main_context_pending:
2461 * @context: a #GMainContext (if %NULL, the default context will be used)
2463 * Checks if any sources have pending events for the given context.
2465 * Return value: %TRUE if events are pending.
2468 g_main_context_pending (GMainContext *context)
2473 context = g_main_context_default();
2475 LOCK_CONTEXT (context);
2476 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
2477 UNLOCK_CONTEXT (context);
2483 * g_main_context_iteration:
2484 * @context: a #GMainContext (if %NULL, the default context will be used)
2485 * @may_block: whether the call may block.
2487 * Runs a single iteration for the given main loop. This involves
2488 * checking to see if any event sources are ready to be processed,
2489 * then if no events sources are ready and @may_block is %TRUE, waiting
2490 * for a source to become ready, then dispatching the highest priority
2491 * events sources that are ready. Otherwise, if @may_block is %FALSE
2492 * sources are not waited to become ready, only those highest priority
2493 * events sources will be dispatched (if any), that are ready at this
2494 * given moment without further waiting.
2496 * Note that even when @may_block is %TRUE, it is still possible for
2497 * g_main_context_iteration() to return %FALSE, since the the wait may
2498 * be interrupted for other reasons than an event source becoming ready.
2500 * Return value: %TRUE if events were dispatched.
2503 g_main_context_iteration (GMainContext *context, gboolean may_block)
2508 context = g_main_context_default();
2510 LOCK_CONTEXT (context);
2511 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
2512 UNLOCK_CONTEXT (context);
2519 * @context: a #GMainContext (if %NULL, the default context will be used).
2520 * @is_running: set to %TRUE to indicate that the loop is running. This
2521 * is not very important since calling g_main_loop_run() will set this to
2524 * Creates a new #GMainLoop structure.
2526 * Return value: a new #GMainLoop.
2529 g_main_loop_new (GMainContext *context,
2530 gboolean is_running)
2535 context = g_main_context_default();
2537 g_main_context_ref (context);
2539 loop = g_new0 (GMainLoop, 1);
2540 loop->context = context;
2541 loop->is_running = is_running != FALSE;
2542 loop->ref_count = 1;
2549 * @loop: a #GMainLoop
2551 * Increases the reference count on a #GMainLoop object by one.
2553 * Return value: @loop
2556 g_main_loop_ref (GMainLoop *loop)
2558 g_return_val_if_fail (loop != NULL, NULL);
2559 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2561 g_atomic_int_inc (&loop->ref_count);
2567 * g_main_loop_unref:
2568 * @loop: a #GMainLoop
2570 * Decreases the reference count on a #GMainLoop object by one. If
2571 * the result is zero, free the loop and free all associated memory.
2574 g_main_loop_unref (GMainLoop *loop)
2576 g_return_if_fail (loop != NULL);
2577 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2579 if (!g_atomic_int_dec_and_test (&loop->ref_count))
2582 g_main_context_unref (loop->context);
2588 * @loop: a #GMainLoop
2590 * Runs a main loop until g_main_loop_quit() is called on the loop.
2591 * If this is called for the thread of the loop's #GMainContext,
2592 * it will process events from the loop, otherwise it will
2596 g_main_loop_run (GMainLoop *loop)
2598 GThread *self = G_THREAD_SELF;
2600 g_return_if_fail (loop != NULL);
2601 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2603 #ifdef G_THREADS_ENABLED
2604 if (!g_main_context_acquire (loop->context))
2606 gboolean got_ownership = FALSE;
2608 /* Another thread owns this context */
2609 if (!g_thread_supported ())
2611 g_warning ("g_main_loop_run() was called from second thread but "
2612 "g_thread_init() was never called.");
2616 LOCK_CONTEXT (loop->context);
2618 g_atomic_int_inc (&loop->ref_count);
2620 if (!loop->is_running)
2621 loop->is_running = TRUE;
2623 if (!loop->context->cond)
2624 loop->context->cond = g_cond_new ();
2626 while (loop->is_running && !got_ownership)
2627 got_ownership = g_main_context_wait (loop->context,
2628 loop->context->cond,
2629 g_static_mutex_get_mutex (&loop->context->mutex));
2631 if (!loop->is_running)
2633 UNLOCK_CONTEXT (loop->context);
2635 g_main_context_release (loop->context);
2636 g_main_loop_unref (loop);
2640 g_assert (got_ownership);
2643 LOCK_CONTEXT (loop->context);
2644 #endif /* G_THREADS_ENABLED */
2646 if (loop->context->in_check_or_prepare)
2648 g_warning ("g_main_loop_run(): called recursively from within a source's "
2649 "check() or prepare() member, iteration not possible.");
2653 g_atomic_int_inc (&loop->ref_count);
2654 loop->is_running = TRUE;
2655 while (loop->is_running)
2656 g_main_context_iterate (loop->context, TRUE, TRUE, self);
2658 UNLOCK_CONTEXT (loop->context);
2660 #ifdef G_THREADS_ENABLED
2661 g_main_context_release (loop->context);
2662 #endif /* G_THREADS_ENABLED */
2664 g_main_loop_unref (loop);
2669 * @loop: a #GMainLoop
2671 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
2672 * for the loop will return.
2674 * Note that sources that have already been dispatched when
2675 * g_main_loop_quit() is called will still be executed.
2678 g_main_loop_quit (GMainLoop *loop)
2680 g_return_if_fail (loop != NULL);
2681 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2683 LOCK_CONTEXT (loop->context);
2684 loop->is_running = FALSE;
2685 g_main_context_wakeup_unlocked (loop->context);
2687 #ifdef G_THREADS_ENABLED
2688 if (loop->context->cond)
2689 g_cond_broadcast (loop->context->cond);
2690 #endif /* G_THREADS_ENABLED */
2692 UNLOCK_CONTEXT (loop->context);
2696 * g_main_loop_is_running:
2697 * @loop: a #GMainLoop.
2699 * Checks to see if the main loop is currently being run via g_main_loop_run().
2701 * Return value: %TRUE if the mainloop is currently being run.
2704 g_main_loop_is_running (GMainLoop *loop)
2706 g_return_val_if_fail (loop != NULL, FALSE);
2707 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
2709 return loop->is_running;
2713 * g_main_loop_get_context:
2714 * @loop: a #GMainLoop.
2716 * Returns the #GMainContext of @loop.
2718 * Return value: the #GMainContext of @loop
2721 g_main_loop_get_context (GMainLoop *loop)
2723 g_return_val_if_fail (loop != NULL, NULL);
2724 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2726 return loop->context;
2729 /* HOLDS: context's lock */
2731 g_main_context_poll (GMainContext *context,
2737 #ifdef G_MAIN_POLL_DEBUG
2743 GPollFunc poll_func;
2745 if (n_fds || timeout != 0)
2747 #ifdef G_MAIN_POLL_DEBUG
2748 if (_g_main_poll_debug)
2750 g_print ("polling context=%p n=%d timeout=%d\n",
2751 context, n_fds, timeout);
2752 poll_timer = g_timer_new ();
2756 LOCK_CONTEXT (context);
2758 poll_func = context->poll_func;
2760 UNLOCK_CONTEXT (context);
2761 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
2764 g_warning ("poll(2) failed due to: %s.",
2765 g_strerror (errno));
2767 /* If g_poll () returns -1, it has already called g_warning() */
2771 #ifdef G_MAIN_POLL_DEBUG
2772 if (_g_main_poll_debug)
2774 LOCK_CONTEXT (context);
2776 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
2779 g_timer_elapsed (poll_timer, NULL));
2780 g_timer_destroy (poll_timer);
2781 pollrec = context->poll_records;
2783 while (pollrec != NULL)
2788 if (fds[i].fd == pollrec->fd->fd &&
2789 pollrec->fd->events &&
2792 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
2793 if (fds[i].revents & G_IO_IN)
2795 if (fds[i].revents & G_IO_OUT)
2797 if (fds[i].revents & G_IO_PRI)
2799 if (fds[i].revents & G_IO_ERR)
2801 if (fds[i].revents & G_IO_HUP)
2803 if (fds[i].revents & G_IO_NVAL)
2809 pollrec = pollrec->next;
2813 UNLOCK_CONTEXT (context);
2816 } /* if (n_fds || timeout != 0) */
2820 * g_main_context_add_poll:
2821 * @context: a #GMainContext (or %NULL for the default context)
2822 * @fd: a #GPollFD structure holding information about a file
2823 * descriptor to watch.
2824 * @priority: the priority for this file descriptor which should be
2825 * the same as the priority used for g_source_attach() to ensure that the
2826 * file descriptor is polled whenever the results may be needed.
2828 * Adds a file descriptor to the set of file descriptors polled for
2829 * this context. This will very seldomly be used directly. Instead
2830 * a typical event source will use g_source_add_poll() instead.
2833 g_main_context_add_poll (GMainContext *context,
2838 context = g_main_context_default ();
2840 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
2841 g_return_if_fail (fd);
2843 LOCK_CONTEXT (context);
2844 g_main_context_add_poll_unlocked (context, priority, fd);
2845 UNLOCK_CONTEXT (context);
2848 /* HOLDS: main_loop_lock */
2850 g_main_context_add_poll_unlocked (GMainContext *context,
2854 GPollRec *lastrec, *pollrec;
2855 GPollRec *newrec = g_slice_new (GPollRec);
2857 /* This file descriptor may be checked before we ever poll */
2860 newrec->priority = priority;
2863 pollrec = context->poll_records;
2864 while (pollrec && priority >= pollrec->priority)
2867 pollrec = pollrec->next;
2871 lastrec->next = newrec;
2873 context->poll_records = newrec;
2875 newrec->next = pollrec;
2877 context->n_poll_records++;
2879 #ifdef G_THREADS_ENABLED
2880 context->poll_changed = TRUE;
2882 /* Now wake up the main loop if it is waiting in the poll() */
2883 g_main_context_wakeup_unlocked (context);
2888 * g_main_context_remove_poll:
2889 * @context:a #GMainContext
2890 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
2892 * Removes file descriptor from the set of file descriptors to be
2893 * polled for a particular context.
2896 g_main_context_remove_poll (GMainContext *context,
2900 context = g_main_context_default ();
2902 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
2903 g_return_if_fail (fd);
2905 LOCK_CONTEXT (context);
2906 g_main_context_remove_poll_unlocked (context, fd);
2907 UNLOCK_CONTEXT (context);
2911 g_main_context_remove_poll_unlocked (GMainContext *context,
2914 GPollRec *pollrec, *lastrec;
2917 pollrec = context->poll_records;
2921 if (pollrec->fd == fd)
2923 if (lastrec != NULL)
2924 lastrec->next = pollrec->next;
2926 context->poll_records = pollrec->next;
2928 g_slice_free (GPollRec, pollrec);
2930 context->n_poll_records--;
2934 pollrec = pollrec->next;
2937 #ifdef G_THREADS_ENABLED
2938 context->poll_changed = TRUE;
2940 /* Now wake up the main loop if it is waiting in the poll() */
2941 g_main_context_wakeup_unlocked (context);
2946 * g_source_get_current_time:
2947 * @source: a #GSource
2948 * @timeval: #GTimeVal structure in which to store current time.
2950 * Gets the "current time" to be used when checking
2951 * this source. The advantage of calling this function over
2952 * calling g_get_current_time() directly is that when
2953 * checking multiple sources, GLib can cache a single value
2954 * instead of having to repeatedly get the system time.
2957 g_source_get_current_time (GSource *source,
2960 GMainContext *context;
2962 g_return_if_fail (source->context != NULL);
2964 context = source->context;
2966 LOCK_CONTEXT (context);
2968 if (!context->time_is_current)
2970 g_get_current_time (&context->current_time);
2971 context->time_is_current = TRUE;
2974 *timeval = context->current_time;
2976 UNLOCK_CONTEXT (context);
2980 * g_main_context_set_poll_func:
2981 * @context: a #GMainContext
2982 * @func: the function to call to poll all file descriptors
2984 * Sets the function to use to handle polling of file descriptors. It
2985 * will be used instead of the poll() system call
2986 * (or GLib's replacement function, which is used where
2987 * poll() isn't available).
2989 * This function could possibly be used to integrate the GLib event
2990 * loop with an external event loop.
2993 g_main_context_set_poll_func (GMainContext *context,
2997 context = g_main_context_default ();
2999 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3001 LOCK_CONTEXT (context);
3004 context->poll_func = func;
3006 context->poll_func = g_poll;
3008 UNLOCK_CONTEXT (context);
3012 * g_main_context_get_poll_func:
3013 * @context: a #GMainContext
3015 * Gets the poll function set by g_main_context_set_poll_func().
3017 * Return value: the poll function
3020 g_main_context_get_poll_func (GMainContext *context)
3025 context = g_main_context_default ();
3027 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3029 LOCK_CONTEXT (context);
3030 result = context->poll_func;
3031 UNLOCK_CONTEXT (context);
3036 /* HOLDS: context's lock */
3037 /* Wake the main loop up from a poll() */
3039 g_main_context_wakeup_unlocked (GMainContext *context)
3041 #ifdef G_THREADS_ENABLED
3042 if (g_thread_supported() && context->poll_waiting)
3044 context->poll_waiting = FALSE;
3046 write (context->wake_up_pipe[1], "A", 1);
3048 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
3055 * g_main_context_wakeup:
3056 * @context: a #GMainContext
3058 * If @context is currently waiting in a poll(), interrupt
3059 * the poll(), and continue the iteration process.
3062 g_main_context_wakeup (GMainContext *context)
3065 context = g_main_context_default ();
3067 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3069 LOCK_CONTEXT (context);
3070 g_main_context_wakeup_unlocked (context);
3071 UNLOCK_CONTEXT (context);
3075 * g_main_context_is_owner:
3076 * @context: a #GMainContext
3078 * Determines whether this thread holds the (recursive)
3079 * ownership of this #GMaincontext. This is useful to
3080 * know before waiting on another thread that may be
3081 * blocking to get ownership of @context.
3083 * Returns: %TRUE if current thread is owner of @context.
3088 g_main_context_is_owner (GMainContext *context)
3093 context = g_main_context_default ();
3095 #ifdef G_THREADS_ENABLED
3096 LOCK_CONTEXT (context);
3097 is_owner = context->owner == G_THREAD_SELF;
3098 UNLOCK_CONTEXT (context);
3109 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3110 GTimeVal *current_time)
3112 guint seconds = timeout_source->interval / 1000;
3113 guint msecs = timeout_source->interval - seconds * 1000;
3115 timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
3116 timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
3117 if (timeout_source->expiration.tv_usec >= 1000000)
3119 timeout_source->expiration.tv_usec -= 1000000;
3120 timeout_source->expiration.tv_sec++;
3122 if (timer_perturb==-1)
3125 * we want a per machine/session unique 'random' value; try the dbus
3126 * address first, that has a UUID in it. If there is no dbus, use the
3127 * hostname for hashing.
3129 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3130 if (!session_bus_address)
3131 session_bus_address = g_getenv ("HOSTNAME");
3132 if (session_bus_address)
3133 timer_perturb = ABS ((gint) g_str_hash (session_bus_address));
3137 if (timeout_source->granularity)
3140 gint gran; /* in usecs */
3143 gran = timeout_source->granularity * 1000;
3144 perturb = timer_perturb % gran;
3146 * We want to give each machine a per machine pertubation;
3147 * shift time back first, and forward later after the rounding
3150 timeout_source->expiration.tv_usec -= perturb;
3151 if (timeout_source->expiration.tv_usec < 0)
3153 timeout_source->expiration.tv_usec += 1000000;
3154 timeout_source->expiration.tv_sec--;
3157 remainder = timeout_source->expiration.tv_usec % gran;
3158 if (remainder >= gran/4) /* round up */
3159 timeout_source->expiration.tv_usec += gran;
3160 timeout_source->expiration.tv_usec -= remainder;
3162 timeout_source->expiration.tv_usec += perturb;
3164 /* the rounding may have overflown tv_usec */
3165 while (timeout_source->expiration.tv_usec > 1000000)
3167 timeout_source->expiration.tv_usec -= 1000000;
3168 timeout_source->expiration.tv_sec++;
3174 g_timeout_prepare (GSource *source,
3179 GTimeVal current_time;
3181 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3183 g_source_get_current_time (source, ¤t_time);
3185 sec = timeout_source->expiration.tv_sec - current_time.tv_sec;
3186 msec = (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000;
3188 /* We do the following in a rather convoluted fashion to deal with
3189 * the fact that we don't have an integral type big enough to hold
3190 * the difference of two timevals in millseconds.
3192 if (sec < 0 || (sec == 0 && msec < 0))
3196 glong interval_sec = timeout_source->interval / 1000;
3197 glong interval_msec = timeout_source->interval % 1000;
3205 if (sec > interval_sec ||
3206 (sec == interval_sec && msec > interval_msec))
3208 /* The system time has been set backwards, so we
3209 * reset the expiration time to now + timeout_source->interval;
3210 * this at least avoids hanging for long periods of time.
3212 g_timeout_set_expiration (timeout_source, ¤t_time);
3213 msec = MIN (G_MAXINT, timeout_source->interval);
3217 msec = MIN (G_MAXINT, (guint)msec + 1000 * (guint)sec);
3221 *timeout = (gint)msec;
3227 g_timeout_check (GSource *source)
3229 GTimeVal current_time;
3230 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3232 g_source_get_current_time (source, ¤t_time);
3234 return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
3235 ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
3236 (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
3240 g_timeout_dispatch (GSource *source,
3241 GSourceFunc callback,
3244 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3248 g_warning ("Timeout source dispatched without callback\n"
3249 "You must call g_source_set_callback().");
3253 if (callback (user_data))
3255 GTimeVal current_time;
3257 g_source_get_current_time (source, ¤t_time);
3258 g_timeout_set_expiration (timeout_source, ¤t_time);
3267 * g_timeout_source_new:
3268 * @interval: the timeout interval in milliseconds.
3270 * Creates a new timeout source.
3272 * The source will not initially be associated with any #GMainContext
3273 * and must be added to one with g_source_attach() before it will be
3276 * Return value: the newly-created timeout source
3279 g_timeout_source_new (guint interval)
3281 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3282 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3283 GTimeVal current_time;
3285 timeout_source->interval = interval;
3287 g_get_current_time (¤t_time);
3288 g_timeout_set_expiration (timeout_source, ¤t_time);
3294 * g_timeout_source_new_seconds:
3295 * @interval: the timeout interval in seconds
3297 * Creates a new timeout source.
3299 * The source will not initially be associated with any #GMainContext
3300 * and must be added to one with g_source_attach() before it will be
3303 * The scheduling granularity/accuracy of this timeout source will be
3306 * Return value: the newly-created timeout source
3311 g_timeout_source_new_seconds (guint interval)
3313 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3314 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3315 GTimeVal current_time;
3317 timeout_source->interval = 1000*interval;
3318 timeout_source->granularity = 1000;
3320 g_get_current_time (¤t_time);
3321 g_timeout_set_expiration (timeout_source, ¤t_time);
3328 * g_timeout_add_full:
3329 * @priority: the priority of the timeout source. Typically this will be in
3330 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3331 * @interval: the time between calls to the function, in milliseconds
3332 * (1/1000ths of a second)
3333 * @function: function to call
3334 * @data: data to pass to @function
3335 * @notify: function to call when the timeout is removed, or %NULL
3337 * Sets a function to be called at regular intervals, with the given
3338 * priority. The function is called repeatedly until it returns
3339 * %FALSE, at which point the timeout is automatically destroyed and
3340 * the function will not be called again. The @notify function is
3341 * called when the timeout is destroyed. The first call to the
3342 * function will be at the end of the first @interval.
3344 * Note that timeout functions may be delayed, due to the processing of other
3345 * event sources. Thus they should not be relied on for precise timing.
3346 * After each call to the timeout function, the time of the next
3347 * timeout is recalculated based on the current time and the given interval
3348 * (it does not try to 'catch up' time lost in delays).
3350 * This internally creates a main loop source using g_timeout_source_new()
3351 * and attaches it to the main loop context using g_source_attach(). You can
3352 * do these steps manually if you need greater control.
3354 * Return value: the ID (greater than 0) of the event source.
3357 g_timeout_add_full (gint priority,
3359 GSourceFunc function,
3361 GDestroyNotify notify)
3366 g_return_val_if_fail (function != NULL, 0);
3368 source = g_timeout_source_new (interval);
3370 if (priority != G_PRIORITY_DEFAULT)
3371 g_source_set_priority (source, priority);
3373 g_source_set_callback (source, function, data, notify);
3374 id = g_source_attach (source, NULL);
3375 g_source_unref (source);
3382 * @interval: the time between calls to the function, in milliseconds
3383 * (1/1000ths of a second)
3384 * @function: function to call
3385 * @data: data to pass to @function
3387 * Sets a function to be called at regular intervals, with the default
3388 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
3389 * until it returns %FALSE, at which point the timeout is automatically
3390 * destroyed and the function will not be called again. The first call
3391 * to the function will be at the end of the first @interval.
3393 * Note that timeout functions may be delayed, due to the processing of other
3394 * event sources. Thus they should not be relied on for precise timing.
3395 * After each call to the timeout function, the time of the next
3396 * timeout is recalculated based on the current time and the given interval
3397 * (it does not try to 'catch up' time lost in delays).
3399 * If you want to have a timer in the "seconds" range and do not care
3400 * about the exact time of the first call of the timer, use the
3401 * g_timeout_add_seconds() function; this function allows for more
3402 * optimizations and more efficient system power usage.
3404 * This internally creates a main loop source using g_timeout_source_new()
3405 * and attaches it to the main loop context using g_source_attach(). You can
3406 * do these steps manually if you need greater control.
3408 * Return value: the ID (greater than 0) of the event source.
3411 g_timeout_add (guint32 interval,
3412 GSourceFunc function,
3415 return g_timeout_add_full (G_PRIORITY_DEFAULT,
3416 interval, function, data, NULL);
3420 * g_timeout_add_seconds_full:
3421 * @priority: the priority of the timeout source. Typically this will be in
3422 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3423 * @interval: the time between calls to the function, in seconds
3424 * @function: function to call
3425 * @data: data to pass to @function
3426 * @notify: function to call when the timeout is removed, or %NULL
3428 * Sets a function to be called at regular intervals, with @priority.
3429 * The function is called repeatedly until it returns %FALSE, at which
3430 * point the timeout is automatically destroyed and the function will
3431 * not be called again.
3433 * Unlike g_timeout_add(), this function operates at whole second granularity.
3434 * The initial starting point of the timer is determined by the implementation
3435 * and the implementation is expected to group multiple timers together so that
3436 * they fire all at the same time.
3437 * To allow this grouping, the @interval to the first timer is rounded
3438 * and can deviate up to one second from the specified interval.
3439 * Subsequent timer iterations will generally run at the specified interval.
3441 * Note that timeout functions may be delayed, due to the processing of other
3442 * event sources. Thus they should not be relied on for precise timing.
3443 * After each call to the timeout function, the time of the next
3444 * timeout is recalculated based on the current time and the given @interval
3446 * If you want timing more precise than whole seconds, use g_timeout_add()
3449 * The grouping of timers to fire at the same time results in a more power
3450 * and CPU efficient behavior so if your timer is in multiples of seconds
3451 * and you don't require the first timer exactly one second from now, the
3452 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
3454 * This internally creates a main loop source using
3455 * g_timeout_source_new_seconds() and attaches it to the main loop context
3456 * using g_source_attach(). You can do these steps manually if you need
3459 * Return value: the ID (greater than 0) of the event source.
3464 g_timeout_add_seconds_full (gint priority,
3466 GSourceFunc function,
3468 GDestroyNotify notify)
3473 g_return_val_if_fail (function != NULL, 0);
3475 source = g_timeout_source_new_seconds (interval);
3477 if (priority != G_PRIORITY_DEFAULT)
3478 g_source_set_priority (source, priority);
3480 g_source_set_callback (source, function, data, notify);
3481 id = g_source_attach (source, NULL);
3482 g_source_unref (source);
3488 * g_timeout_add_seconds:
3489 * @interval: the time between calls to the function, in seconds
3490 * @function: function to call
3491 * @data: data to pass to @function
3493 * Sets a function to be called at regular intervals with the default
3494 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
3495 * it returns %FALSE, at which point the timeout is automatically destroyed
3496 * and the function will not be called again.
3498 * This internally creates a main loop source using
3499 * g_timeout_source_new_seconds() and attaches it to the main loop context
3500 * using g_source_attach(). You can do these steps manually if you need
3501 * greater control. Also see g_timout_add_seconds_full().
3503 * Return value: the ID (greater than 0) of the event source.
3508 g_timeout_add_seconds (guint interval,
3509 GSourceFunc function,
3512 g_return_val_if_fail (function != NULL, 0);
3514 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
3517 /* Child watch functions */
3522 g_child_watch_prepare (GSource *source,
3531 g_child_watch_check (GSource *source)
3533 GChildWatchSource *child_watch_source;
3534 gboolean child_exited;
3536 child_watch_source = (GChildWatchSource *) source;
3538 child_exited = child_watch_source->poll.revents & G_IO_IN;
3545 * Note: We do _not_ check for the special value of STILL_ACTIVE
3546 * since we know that the process has exited and doing so runs into
3547 * problems if the child process "happens to return STILL_ACTIVE(259)"
3548 * as Microsoft's Platform SDK puts it.
3550 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
3552 gchar *emsg = g_win32_error_message (GetLastError ());
3553 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
3556 child_watch_source->child_status = -1;
3559 child_watch_source->child_status = child_status;
3562 return child_exited;
3565 #else /* G_OS_WIN32 */
3568 check_for_child_exited (GSource *source)
3570 GChildWatchSource *child_watch_source;
3573 /* protect against another SIGCHLD in the middle of this call */
3574 count = child_watch_count;
3576 child_watch_source = (GChildWatchSource *) source;
3578 if (child_watch_source->child_exited)
3581 if (child_watch_source->count < count)
3585 if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
3587 child_watch_source->child_status = child_status;
3588 child_watch_source->child_exited = TRUE;
3590 child_watch_source->count = count;
3593 return child_watch_source->child_exited;
3597 g_child_watch_prepare (GSource *source,
3602 return check_for_child_exited (source);
3607 g_child_watch_check (GSource *source)
3609 return check_for_child_exited (source);
3612 #endif /* G_OS_WIN32 */
3615 g_child_watch_dispatch (GSource *source,
3616 GSourceFunc callback,
3619 GChildWatchSource *child_watch_source;
3620 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
3622 child_watch_source = (GChildWatchSource *) source;
3626 g_warning ("Child watch source dispatched without callback\n"
3627 "You must call g_source_set_callback().");
3631 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
3633 /* We never keep a child watch source around as the child is gone */
3640 g_child_watch_signal_handler (int signum)
3642 child_watch_count ++;
3644 if (child_watch_init_state == CHILD_WATCH_INITIALIZED_THREADED)
3646 write (child_watch_wake_up_pipe[1], "B", 1);
3650 /* We count on the signal interrupting the poll in the same thread.
3656 g_child_watch_source_init_single (void)
3658 struct sigaction action;
3660 g_assert (! g_thread_supported());
3661 g_assert (child_watch_init_state == CHILD_WATCH_UNINITIALIZED);
3663 child_watch_init_state = CHILD_WATCH_INITIALIZED_SINGLE;
3665 action.sa_handler = g_child_watch_signal_handler;
3666 sigemptyset (&action.sa_mask);
3667 action.sa_flags = SA_NOCLDSTOP;
3668 sigaction (SIGCHLD, &action, NULL);
3671 G_GNUC_NORETURN static gpointer
3672 child_watch_helper_thread (gpointer data)
3679 read (child_watch_wake_up_pipe[0], b, 20);
3681 /* We were woken up. Wake up all other contexts in all other threads */
3682 G_LOCK (main_context_list);
3683 for (list = main_context_list; list; list = list->next)
3685 GMainContext *context;
3687 context = list->data;
3688 if (g_atomic_int_get (&context->ref_count) > 0)
3689 /* Due to racing conditions we can find ref_count == 0, in
3690 * that case, however, the context is still not destroyed
3691 * and no poll can be active, otherwise the ref_count
3693 g_main_context_wakeup (context);
3695 G_UNLOCK (main_context_list);
3700 g_child_watch_source_init_multi_threaded (void)
3702 GError *error = NULL;
3703 struct sigaction action;
3705 g_assert (g_thread_supported());
3707 if (pipe (child_watch_wake_up_pipe) < 0)
3708 g_error ("Cannot create wake up pipe: %s\n", g_strerror (errno));
3709 fcntl (child_watch_wake_up_pipe[1], F_SETFL, O_NONBLOCK | fcntl (child_watch_wake_up_pipe[1], F_GETFL));
3711 /* We create a helper thread that polls on the wakeup pipe indefinitely */
3712 /* FIXME: Think this through for races */
3713 if (g_thread_create (child_watch_helper_thread, NULL, FALSE, &error) == NULL)
3714 g_error ("Cannot create a thread to monitor child exit status: %s\n", error->message);
3715 child_watch_init_state = CHILD_WATCH_INITIALIZED_THREADED;
3717 action.sa_handler = g_child_watch_signal_handler;
3718 sigemptyset (&action.sa_mask);
3719 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
3720 sigaction (SIGCHLD, &action, NULL);
3724 g_child_watch_source_init_promote_single_to_threaded (void)
3726 g_child_watch_source_init_multi_threaded ();
3730 g_child_watch_source_init (void)
3732 if (g_thread_supported())
3734 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
3735 g_child_watch_source_init_multi_threaded ();
3736 else if (child_watch_init_state == CHILD_WATCH_INITIALIZED_SINGLE)
3737 g_child_watch_source_init_promote_single_to_threaded ();
3741 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
3742 g_child_watch_source_init_single ();
3746 #endif /* !G_OS_WIN32 */
3749 * g_child_watch_source_new:
3750 * @pid: process to watch. On POSIX the pid of a child process. On
3751 * Windows a handle for a process (which doesn't have to be a child).
3753 * Creates a new child_watch source.
3755 * The source will not initially be associated with any #GMainContext
3756 * and must be added to one with g_source_attach() before it will be
3759 * Note that child watch sources can only be used in conjunction with
3760 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
3763 * Note that on platforms where #GPid must be explicitly closed
3764 * (see g_spawn_close_pid()) @pid must not be closed while the
3765 * source is still active. Typically, you will want to call
3766 * g_spawn_close_pid() in the callback function for the source.
3768 * Note further that using g_child_watch_source_new() is not
3769 * compatible with calling <literal>waitpid(-1)</literal> in
3770 * the application. Calling waitpid() for individual pids will
3773 * Return value: the newly-created child watch source
3778 g_child_watch_source_new (GPid pid)
3780 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
3781 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
3784 child_watch_source->poll.fd = (gintptr) pid;
3785 child_watch_source->poll.events = G_IO_IN;
3787 g_source_add_poll (source, &child_watch_source->poll);
3788 #else /* G_OS_WIN32 */
3789 g_child_watch_source_init ();
3790 #endif /* G_OS_WIN32 */
3792 child_watch_source->pid = pid;
3798 * g_child_watch_add_full:
3799 * @priority: the priority of the idle source. Typically this will be in the
3800 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3801 * @pid: process to watch. On POSIX the pid of a child process. On
3802 * Windows a handle for a process (which doesn't have to be a child).
3803 * @function: function to call
3804 * @data: data to pass to @function
3805 * @notify: function to call when the idle is removed, or %NULL
3807 * Sets a function to be called when the child indicated by @pid
3808 * exits, at the priority @priority.
3810 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
3811 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
3812 * the spawn function for the child watching to work.
3814 * Note that on platforms where #GPid must be explicitly closed
3815 * (see g_spawn_close_pid()) @pid must not be closed while the
3816 * source is still active. Typically, you will want to call
3817 * g_spawn_close_pid() in the callback function for the source.
3819 * GLib supports only a single callback per process id.
3821 * This internally creates a main loop source using
3822 * g_child_watch_source_new() and attaches it to the main loop context
3823 * using g_source_attach(). You can do these steps manually if you
3824 * need greater control.
3826 * Return value: the ID (greater than 0) of the event source.
3831 g_child_watch_add_full (gint priority,
3833 GChildWatchFunc function,
3835 GDestroyNotify notify)
3840 g_return_val_if_fail (function != NULL, 0);
3842 source = g_child_watch_source_new (pid);
3844 if (priority != G_PRIORITY_DEFAULT)
3845 g_source_set_priority (source, priority);
3847 g_source_set_callback (source, (GSourceFunc) function, data, notify);
3848 id = g_source_attach (source, NULL);
3849 g_source_unref (source);
3855 * g_child_watch_add:
3856 * @pid: process id to watch. On POSIX the pid of a child process. On
3857 * Windows a handle for a process (which doesn't have to be a child).
3858 * @function: function to call
3859 * @data: data to pass to @function
3861 * Sets a function to be called when the child indicated by @pid
3862 * exits, at a default priority, #G_PRIORITY_DEFAULT.
3864 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
3865 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
3866 * the spawn function for the child watching to work.
3868 * Note that on platforms where #GPid must be explicitly closed
3869 * (see g_spawn_close_pid()) @pid must not be closed while the
3870 * source is still active. Typically, you will want to call
3871 * g_spawn_close_pid() in the callback function for the source.
3873 * GLib supports only a single callback per process id.
3875 * This internally creates a main loop source using
3876 * g_child_watch_source_new() and attaches it to the main loop context
3877 * using g_source_attach(). You can do these steps manually if you
3878 * need greater control.
3880 * Return value: the ID (greater than 0) of the event source.
3885 g_child_watch_add (GPid pid,
3886 GChildWatchFunc function,
3889 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
3893 /* Idle functions */
3896 g_idle_prepare (GSource *source,
3905 g_idle_check (GSource *source)
3911 g_idle_dispatch (GSource *source,
3912 GSourceFunc callback,
3917 g_warning ("Idle source dispatched without callback\n"
3918 "You must call g_source_set_callback().");
3922 return callback (user_data);
3926 * g_idle_source_new:
3928 * Creates a new idle source.
3930 * The source will not initially be associated with any #GMainContext
3931 * and must be added to one with g_source_attach() before it will be
3932 * executed. Note that the default priority for idle sources is
3933 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
3934 * have a default priority of %G_PRIORITY_DEFAULT.
3936 * Return value: the newly-created idle source
3939 g_idle_source_new (void)
3943 source = g_source_new (&g_idle_funcs, sizeof (GSource));
3944 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
3951 * @priority: the priority of the idle source. Typically this will be in the
3952 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3953 * @function: function to call
3954 * @data: data to pass to @function
3955 * @notify: function to call when the idle is removed, or %NULL
3957 * Adds a function to be called whenever there are no higher priority
3958 * events pending. If the function returns %FALSE it is automatically
3959 * removed from the list of event sources and will not be called again.
3961 * This internally creates a main loop source using g_idle_source_new()
3962 * and attaches it to the main loop context using g_source_attach().
3963 * You can do these steps manually if you need greater control.
3965 * Return value: the ID (greater than 0) of the event source.
3968 g_idle_add_full (gint priority,
3969 GSourceFunc function,
3971 GDestroyNotify notify)
3976 g_return_val_if_fail (function != NULL, 0);
3978 source = g_idle_source_new ();
3980 if (priority != G_PRIORITY_DEFAULT_IDLE)
3981 g_source_set_priority (source, priority);
3983 g_source_set_callback (source, function, data, notify);
3984 id = g_source_attach (source, NULL);
3985 g_source_unref (source);
3992 * @function: function to call
3993 * @data: data to pass to @function.
3995 * Adds a function to be called whenever there are no higher priority
3996 * events pending to the default main loop. The function is given the
3997 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
3998 * returns %FALSE it is automatically removed from the list of event
3999 * sources and will not be called again.
4001 * This internally creates a main loop source using g_idle_source_new()
4002 * and attaches it to the main loop context using g_source_attach().
4003 * You can do these steps manually if you need greater control.
4005 * Return value: the ID (greater than 0) of the event source.
4008 g_idle_add (GSourceFunc function,
4011 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4015 * g_idle_remove_by_data:
4016 * @data: the data for the idle source's callback.
4018 * Removes the idle function with the given data.
4020 * Return value: %TRUE if an idle source was found and removed.
4023 g_idle_remove_by_data (gpointer data)
4025 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4028 #define __G_MAIN_C__
4029 #include "galiasdef.c"