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 LOCK_CONTEXT (context);
2395 g_return_val_if_fail (g_thread_supported (), FALSE);
2401 context->cond = g_cond_new ();
2403 got_ownership = g_main_context_wait (context,
2405 g_static_mutex_get_mutex (&context->mutex));
2411 LOCK_CONTEXT (context);
2412 #endif /* G_THREADS_ENABLED */
2414 if (!context->cached_poll_array)
2416 context->cached_poll_array_size = context->n_poll_records;
2417 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2420 allocated_nfds = context->cached_poll_array_size;
2421 fds = context->cached_poll_array;
2423 UNLOCK_CONTEXT (context);
2425 g_main_context_prepare (context, &max_priority);
2427 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
2428 allocated_nfds)) > allocated_nfds)
2430 LOCK_CONTEXT (context);
2432 context->cached_poll_array_size = allocated_nfds = nfds;
2433 context->cached_poll_array = fds = g_new (GPollFD, nfds);
2434 UNLOCK_CONTEXT (context);
2440 g_main_context_poll (context, timeout, max_priority, fds, nfds);
2442 some_ready = g_main_context_check (context, max_priority, fds, nfds);
2445 g_main_context_dispatch (context);
2447 #ifdef G_THREADS_ENABLED
2448 g_main_context_release (context);
2449 #endif /* G_THREADS_ENABLED */
2451 LOCK_CONTEXT (context);
2457 * g_main_context_pending:
2458 * @context: a #GMainContext (if %NULL, the default context will be used)
2460 * Checks if any sources have pending events for the given context.
2462 * Return value: %TRUE if events are pending.
2465 g_main_context_pending (GMainContext *context)
2470 context = g_main_context_default();
2472 LOCK_CONTEXT (context);
2473 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
2474 UNLOCK_CONTEXT (context);
2480 * g_main_context_iteration:
2481 * @context: a #GMainContext (if %NULL, the default context will be used)
2482 * @may_block: whether the call may block.
2484 * Runs a single iteration for the given main loop. This involves
2485 * checking to see if any event sources are ready to be processed,
2486 * then if no events sources are ready and @may_block is %TRUE, waiting
2487 * for a source to become ready, then dispatching the highest priority
2488 * events sources that are ready. Otherwise, if @may_block is %FALSE
2489 * sources are not waited to become ready, only those highest priority
2490 * events sources will be dispatched (if any), that are ready at this
2491 * given moment without further waiting.
2493 * Note that even when @may_block is %TRUE, it is still possible for
2494 * g_main_context_iteration() to return %FALSE, since the the wait may
2495 * be interrupted for other reasons than an event source becoming ready.
2497 * Return value: %TRUE if events were dispatched.
2500 g_main_context_iteration (GMainContext *context, gboolean may_block)
2505 context = g_main_context_default();
2507 LOCK_CONTEXT (context);
2508 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
2509 UNLOCK_CONTEXT (context);
2516 * @context: a #GMainContext (if %NULL, the default context will be used).
2517 * @is_running: set to %TRUE to indicate that the loop is running. This
2518 * is not very important since calling g_main_loop_run() will set this to
2521 * Creates a new #GMainLoop structure.
2523 * Return value: a new #GMainLoop.
2526 g_main_loop_new (GMainContext *context,
2527 gboolean is_running)
2532 context = g_main_context_default();
2534 g_main_context_ref (context);
2536 loop = g_new0 (GMainLoop, 1);
2537 loop->context = context;
2538 loop->is_running = is_running != FALSE;
2539 loop->ref_count = 1;
2546 * @loop: a #GMainLoop
2548 * Increases the reference count on a #GMainLoop object by one.
2550 * Return value: @loop
2553 g_main_loop_ref (GMainLoop *loop)
2555 g_return_val_if_fail (loop != NULL, NULL);
2556 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2558 g_atomic_int_inc (&loop->ref_count);
2564 * g_main_loop_unref:
2565 * @loop: a #GMainLoop
2567 * Decreases the reference count on a #GMainLoop object by one. If
2568 * the result is zero, free the loop and free all associated memory.
2571 g_main_loop_unref (GMainLoop *loop)
2573 g_return_if_fail (loop != NULL);
2574 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2576 if (!g_atomic_int_dec_and_test (&loop->ref_count))
2579 g_main_context_unref (loop->context);
2585 * @loop: a #GMainLoop
2587 * Runs a main loop until g_main_loop_quit() is called on the loop.
2588 * If this is called for the thread of the loop's #GMainContext,
2589 * it will process events from the loop, otherwise it will
2593 g_main_loop_run (GMainLoop *loop)
2595 GThread *self = G_THREAD_SELF;
2597 g_return_if_fail (loop != NULL);
2598 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2600 #ifdef G_THREADS_ENABLED
2601 if (!g_main_context_acquire (loop->context))
2603 gboolean got_ownership = FALSE;
2605 /* Another thread owns this context */
2606 if (!g_thread_supported ())
2608 g_warning ("g_main_loop_run() was called from second thread but "
2609 "g_thread_init() was never called.");
2613 LOCK_CONTEXT (loop->context);
2615 g_atomic_int_inc (&loop->ref_count);
2617 if (!loop->is_running)
2618 loop->is_running = TRUE;
2620 if (!loop->context->cond)
2621 loop->context->cond = g_cond_new ();
2623 while (loop->is_running && !got_ownership)
2624 got_ownership = g_main_context_wait (loop->context,
2625 loop->context->cond,
2626 g_static_mutex_get_mutex (&loop->context->mutex));
2628 if (!loop->is_running)
2630 UNLOCK_CONTEXT (loop->context);
2632 g_main_context_release (loop->context);
2633 g_main_loop_unref (loop);
2637 g_assert (got_ownership);
2640 LOCK_CONTEXT (loop->context);
2641 #endif /* G_THREADS_ENABLED */
2643 if (loop->context->in_check_or_prepare)
2645 g_warning ("g_main_loop_run(): called recursively from within a source's "
2646 "check() or prepare() member, iteration not possible.");
2650 g_atomic_int_inc (&loop->ref_count);
2651 loop->is_running = TRUE;
2652 while (loop->is_running)
2653 g_main_context_iterate (loop->context, TRUE, TRUE, self);
2655 UNLOCK_CONTEXT (loop->context);
2657 #ifdef G_THREADS_ENABLED
2658 g_main_context_release (loop->context);
2659 #endif /* G_THREADS_ENABLED */
2661 g_main_loop_unref (loop);
2666 * @loop: a #GMainLoop
2668 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
2669 * for the loop will return.
2671 * Note that sources that have already been dispatched when
2672 * g_main_loop_quit() is called will still be executed.
2675 g_main_loop_quit (GMainLoop *loop)
2677 g_return_if_fail (loop != NULL);
2678 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2680 LOCK_CONTEXT (loop->context);
2681 loop->is_running = FALSE;
2682 g_main_context_wakeup_unlocked (loop->context);
2684 #ifdef G_THREADS_ENABLED
2685 if (loop->context->cond)
2686 g_cond_broadcast (loop->context->cond);
2687 #endif /* G_THREADS_ENABLED */
2689 UNLOCK_CONTEXT (loop->context);
2693 * g_main_loop_is_running:
2694 * @loop: a #GMainLoop.
2696 * Checks to see if the main loop is currently being run via g_main_loop_run().
2698 * Return value: %TRUE if the mainloop is currently being run.
2701 g_main_loop_is_running (GMainLoop *loop)
2703 g_return_val_if_fail (loop != NULL, FALSE);
2704 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
2706 return loop->is_running;
2710 * g_main_loop_get_context:
2711 * @loop: a #GMainLoop.
2713 * Returns the #GMainContext of @loop.
2715 * Return value: the #GMainContext of @loop
2718 g_main_loop_get_context (GMainLoop *loop)
2720 g_return_val_if_fail (loop != NULL, NULL);
2721 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2723 return loop->context;
2726 /* HOLDS: context's lock */
2728 g_main_context_poll (GMainContext *context,
2734 #ifdef G_MAIN_POLL_DEBUG
2740 GPollFunc poll_func;
2742 if (n_fds || timeout != 0)
2744 #ifdef G_MAIN_POLL_DEBUG
2745 if (_g_main_poll_debug)
2747 g_print ("polling context=%p n=%d timeout=%d\n",
2748 context, n_fds, timeout);
2749 poll_timer = g_timer_new ();
2753 LOCK_CONTEXT (context);
2755 poll_func = context->poll_func;
2757 UNLOCK_CONTEXT (context);
2758 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
2761 g_warning ("poll(2) failed due to: %s.",
2762 g_strerror (errno));
2764 /* If g_poll () returns -1, it has already called g_warning() */
2768 #ifdef G_MAIN_POLL_DEBUG
2769 if (_g_main_poll_debug)
2771 LOCK_CONTEXT (context);
2773 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
2776 g_timer_elapsed (poll_timer, NULL));
2777 g_timer_destroy (poll_timer);
2778 pollrec = context->poll_records;
2780 while (pollrec != NULL)
2785 if (fds[i].fd == pollrec->fd->fd &&
2786 pollrec->fd->events &&
2789 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
2790 if (fds[i].revents & G_IO_IN)
2792 if (fds[i].revents & G_IO_OUT)
2794 if (fds[i].revents & G_IO_PRI)
2796 if (fds[i].revents & G_IO_ERR)
2798 if (fds[i].revents & G_IO_HUP)
2800 if (fds[i].revents & G_IO_NVAL)
2806 pollrec = pollrec->next;
2810 UNLOCK_CONTEXT (context);
2813 } /* if (n_fds || timeout != 0) */
2817 * g_main_context_add_poll:
2818 * @context: a #GMainContext (or %NULL for the default context)
2819 * @fd: a #GPollFD structure holding information about a file
2820 * descriptor to watch.
2821 * @priority: the priority for this file descriptor which should be
2822 * the same as the priority used for g_source_attach() to ensure that the
2823 * file descriptor is polled whenever the results may be needed.
2825 * Adds a file descriptor to the set of file descriptors polled for
2826 * this context. This will very seldomly be used directly. Instead
2827 * a typical event source will use g_source_add_poll() instead.
2830 g_main_context_add_poll (GMainContext *context,
2835 context = g_main_context_default ();
2837 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
2838 g_return_if_fail (fd);
2840 LOCK_CONTEXT (context);
2841 g_main_context_add_poll_unlocked (context, priority, fd);
2842 UNLOCK_CONTEXT (context);
2845 /* HOLDS: main_loop_lock */
2847 g_main_context_add_poll_unlocked (GMainContext *context,
2851 GPollRec *lastrec, *pollrec;
2852 GPollRec *newrec = g_slice_new (GPollRec);
2854 /* This file descriptor may be checked before we ever poll */
2857 newrec->priority = priority;
2860 pollrec = context->poll_records;
2861 while (pollrec && priority >= pollrec->priority)
2864 pollrec = pollrec->next;
2868 lastrec->next = newrec;
2870 context->poll_records = newrec;
2872 newrec->next = pollrec;
2874 context->n_poll_records++;
2876 #ifdef G_THREADS_ENABLED
2877 context->poll_changed = TRUE;
2879 /* Now wake up the main loop if it is waiting in the poll() */
2880 g_main_context_wakeup_unlocked (context);
2885 * g_main_context_remove_poll:
2886 * @context:a #GMainContext
2887 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
2889 * Removes file descriptor from the set of file descriptors to be
2890 * polled for a particular context.
2893 g_main_context_remove_poll (GMainContext *context,
2897 context = g_main_context_default ();
2899 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
2900 g_return_if_fail (fd);
2902 LOCK_CONTEXT (context);
2903 g_main_context_remove_poll_unlocked (context, fd);
2904 UNLOCK_CONTEXT (context);
2908 g_main_context_remove_poll_unlocked (GMainContext *context,
2911 GPollRec *pollrec, *lastrec;
2914 pollrec = context->poll_records;
2918 if (pollrec->fd == fd)
2920 if (lastrec != NULL)
2921 lastrec->next = pollrec->next;
2923 context->poll_records = pollrec->next;
2925 g_slice_free (GPollRec, pollrec);
2927 context->n_poll_records--;
2931 pollrec = pollrec->next;
2934 #ifdef G_THREADS_ENABLED
2935 context->poll_changed = TRUE;
2937 /* Now wake up the main loop if it is waiting in the poll() */
2938 g_main_context_wakeup_unlocked (context);
2943 * g_source_get_current_time:
2944 * @source: a #GSource
2945 * @timeval: #GTimeVal structure in which to store current time.
2947 * Gets the "current time" to be used when checking
2948 * this source. The advantage of calling this function over
2949 * calling g_get_current_time() directly is that when
2950 * checking multiple sources, GLib can cache a single value
2951 * instead of having to repeatedly get the system time.
2954 g_source_get_current_time (GSource *source,
2957 GMainContext *context;
2959 g_return_if_fail (source->context != NULL);
2961 context = source->context;
2963 LOCK_CONTEXT (context);
2965 if (!context->time_is_current)
2967 g_get_current_time (&context->current_time);
2968 context->time_is_current = TRUE;
2971 *timeval = context->current_time;
2973 UNLOCK_CONTEXT (context);
2977 * g_main_context_set_poll_func:
2978 * @context: a #GMainContext
2979 * @func: the function to call to poll all file descriptors
2981 * Sets the function to use to handle polling of file descriptors. It
2982 * will be used instead of the poll() system call
2983 * (or GLib's replacement function, which is used where
2984 * poll() isn't available).
2986 * This function could possibly be used to integrate the GLib event
2987 * loop with an external event loop.
2990 g_main_context_set_poll_func (GMainContext *context,
2994 context = g_main_context_default ();
2996 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
2998 LOCK_CONTEXT (context);
3001 context->poll_func = func;
3003 context->poll_func = g_poll;
3005 UNLOCK_CONTEXT (context);
3009 * g_main_context_get_poll_func:
3010 * @context: a #GMainContext
3012 * Gets the poll function set by g_main_context_set_poll_func().
3014 * Return value: the poll function
3017 g_main_context_get_poll_func (GMainContext *context)
3022 context = g_main_context_default ();
3024 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3026 LOCK_CONTEXT (context);
3027 result = context->poll_func;
3028 UNLOCK_CONTEXT (context);
3033 /* HOLDS: context's lock */
3034 /* Wake the main loop up from a poll() */
3036 g_main_context_wakeup_unlocked (GMainContext *context)
3038 #ifdef G_THREADS_ENABLED
3039 if (g_thread_supported() && context->poll_waiting)
3041 context->poll_waiting = FALSE;
3043 write (context->wake_up_pipe[1], "A", 1);
3045 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
3052 * g_main_context_wakeup:
3053 * @context: a #GMainContext
3055 * If @context is currently waiting in a poll(), interrupt
3056 * the poll(), and continue the iteration process.
3059 g_main_context_wakeup (GMainContext *context)
3062 context = g_main_context_default ();
3064 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3066 LOCK_CONTEXT (context);
3067 g_main_context_wakeup_unlocked (context);
3068 UNLOCK_CONTEXT (context);
3072 * g_main_context_is_owner:
3073 * @context: a #GMainContext
3075 * Determines whether this thread holds the (recursive)
3076 * ownership of this #GMaincontext. This is useful to
3077 * know before waiting on another thread that may be
3078 * blocking to get ownership of @context.
3080 * Returns: %TRUE if current thread is owner of @context.
3085 g_main_context_is_owner (GMainContext *context)
3090 context = g_main_context_default ();
3092 #ifdef G_THREADS_ENABLED
3093 LOCK_CONTEXT (context);
3094 is_owner = context->owner == G_THREAD_SELF;
3095 UNLOCK_CONTEXT (context);
3106 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3107 GTimeVal *current_time)
3109 guint seconds = timeout_source->interval / 1000;
3110 guint msecs = timeout_source->interval - seconds * 1000;
3112 timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
3113 timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
3114 if (timeout_source->expiration.tv_usec >= 1000000)
3116 timeout_source->expiration.tv_usec -= 1000000;
3117 timeout_source->expiration.tv_sec++;
3119 if (timer_perturb==-1)
3122 * we want a per machine/session unique 'random' value; try the dbus
3123 * address first, that has a UUID in it. If there is no dbus, use the
3124 * hostname for hashing.
3126 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3127 if (!session_bus_address)
3128 session_bus_address = g_getenv ("HOSTNAME");
3129 if (session_bus_address)
3130 timer_perturb = ABS ((gint) g_str_hash (session_bus_address));
3134 if (timeout_source->granularity)
3137 gint gran; /* in usecs */
3140 gran = timeout_source->granularity * 1000;
3141 perturb = timer_perturb % gran;
3143 * We want to give each machine a per machine pertubation;
3144 * shift time back first, and forward later after the rounding
3147 timeout_source->expiration.tv_usec -= perturb;
3148 if (timeout_source->expiration.tv_usec < 0)
3150 timeout_source->expiration.tv_usec += 1000000;
3151 timeout_source->expiration.tv_sec--;
3154 remainder = timeout_source->expiration.tv_usec % gran;
3155 if (remainder >= gran/4) /* round up */
3156 timeout_source->expiration.tv_usec += gran;
3157 timeout_source->expiration.tv_usec -= remainder;
3159 timeout_source->expiration.tv_usec += perturb;
3161 /* the rounding may have overflown tv_usec */
3162 while (timeout_source->expiration.tv_usec > 1000000)
3164 timeout_source->expiration.tv_usec -= 1000000;
3165 timeout_source->expiration.tv_sec++;
3171 g_timeout_prepare (GSource *source,
3176 GTimeVal current_time;
3178 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3180 g_source_get_current_time (source, ¤t_time);
3182 sec = timeout_source->expiration.tv_sec - current_time.tv_sec;
3183 msec = (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000;
3185 /* We do the following in a rather convoluted fashion to deal with
3186 * the fact that we don't have an integral type big enough to hold
3187 * the difference of two timevals in millseconds.
3189 if (sec < 0 || (sec == 0 && msec < 0))
3193 glong interval_sec = timeout_source->interval / 1000;
3194 glong interval_msec = timeout_source->interval % 1000;
3202 if (sec > interval_sec ||
3203 (sec == interval_sec && msec > interval_msec))
3205 /* The system time has been set backwards, so we
3206 * reset the expiration time to now + timeout_source->interval;
3207 * this at least avoids hanging for long periods of time.
3209 g_timeout_set_expiration (timeout_source, ¤t_time);
3210 msec = MIN (G_MAXINT, timeout_source->interval);
3214 msec = MIN (G_MAXINT, (guint)msec + 1000 * (guint)sec);
3218 *timeout = (gint)msec;
3224 g_timeout_check (GSource *source)
3226 GTimeVal current_time;
3227 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3229 g_source_get_current_time (source, ¤t_time);
3231 return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
3232 ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
3233 (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
3237 g_timeout_dispatch (GSource *source,
3238 GSourceFunc callback,
3241 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3245 g_warning ("Timeout source dispatched without callback\n"
3246 "You must call g_source_set_callback().");
3250 if (callback (user_data))
3252 GTimeVal current_time;
3254 g_source_get_current_time (source, ¤t_time);
3255 g_timeout_set_expiration (timeout_source, ¤t_time);
3264 * g_timeout_source_new:
3265 * @interval: the timeout interval in milliseconds.
3267 * Creates a new timeout source.
3269 * The source will not initially be associated with any #GMainContext
3270 * and must be added to one with g_source_attach() before it will be
3273 * Return value: the newly-created timeout source
3276 g_timeout_source_new (guint interval)
3278 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3279 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3280 GTimeVal current_time;
3282 timeout_source->interval = interval;
3284 g_get_current_time (¤t_time);
3285 g_timeout_set_expiration (timeout_source, ¤t_time);
3291 * g_timeout_source_new_seconds:
3292 * @interval: the timeout interval in seconds
3294 * Creates a new timeout source.
3296 * The source will not initially be associated with any #GMainContext
3297 * and must be added to one with g_source_attach() before it will be
3300 * The scheduling granularity/accuracy of this timeout source will be
3303 * Return value: the newly-created timeout source
3308 g_timeout_source_new_seconds (guint interval)
3310 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3311 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3312 GTimeVal current_time;
3314 timeout_source->interval = 1000*interval;
3315 timeout_source->granularity = 1000;
3317 g_get_current_time (¤t_time);
3318 g_timeout_set_expiration (timeout_source, ¤t_time);
3325 * g_timeout_add_full:
3326 * @priority: the priority of the timeout source. Typically this will be in
3327 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3328 * @interval: the time between calls to the function, in milliseconds
3329 * (1/1000ths of a second)
3330 * @function: function to call
3331 * @data: data to pass to @function
3332 * @notify: function to call when the timeout is removed, or %NULL
3334 * Sets a function to be called at regular intervals, with the given
3335 * priority. The function is called repeatedly until it returns
3336 * %FALSE, at which point the timeout is automatically destroyed and
3337 * the function will not be called again. The @notify function is
3338 * called when the timeout is destroyed. The first call to the
3339 * function will be at the end of the first @interval.
3341 * Note that timeout functions may be delayed, due to the processing of other
3342 * event sources. Thus they should not be relied on for precise timing.
3343 * After each call to the timeout function, the time of the next
3344 * timeout is recalculated based on the current time and the given interval
3345 * (it does not try to 'catch up' time lost in delays).
3347 * This internally creates a main loop source using g_timeout_source_new()
3348 * and attaches it to the main loop context using g_source_attach(). You can
3349 * do these steps manually if you need greater control.
3351 * Return value: the ID (greater than 0) of the event source.
3354 g_timeout_add_full (gint priority,
3356 GSourceFunc function,
3358 GDestroyNotify notify)
3363 g_return_val_if_fail (function != NULL, 0);
3365 source = g_timeout_source_new (interval);
3367 if (priority != G_PRIORITY_DEFAULT)
3368 g_source_set_priority (source, priority);
3370 g_source_set_callback (source, function, data, notify);
3371 id = g_source_attach (source, NULL);
3372 g_source_unref (source);
3379 * @interval: the time between calls to the function, in milliseconds
3380 * (1/1000ths of a second)
3381 * @function: function to call
3382 * @data: data to pass to @function
3384 * Sets a function to be called at regular intervals, with the default
3385 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
3386 * until it returns %FALSE, at which point the timeout is automatically
3387 * destroyed and the function will not be called again. The first call
3388 * to the function will be at the end of the first @interval.
3390 * Note that timeout functions may be delayed, due to the processing of other
3391 * event sources. Thus they should not be relied on for precise timing.
3392 * After each call to the timeout function, the time of the next
3393 * timeout is recalculated based on the current time and the given interval
3394 * (it does not try to 'catch up' time lost in delays).
3396 * If you want to have a timer in the "seconds" range and do not care
3397 * about the exact time of the first call of the timer, use the
3398 * g_timeout_add_seconds() function; this function allows for more
3399 * optimizations and more efficient system power usage.
3401 * This internally creates a main loop source using g_timeout_source_new()
3402 * and attaches it to the main loop context using g_source_attach(). You can
3403 * do these steps manually if you need greater control.
3405 * Return value: the ID (greater than 0) of the event source.
3408 g_timeout_add (guint32 interval,
3409 GSourceFunc function,
3412 return g_timeout_add_full (G_PRIORITY_DEFAULT,
3413 interval, function, data, NULL);
3417 * g_timeout_add_seconds_full:
3418 * @priority: the priority of the timeout source. Typically this will be in
3419 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3420 * @interval: the time between calls to the function, in seconds
3421 * @function: function to call
3422 * @data: data to pass to @function
3423 * @notify: function to call when the timeout is removed, or %NULL
3425 * Sets a function to be called at regular intervals, with @priority.
3426 * The function is called repeatedly until it returns %FALSE, at which
3427 * point the timeout is automatically destroyed and the function will
3428 * not be called again.
3430 * Unlike g_timeout_add(), this function operates at whole second granularity.
3431 * The initial starting point of the timer is determined by the implementation
3432 * and the implementation is expected to group multiple timers together so that
3433 * they fire all at the same time.
3434 * To allow this grouping, the @interval to the first timer is rounded
3435 * and can deviate up to one second from the specified interval.
3436 * Subsequent timer iterations will generally run at the specified interval.
3438 * Note that timeout functions may be delayed, due to the processing of other
3439 * event sources. Thus they should not be relied on for precise timing.
3440 * After each call to the timeout function, the time of the next
3441 * timeout is recalculated based on the current time and the given @interval
3443 * If you want timing more precise than whole seconds, use g_timeout_add()
3446 * The grouping of timers to fire at the same time results in a more power
3447 * and CPU efficient behavior so if your timer is in multiples of seconds
3448 * and you don't require the first timer exactly one second from now, the
3449 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
3451 * This internally creates a main loop source using
3452 * g_timeout_source_new_seconds() and attaches it to the main loop context
3453 * using g_source_attach(). You can do these steps manually if you need
3456 * Return value: the ID (greater than 0) of the event source.
3461 g_timeout_add_seconds_full (gint priority,
3463 GSourceFunc function,
3465 GDestroyNotify notify)
3470 g_return_val_if_fail (function != NULL, 0);
3472 source = g_timeout_source_new_seconds (interval);
3474 if (priority != G_PRIORITY_DEFAULT)
3475 g_source_set_priority (source, priority);
3477 g_source_set_callback (source, function, data, notify);
3478 id = g_source_attach (source, NULL);
3479 g_source_unref (source);
3485 * g_timeout_add_seconds:
3486 * @interval: the time between calls to the function, in seconds
3487 * @function: function to call
3488 * @data: data to pass to @function
3490 * Sets a function to be called at regular intervals with the default
3491 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
3492 * it returns %FALSE, at which point the timeout is automatically destroyed
3493 * and the function will not be called again.
3495 * This internally creates a main loop source using
3496 * g_timeout_source_new_seconds() and attaches it to the main loop context
3497 * using g_source_attach(). You can do these steps manually if you need
3498 * greater control. Also see g_timout_add_seconds_full().
3500 * Return value: the ID (greater than 0) of the event source.
3505 g_timeout_add_seconds (guint interval,
3506 GSourceFunc function,
3509 g_return_val_if_fail (function != NULL, 0);
3511 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
3514 /* Child watch functions */
3519 g_child_watch_prepare (GSource *source,
3528 g_child_watch_check (GSource *source)
3530 GChildWatchSource *child_watch_source;
3531 gboolean child_exited;
3533 child_watch_source = (GChildWatchSource *) source;
3535 child_exited = child_watch_source->poll.revents & G_IO_IN;
3542 * Note: We do _not_ check for the special value of STILL_ACTIVE
3543 * since we know that the process has exited and doing so runs into
3544 * problems if the child process "happens to return STILL_ACTIVE(259)"
3545 * as Microsoft's Platform SDK puts it.
3547 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
3549 gchar *emsg = g_win32_error_message (GetLastError ());
3550 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
3553 child_watch_source->child_status = -1;
3556 child_watch_source->child_status = child_status;
3559 return child_exited;
3562 #else /* G_OS_WIN32 */
3565 check_for_child_exited (GSource *source)
3567 GChildWatchSource *child_watch_source;
3570 /* protect against another SIGCHLD in the middle of this call */
3571 count = child_watch_count;
3573 child_watch_source = (GChildWatchSource *) source;
3575 if (child_watch_source->child_exited)
3578 if (child_watch_source->count < count)
3582 if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
3584 child_watch_source->child_status = child_status;
3585 child_watch_source->child_exited = TRUE;
3587 child_watch_source->count = count;
3590 return child_watch_source->child_exited;
3594 g_child_watch_prepare (GSource *source,
3599 return check_for_child_exited (source);
3604 g_child_watch_check (GSource *source)
3606 return check_for_child_exited (source);
3609 #endif /* G_OS_WIN32 */
3612 g_child_watch_dispatch (GSource *source,
3613 GSourceFunc callback,
3616 GChildWatchSource *child_watch_source;
3617 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
3619 child_watch_source = (GChildWatchSource *) source;
3623 g_warning ("Child watch source dispatched without callback\n"
3624 "You must call g_source_set_callback().");
3628 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
3630 /* We never keep a child watch source around as the child is gone */
3637 g_child_watch_signal_handler (int signum)
3639 child_watch_count ++;
3641 if (child_watch_init_state == CHILD_WATCH_INITIALIZED_THREADED)
3643 write (child_watch_wake_up_pipe[1], "B", 1);
3647 /* We count on the signal interrupting the poll in the same thread.
3653 g_child_watch_source_init_single (void)
3655 struct sigaction action;
3657 g_assert (! g_thread_supported());
3658 g_assert (child_watch_init_state == CHILD_WATCH_UNINITIALIZED);
3660 child_watch_init_state = CHILD_WATCH_INITIALIZED_SINGLE;
3662 action.sa_handler = g_child_watch_signal_handler;
3663 sigemptyset (&action.sa_mask);
3664 action.sa_flags = SA_NOCLDSTOP;
3665 sigaction (SIGCHLD, &action, NULL);
3668 G_GNUC_NORETURN static gpointer
3669 child_watch_helper_thread (gpointer data)
3676 read (child_watch_wake_up_pipe[0], b, 20);
3678 /* We were woken up. Wake up all other contexts in all other threads */
3679 G_LOCK (main_context_list);
3680 for (list = main_context_list; list; list = list->next)
3682 GMainContext *context;
3684 context = list->data;
3685 if (g_atomic_int_get (&context->ref_count) > 0)
3686 /* Due to racing conditions we can find ref_count == 0, in
3687 * that case, however, the context is still not destroyed
3688 * and no poll can be active, otherwise the ref_count
3690 g_main_context_wakeup (context);
3692 G_UNLOCK (main_context_list);
3697 g_child_watch_source_init_multi_threaded (void)
3699 GError *error = NULL;
3700 struct sigaction action;
3702 g_assert (g_thread_supported());
3704 if (pipe (child_watch_wake_up_pipe) < 0)
3705 g_error ("Cannot create wake up pipe: %s\n", g_strerror (errno));
3706 fcntl (child_watch_wake_up_pipe[1], F_SETFL, O_NONBLOCK | fcntl (child_watch_wake_up_pipe[1], F_GETFL));
3708 /* We create a helper thread that polls on the wakeup pipe indefinitely */
3709 /* FIXME: Think this through for races */
3710 if (g_thread_create (child_watch_helper_thread, NULL, FALSE, &error) == NULL)
3711 g_error ("Cannot create a thread to monitor child exit status: %s\n", error->message);
3712 child_watch_init_state = CHILD_WATCH_INITIALIZED_THREADED;
3714 action.sa_handler = g_child_watch_signal_handler;
3715 sigemptyset (&action.sa_mask);
3716 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
3717 sigaction (SIGCHLD, &action, NULL);
3721 g_child_watch_source_init_promote_single_to_threaded (void)
3723 g_child_watch_source_init_multi_threaded ();
3727 g_child_watch_source_init (void)
3729 if (g_thread_supported())
3731 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
3732 g_child_watch_source_init_multi_threaded ();
3733 else if (child_watch_init_state == CHILD_WATCH_INITIALIZED_SINGLE)
3734 g_child_watch_source_init_promote_single_to_threaded ();
3738 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
3739 g_child_watch_source_init_single ();
3743 #endif /* !G_OS_WIN32 */
3746 * g_child_watch_source_new:
3747 * @pid: process to watch. On POSIX the pid of a child process. On
3748 * Windows a handle for a process (which doesn't have to be a child).
3750 * Creates a new child_watch source.
3752 * The source will not initially be associated with any #GMainContext
3753 * and must be added to one with g_source_attach() before it will be
3756 * Note that child watch sources can only be used in conjunction with
3757 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
3760 * Note that on platforms where #GPid must be explicitly closed
3761 * (see g_spawn_close_pid()) @pid must not be closed while the
3762 * source is still active. Typically, you will want to call
3763 * g_spawn_close_pid() in the callback function for the source.
3765 * Note further that using g_child_watch_source_new() is not
3766 * compatible with calling <literal>waitpid(-1)</literal> in
3767 * the application. Calling waitpid() for individual pids will
3770 * Return value: the newly-created child watch source
3775 g_child_watch_source_new (GPid pid)
3777 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
3778 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
3781 child_watch_source->poll.fd = (gintptr) pid;
3782 child_watch_source->poll.events = G_IO_IN;
3784 g_source_add_poll (source, &child_watch_source->poll);
3785 #else /* G_OS_WIN32 */
3786 g_child_watch_source_init ();
3787 #endif /* G_OS_WIN32 */
3789 child_watch_source->pid = pid;
3795 * g_child_watch_add_full:
3796 * @priority: the priority of the idle source. Typically this will be in the
3797 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3798 * @pid: process to watch. On POSIX the pid of a child process. On
3799 * Windows a handle for a process (which doesn't have to be a child).
3800 * @function: function to call
3801 * @data: data to pass to @function
3802 * @notify: function to call when the idle is removed, or %NULL
3804 * Sets a function to be called when the child indicated by @pid
3805 * exits, at the priority @priority.
3807 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
3808 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
3809 * the spawn function for the child watching to work.
3811 * Note that on platforms where #GPid must be explicitly closed
3812 * (see g_spawn_close_pid()) @pid must not be closed while the
3813 * source is still active. Typically, you will want to call
3814 * g_spawn_close_pid() in the callback function for the source.
3816 * GLib supports only a single callback per process id.
3818 * This internally creates a main loop source using
3819 * g_child_watch_source_new() and attaches it to the main loop context
3820 * using g_source_attach(). You can do these steps manually if you
3821 * need greater control.
3823 * Return value: the ID (greater than 0) of the event source.
3828 g_child_watch_add_full (gint priority,
3830 GChildWatchFunc function,
3832 GDestroyNotify notify)
3837 g_return_val_if_fail (function != NULL, 0);
3839 source = g_child_watch_source_new (pid);
3841 if (priority != G_PRIORITY_DEFAULT)
3842 g_source_set_priority (source, priority);
3844 g_source_set_callback (source, (GSourceFunc) function, data, notify);
3845 id = g_source_attach (source, NULL);
3846 g_source_unref (source);
3852 * g_child_watch_add:
3853 * @pid: process id to watch. On POSIX the pid of a child process. On
3854 * Windows a handle for a process (which doesn't have to be a child).
3855 * @function: function to call
3856 * @data: data to pass to @function
3858 * Sets a function to be called when the child indicated by @pid
3859 * exits, at a default priority, #G_PRIORITY_DEFAULT.
3861 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
3862 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
3863 * the spawn function for the child watching to work.
3865 * Note that on platforms where #GPid must be explicitly closed
3866 * (see g_spawn_close_pid()) @pid must not be closed while the
3867 * source is still active. Typically, you will want to call
3868 * g_spawn_close_pid() in the callback function for the source.
3870 * GLib supports only a single callback per process id.
3872 * This internally creates a main loop source using
3873 * g_child_watch_source_new() and attaches it to the main loop context
3874 * using g_source_attach(). You can do these steps manually if you
3875 * need greater control.
3877 * Return value: the ID (greater than 0) of the event source.
3882 g_child_watch_add (GPid pid,
3883 GChildWatchFunc function,
3886 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
3890 /* Idle functions */
3893 g_idle_prepare (GSource *source,
3902 g_idle_check (GSource *source)
3908 g_idle_dispatch (GSource *source,
3909 GSourceFunc callback,
3914 g_warning ("Idle source dispatched without callback\n"
3915 "You must call g_source_set_callback().");
3919 return callback (user_data);
3923 * g_idle_source_new:
3925 * Creates a new idle source.
3927 * The source will not initially be associated with any #GMainContext
3928 * and must be added to one with g_source_attach() before it will be
3929 * executed. Note that the default priority for idle sources is
3930 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
3931 * have a default priority of %G_PRIORITY_DEFAULT.
3933 * Return value: the newly-created idle source
3936 g_idle_source_new (void)
3940 source = g_source_new (&g_idle_funcs, sizeof (GSource));
3941 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
3948 * @priority: the priority of the idle source. Typically this will be in the
3949 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3950 * @function: function to call
3951 * @data: data to pass to @function
3952 * @notify: function to call when the idle is removed, or %NULL
3954 * Adds a function to be called whenever there are no higher priority
3955 * events pending. If the function returns %FALSE it is automatically
3956 * removed from the list of event sources and will not be called again.
3958 * This internally creates a main loop source using g_idle_source_new()
3959 * and attaches it to the main loop context using g_source_attach().
3960 * You can do these steps manually if you need greater control.
3962 * Return value: the ID (greater than 0) of the event source.
3965 g_idle_add_full (gint priority,
3966 GSourceFunc function,
3968 GDestroyNotify notify)
3973 g_return_val_if_fail (function != NULL, 0);
3975 source = g_idle_source_new ();
3977 if (priority != G_PRIORITY_DEFAULT_IDLE)
3978 g_source_set_priority (source, priority);
3980 g_source_set_callback (source, function, data, notify);
3981 id = g_source_attach (source, NULL);
3982 g_source_unref (source);
3989 * @function: function to call
3990 * @data: data to pass to @function.
3992 * Adds a function to be called whenever there are no higher priority
3993 * events pending to the default main loop. The function is given the
3994 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
3995 * returns %FALSE it is automatically removed from the list of event
3996 * sources and will not be called again.
3998 * This internally creates a main loop source using g_idle_source_new()
3999 * and attaches it to the main loop context using g_source_attach().
4000 * You can do these steps manually if you need greater control.
4002 * Return value: the ID (greater than 0) of the event source.
4005 g_idle_add (GSourceFunc function,
4008 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4012 * g_idle_remove_by_data:
4013 * @data: the data for the idle source's callback.
4015 * Removes the idle function with the given data.
4017 * Return value: %TRUE if an idle source was found and removed.
4020 g_idle_remove_by_data (gpointer data)
4022 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4025 #define __G_MAIN_C__
4026 #include "galiasdef.c"