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 to enable debugging printouts if the
37 * environment variable G_MAIN_POLL_DEBUG is set to some value.
39 /* #define G_MAIN_POLL_DEBUG */
42 /* Always enable debugging printout on Windows, as it is more often
45 #define G_MAIN_POLL_DEBUG
49 #include "gthreadprivate.h"
51 #include <sys/types.h>
54 #ifdef HAVE_SYS_TIME_H
56 #endif /* HAVE_SYS_TIME_H */
57 #ifdef GLIB_HAVE_SYS_POLL_H
58 # include <sys/poll.h>
59 # undef events /* AIX 4.1.5 & 4.3.2 define this for SVR3,4 compatibility */
60 # undef revents /* AIX 4.1.5 & 4.3.2 define this for SVR3,4 compatibility */
62 /* The poll() emulation on OS/X doesn't handle fds=NULL, nfds=0,
63 * so we prefer our own poll emulation.
65 #if defined(_POLL_EMUL_H_) || defined(BROKEN_POLL)
69 #endif /* GLIB_HAVE_SYS_POLL_H */
72 #endif /* HAVE_UNISTD_H */
78 #endif /* G_OS_WIN32 */
81 #include <sys/socket.h>
83 #endif /* G_OS_BEOS */
92 #ifdef G_MAIN_POLL_DEBUG
94 #define GPOLLFD_FORMAT "%#x"
96 #define GPOLLFD_FORMAT "%d"
102 typedef struct _GTimeoutSource GTimeoutSource;
103 typedef struct _GChildWatchSource GChildWatchSource;
104 typedef struct _GPollRec GPollRec;
105 typedef struct _GSourceCallback GSourceCallback;
109 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
110 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
113 #ifdef G_THREADS_ENABLED
114 typedef struct _GMainWaiter GMainWaiter;
123 typedef struct _GMainDispatch GMainDispatch;
125 struct _GMainDispatch
128 GSList *dispatching_sources; /* stack of current sources */
131 #ifdef G_MAIN_POLL_DEBUG
132 static gboolean g_main_poll_debug = FALSE;
137 #ifdef G_THREADS_ENABLED
138 /* The following lock is used for both the list of sources
139 * and the list of poll records
150 GPtrArray *pending_dispatches;
151 gint timeout; /* Timeout for current iteration */
154 GSource *source_list;
155 gint in_check_or_prepare;
157 GPollRec *poll_records;
158 guint n_poll_records;
159 GPollFD *cached_poll_array;
160 guint cached_poll_array_size;
162 #ifdef G_THREADS_ENABLED
164 /* this pipe is used to wake up the main loop when a source is added.
166 gint wake_up_pipe[2];
167 #else /* G_OS_WIN32 */
168 HANDLE wake_up_semaphore;
169 #endif /* G_OS_WIN32 */
172 gboolean poll_waiting;
174 /* Flag indicating whether the set of fd's changed during a poll */
175 gboolean poll_changed;
176 #endif /* G_THREADS_ENABLED */
180 GTimeVal current_time;
181 gboolean time_is_current;
184 struct _GSourceCallback
189 GDestroyNotify notify;
194 GMainContext *context;
199 struct _GTimeoutSource
207 struct _GChildWatchSource
214 #else /* G_OS_WIN32 */
216 gboolean child_exited;
217 #endif /* G_OS_WIN32 */
227 #ifdef G_THREADS_ENABLED
228 #define LOCK_CONTEXT(context) g_static_mutex_lock (&context->mutex)
229 #define UNLOCK_CONTEXT(context) g_static_mutex_unlock (&context->mutex)
230 #define G_THREAD_SELF g_thread_self ()
232 #define LOCK_CONTEXT(context) (void)0
233 #define UNLOCK_CONTEXT(context) (void)0
234 #define G_THREAD_SELF NULL
237 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
238 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
239 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
241 #define SOURCE_UNREF(source, context) \
243 if ((source)->ref_count > 1) \
244 (source)->ref_count--; \
246 g_source_unref_internal ((source), (context), TRUE); \
250 /* Forward declarations */
252 static void g_source_unref_internal (GSource *source,
253 GMainContext *context,
255 static void g_source_destroy_internal (GSource *source,
256 GMainContext *context,
258 static void g_main_context_poll (GMainContext *context,
263 static void g_main_context_add_poll_unlocked (GMainContext *context,
266 static void g_main_context_remove_poll_unlocked (GMainContext *context,
268 static void g_main_context_wakeup_unlocked (GMainContext *context);
270 static gboolean g_timeout_prepare (GSource *source,
272 static gboolean g_timeout_check (GSource *source);
273 static gboolean g_timeout_dispatch (GSource *source,
274 GSourceFunc callback,
276 static gboolean g_child_watch_prepare (GSource *source,
278 static gboolean g_child_watch_check (GSource *source);
279 static gboolean g_child_watch_dispatch (GSource *source,
280 GSourceFunc callback,
282 static gboolean g_idle_prepare (GSource *source,
284 static gboolean g_idle_check (GSource *source);
285 static gboolean g_idle_dispatch (GSource *source,
286 GSourceFunc callback,
289 G_LOCK_DEFINE_STATIC (main_loop);
290 static GMainContext *default_main_context;
291 static GSList *main_contexts_without_pipe = NULL;
294 /* Child status monitoring code */
296 CHILD_WATCH_UNINITIALIZED,
297 CHILD_WATCH_INITIALIZED_SINGLE,
298 CHILD_WATCH_INITIALIZED_THREADED
300 static gint child_watch_init_state = CHILD_WATCH_UNINITIALIZED;
301 static gint child_watch_count = 1;
302 static gint child_watch_wake_up_pipe[2] = {0, 0};
303 #endif /* !G_OS_WIN32 */
304 G_LOCK_DEFINE_STATIC (main_context_list);
305 static GSList *main_context_list = NULL;
307 static gint timer_perturb = -1;
309 GSourceFuncs g_timeout_funcs =
317 GSourceFuncs g_child_watch_funcs =
319 g_child_watch_prepare,
321 g_child_watch_dispatch,
325 GSourceFuncs g_idle_funcs =
334 /* SunOS has poll, but doesn't provide a prototype. */
335 # if defined (sun) && !defined (__SVR4)
336 extern gint poll (GPollFD *ufds, guint nfsd, gint timeout);
338 #else /* !HAVE_POLL */
343 g_poll (GPollFD *fds,
347 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
348 gboolean poll_msgs = FALSE;
354 #ifdef G_MAIN_POLL_DEBUG
355 if (g_main_poll_debug)
356 g_print ("g_poll: waiting for");
358 for (f = fds; f < &fds[nfds]; ++f)
361 if (f->fd == G_WIN32_MSG_HANDLE)
364 #ifdef G_MAIN_POLL_DEBUG
365 if (g_main_poll_debug)
369 else if (nhandles == MAXIMUM_WAIT_OBJECTS)
371 g_warning (G_STRLOC ": Too many handles to wait for!\n");
376 #ifdef G_MAIN_POLL_DEBUG
377 if (g_main_poll_debug)
378 g_print (" %#x", f->fd);
380 handles[nhandles++] = (HANDLE) f->fd;
383 #ifdef G_MAIN_POLL_DEBUG
384 if (g_main_poll_debug)
393 /* Waiting for messages, and maybe events
394 * -> First PeekMessage
396 #ifdef G_MAIN_POLL_DEBUG
397 if (g_main_poll_debug)
398 g_print ("PeekMessage\n");
400 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
401 ready = WAIT_OBJECT_0 + nhandles;
404 /* Wait for either message or event
405 * -> Use MsgWaitForMultipleObjectsEx
407 #ifdef G_MAIN_POLL_DEBUG
408 if (g_main_poll_debug)
409 g_print ("MsgWaitForMultipleObjectsEx(%d, %d)\n", nhandles, timeout);
411 ready = MsgWaitForMultipleObjectsEx (nhandles, handles, timeout,
412 QS_ALLINPUT, MWMO_ALERTABLE);
414 if (ready == WAIT_FAILED)
416 gchar *emsg = g_win32_error_message (GetLastError ());
417 g_warning (G_STRLOC ": MsgWaitForMultipleObjectsEx() failed: %s", emsg);
422 else if (nhandles == 0)
424 /* No handles to wait for, just the timeout */
425 if (timeout == INFINITE)
429 SleepEx (timeout, TRUE);
430 ready = WAIT_TIMEOUT;
435 /* Wait for just events
436 * -> Use WaitForMultipleObjectsEx
438 #ifdef G_MAIN_POLL_DEBUG
439 if (g_main_poll_debug)
440 g_print ("WaitForMultipleObjectsEx(%d, %d)\n", nhandles, timeout);
442 ready = WaitForMultipleObjectsEx (nhandles, handles, FALSE, timeout, TRUE);
443 if (ready == WAIT_FAILED)
445 gchar *emsg = g_win32_error_message (GetLastError ());
446 g_warning (G_STRLOC ": WaitForMultipleObjectsEx() failed: %s", emsg);
451 #ifdef G_MAIN_POLL_DEBUG
452 if (g_main_poll_debug)
453 g_print ("wait returns %ld%s\n",
455 (ready == WAIT_FAILED ? " (WAIT_FAILED)" :
456 (ready == WAIT_TIMEOUT ? " (WAIT_TIMEOUT)" :
457 (poll_msgs && ready == WAIT_OBJECT_0 + nhandles ? " (msg)" : ""))));
459 for (f = fds; f < &fds[nfds]; ++f)
462 if (ready == WAIT_FAILED)
464 else if (ready == WAIT_TIMEOUT ||
465 ready == WAIT_IO_COMPLETION)
467 else if (poll_msgs && ready == WAIT_OBJECT_0 + nhandles)
469 for (f = fds; f < &fds[nfds]; ++f)
472 if (f->events & G_IO_IN)
473 if (f->fd == G_WIN32_MSG_HANDLE)
474 f->revents |= G_IO_IN;
477 else if (ready >= WAIT_OBJECT_0 && ready < WAIT_OBJECT_0 + nhandles)
478 for (f = fds; f < &fds[nfds]; ++f)
480 if (f->fd == (gint) handles[ready - WAIT_OBJECT_0])
482 f->revents = f->events;
483 #ifdef G_MAIN_POLL_DEBUG
484 if (g_main_poll_debug)
485 g_print ("g_poll: got event %#x\n", f->fd);
493 #else /* !G_OS_WIN32 */
495 /* The following implementation of poll() comes from the GNU C Library.
496 * Copyright (C) 1994, 1996, 1997 Free Software Foundation, Inc.
499 #include <string.h> /* for bzero on BSD systems */
501 #ifdef HAVE_SYS_SELECT_H
502 #include <sys/select.h>
503 #endif /* HAVE_SYS_SELECT_H */
507 #endif /* G_OS_BEOS */
510 # define SELECT_MASK fd_set
511 #else /* !NO_FD_SET */
513 typedef long fd_mask;
516 # define SELECT_MASK void
518 # define SELECT_MASK int
519 # endif /* !_IBMR2 */
520 #endif /* !NO_FD_SET */
523 g_poll (GPollFD *fds,
528 SELECT_MASK rset, wset, xset;
537 for (f = fds; f < &fds[nfds]; ++f)
540 if (f->events & G_IO_IN)
541 FD_SET (f->fd, &rset);
542 if (f->events & G_IO_OUT)
543 FD_SET (f->fd, &wset);
544 if (f->events & G_IO_PRI)
545 FD_SET (f->fd, &xset);
546 if (f->fd > maxfd && (f->events & (G_IO_IN|G_IO_OUT|G_IO_PRI)))
550 tv.tv_sec = timeout / 1000;
551 tv.tv_usec = (timeout % 1000) * 1000;
553 ready = select (maxfd + 1, &rset, &wset, &xset,
554 timeout == -1 ? NULL : &tv);
556 for (f = fds; f < &fds[nfds]; ++f)
561 if (FD_ISSET (f->fd, &rset))
562 f->revents |= G_IO_IN;
563 if (FD_ISSET (f->fd, &wset))
564 f->revents |= G_IO_OUT;
565 if (FD_ISSET (f->fd, &xset))
566 f->revents |= G_IO_PRI;
573 #endif /* !G_OS_WIN32 */
575 #endif /* !HAVE_POLL */
578 * g_main_context_ref:
579 * @context: a #GMainContext
581 * Increases the reference count on a #GMainContext object by one.
583 * Returns: the @context that was passed in (since 2.6)
586 g_main_context_ref (GMainContext *context)
588 g_return_val_if_fail (context != NULL, NULL);
589 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
591 g_atomic_int_inc (&context->ref_count);
597 poll_rec_list_free (GMainContext *context,
600 g_slice_free_chain (GPollRec, list, next);
604 * g_main_context_unref:
605 * @context: a #GMainContext
607 * Decreases the reference count on a #GMainContext object by one. If
608 * the result is zero, free the context and free all associated memory.
611 g_main_context_unref (GMainContext *context)
614 g_return_if_fail (context != NULL);
615 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
617 if (!g_atomic_int_dec_and_test (&context->ref_count))
620 G_LOCK (main_context_list);
621 main_context_list = g_slist_remove (main_context_list, context);
622 G_UNLOCK (main_context_list);
624 source = context->source_list;
627 GSource *next = source->next;
628 g_source_destroy_internal (source, context, FALSE);
632 #ifdef G_THREADS_ENABLED
633 g_static_mutex_free (&context->mutex);
636 g_ptr_array_free (context->pending_dispatches, TRUE);
637 g_free (context->cached_poll_array);
639 poll_rec_list_free (context, context->poll_records);
641 #ifdef G_THREADS_ENABLED
642 if (g_thread_supported())
645 close (context->wake_up_pipe[0]);
646 close (context->wake_up_pipe[1]);
648 CloseHandle (context->wake_up_semaphore);
652 main_contexts_without_pipe = g_slist_remove (main_contexts_without_pipe,
655 if (context->cond != NULL)
656 g_cond_free (context->cond);
662 #ifdef G_THREADS_ENABLED
664 g_main_context_init_pipe (GMainContext *context)
667 if (context->wake_up_pipe[0] != -1)
669 if (pipe (context->wake_up_pipe) < 0)
670 g_error ("Cannot create pipe main loop wake-up: %s\n",
673 fcntl (context->wake_up_pipe[0], F_SETFD, FD_CLOEXEC);
674 fcntl (context->wake_up_pipe[1], F_SETFD, FD_CLOEXEC);
676 context->wake_up_rec.fd = context->wake_up_pipe[0];
677 context->wake_up_rec.events = G_IO_IN;
679 if (context->wake_up_semaphore != NULL)
681 context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
682 if (context->wake_up_semaphore == NULL)
683 g_error ("Cannot create wake-up semaphore: %s",
684 g_win32_error_message (GetLastError ()));
685 context->wake_up_rec.fd = (gint) context->wake_up_semaphore;
686 context->wake_up_rec.events = G_IO_IN;
687 # ifdef G_MAIN_POLL_DEBUG
688 if (g_main_poll_debug)
689 g_print ("wake-up semaphore: %#x\n", (guint) context->wake_up_semaphore);
692 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
696 _g_main_thread_init (void)
698 GSList *curr = main_contexts_without_pipe;
701 g_main_context_init_pipe ((GMainContext *)curr->data);
704 g_slist_free (main_contexts_without_pipe);
705 main_contexts_without_pipe = NULL;
707 #endif /* G_THREADS_ENABLED */
710 * g_main_context_new:
712 * Creates a new #GMainContext structure.
714 * Return value: the new #GMainContext
717 g_main_context_new (void)
719 GMainContext *context = g_new0 (GMainContext, 1);
721 #ifdef G_THREADS_ENABLED
722 g_static_mutex_init (&context->mutex);
724 context->owner = NULL;
725 context->waiters = NULL;
728 context->wake_up_pipe[0] = -1;
729 context->wake_up_pipe[1] = -1;
731 context->wake_up_semaphore = NULL;
735 context->ref_count = 1;
737 context->next_id = 1;
739 context->source_list = NULL;
742 context->poll_func = (GPollFunc)poll;
744 context->poll_func = g_poll;
747 context->cached_poll_array = NULL;
748 context->cached_poll_array_size = 0;
750 context->pending_dispatches = g_ptr_array_new ();
752 context->time_is_current = FALSE;
754 #ifdef G_THREADS_ENABLED
755 if (g_thread_supported ())
756 g_main_context_init_pipe (context);
758 main_contexts_without_pipe = g_slist_prepend (main_contexts_without_pipe,
762 G_LOCK (main_context_list);
763 main_context_list = g_slist_append (main_context_list, context);
765 #ifdef G_MAIN_POLL_DEBUG
766 if (g_main_poll_debug)
767 g_print ("created context=%p\n", context);
770 G_UNLOCK (main_context_list);
776 * g_main_context_default:
778 * Returns the default main context. This is the main context used
779 * for main loop functions when a main loop is not explicitly
782 * Return value: the default main context.
785 g_main_context_default (void)
791 if (!default_main_context)
793 default_main_context = g_main_context_new ();
794 #ifdef G_MAIN_POLL_DEBUG
795 if (g_main_poll_debug)
796 g_print ("default context=%p\n", default_main_context);
800 G_UNLOCK (main_loop);
802 return default_main_context;
805 /* Hooks for adding to the main loop */
809 * @source_funcs: structure containing functions that implement
810 * the sources behavior.
811 * @struct_size: size of the #GSource structure to create.
813 * Creates a new #GSource structure. The size is specified to
814 * allow creating structures derived from #GSource that contain
815 * additional data. The size passed in must be at least
816 * <literal>sizeof (GSource)</literal>.
818 * The source will not initially be associated with any #GMainContext
819 * and must be added to one with g_source_attach() before it will be
822 * Return value: the newly-created #GSource.
825 g_source_new (GSourceFuncs *source_funcs,
830 g_return_val_if_fail (source_funcs != NULL, NULL);
831 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
833 source = (GSource*) g_malloc0 (struct_size);
835 source->source_funcs = source_funcs;
836 source->ref_count = 1;
838 source->priority = G_PRIORITY_DEFAULT;
840 source->flags = G_HOOK_FLAG_ACTIVE;
842 /* NULL/0 initialization for all other fields */
847 /* Holds context's lock
850 g_source_list_add (GSource *source,
851 GMainContext *context)
853 GSource *tmp_source, *last_source;
856 tmp_source = context->source_list;
857 while (tmp_source && tmp_source->priority <= source->priority)
859 last_source = tmp_source;
860 tmp_source = tmp_source->next;
863 source->next = tmp_source;
865 tmp_source->prev = source;
867 source->prev = last_source;
869 last_source->next = source;
871 context->source_list = source;
874 /* Holds context's lock
877 g_source_list_remove (GSource *source,
878 GMainContext *context)
881 source->prev->next = source->next;
883 context->source_list = source->next;
886 source->next->prev = source->prev;
894 * @source: a #GSource
895 * @context: a #GMainContext (if %NULL, the default context will be used)
897 * Adds a #GSource to a @context so that it will be executed within
900 * Return value: the ID (greater than 0) for the source within the
904 g_source_attach (GSource *source,
905 GMainContext *context)
910 g_return_val_if_fail (source->context == NULL, 0);
911 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
914 context = g_main_context_default ();
916 LOCK_CONTEXT (context);
918 source->context = context;
919 result = source->source_id = context->next_id++;
922 g_source_list_add (source, context);
924 tmp_list = source->poll_fds;
927 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
928 tmp_list = tmp_list->next;
931 #ifdef G_THREADS_ENABLED
932 /* Now wake up the main loop if it is waiting in the poll() */
933 g_main_context_wakeup_unlocked (context);
936 UNLOCK_CONTEXT (context);
942 g_source_destroy_internal (GSource *source,
943 GMainContext *context,
947 LOCK_CONTEXT (context);
949 if (!SOURCE_DESTROYED (source))
952 gpointer old_cb_data;
953 GSourceCallbackFuncs *old_cb_funcs;
955 source->flags &= ~G_HOOK_FLAG_ACTIVE;
957 old_cb_data = source->callback_data;
958 old_cb_funcs = source->callback_funcs;
960 source->callback_data = NULL;
961 source->callback_funcs = NULL;
965 UNLOCK_CONTEXT (context);
966 old_cb_funcs->unref (old_cb_data);
967 LOCK_CONTEXT (context);
970 if (!SOURCE_BLOCKED (source))
972 tmp_list = source->poll_fds;
975 g_main_context_remove_poll_unlocked (context, tmp_list->data);
976 tmp_list = tmp_list->next;
980 g_source_unref_internal (source, context, TRUE);
984 UNLOCK_CONTEXT (context);
989 * @source: a #GSource
991 * Removes a source from its #GMainContext, if any, and mark it as
992 * destroyed. The source cannot be subsequently added to another
996 g_source_destroy (GSource *source)
998 GMainContext *context;
1000 g_return_if_fail (source != NULL);
1002 context = source->context;
1005 g_source_destroy_internal (source, context, FALSE);
1007 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1012 * @source: a #GSource
1014 * Returns the numeric ID for a particular source. The ID of a source
1015 * is a positive integer which is unique within a particular main loop
1016 * context. The reverse
1017 * mapping from ID to source is done by g_main_context_find_source_by_id().
1019 * Return value: the ID (greater than 0) for the source
1022 g_source_get_id (GSource *source)
1026 g_return_val_if_fail (source != NULL, 0);
1027 g_return_val_if_fail (source->context != NULL, 0);
1029 LOCK_CONTEXT (source->context);
1030 result = source->source_id;
1031 UNLOCK_CONTEXT (source->context);
1037 * g_source_get_context:
1038 * @source: a #GSource
1040 * Gets the #GMainContext with which the source is associated.
1041 * Calling this function on a destroyed source is an error.
1043 * Return value: the #GMainContext with which the source is associated,
1044 * or %NULL if the context has not yet been added
1048 g_source_get_context (GSource *source)
1050 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1052 return source->context;
1056 * g_source_add_poll:
1057 * @source:a #GSource
1058 * @fd: a #GPollFD structure holding information about a file
1059 * descriptor to watch.
1061 * Adds a file descriptor to the set of file descriptors polled for
1062 * this source. This is usually combined with g_source_new() to add an
1063 * event source. The event source's check function will typically test
1064 * the @revents field in the #GPollFD struct and return %TRUE if events need
1068 g_source_add_poll (GSource *source,
1071 GMainContext *context;
1073 g_return_if_fail (source != NULL);
1074 g_return_if_fail (fd != NULL);
1075 g_return_if_fail (!SOURCE_DESTROYED (source));
1077 context = source->context;
1080 LOCK_CONTEXT (context);
1082 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1086 if (!SOURCE_BLOCKED (source))
1087 g_main_context_add_poll_unlocked (context, source->priority, fd);
1088 UNLOCK_CONTEXT (context);
1093 * g_source_remove_poll:
1094 * @source:a #GSource
1095 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1097 * Removes a file descriptor from the set of file descriptors polled for
1101 g_source_remove_poll (GSource *source,
1104 GMainContext *context;
1106 g_return_if_fail (source != NULL);
1107 g_return_if_fail (fd != NULL);
1108 g_return_if_fail (!SOURCE_DESTROYED (source));
1110 context = source->context;
1113 LOCK_CONTEXT (context);
1115 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1119 if (!SOURCE_BLOCKED (source))
1120 g_main_context_remove_poll_unlocked (context, fd);
1121 UNLOCK_CONTEXT (context);
1126 * g_source_set_callback_indirect:
1127 * @source: the source
1128 * @callback_data: pointer to callback data "object"
1129 * @callback_funcs: functions for reference counting @callback_data
1130 * and getting the callback and data
1132 * Sets the callback function storing the data as a refcounted callback
1133 * "object". This is used internally. Note that calling
1134 * g_source_set_callback_indirect() assumes
1135 * an initial reference count on @callback_data, and thus
1136 * @callback_funcs->unref will eventually be called once more
1137 * than @callback_funcs->ref.
1140 g_source_set_callback_indirect (GSource *source,
1141 gpointer callback_data,
1142 GSourceCallbackFuncs *callback_funcs)
1144 GMainContext *context;
1145 gpointer old_cb_data;
1146 GSourceCallbackFuncs *old_cb_funcs;
1148 g_return_if_fail (source != NULL);
1149 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1151 context = source->context;
1154 LOCK_CONTEXT (context);
1156 old_cb_data = source->callback_data;
1157 old_cb_funcs = source->callback_funcs;
1159 source->callback_data = callback_data;
1160 source->callback_funcs = callback_funcs;
1163 UNLOCK_CONTEXT (context);
1166 old_cb_funcs->unref (old_cb_data);
1170 g_source_callback_ref (gpointer cb_data)
1172 GSourceCallback *callback = cb_data;
1174 callback->ref_count++;
1179 g_source_callback_unref (gpointer cb_data)
1181 GSourceCallback *callback = cb_data;
1183 callback->ref_count--;
1184 if (callback->ref_count == 0)
1186 if (callback->notify)
1187 callback->notify (callback->data);
1193 g_source_callback_get (gpointer cb_data,
1198 GSourceCallback *callback = cb_data;
1200 *func = callback->func;
1201 *data = callback->data;
1204 static GSourceCallbackFuncs g_source_callback_funcs = {
1205 g_source_callback_ref,
1206 g_source_callback_unref,
1207 g_source_callback_get,
1211 * g_source_set_callback:
1212 * @source: the source
1213 * @func: a callback function
1214 * @data: the data to pass to callback function
1215 * @notify: a function to call when @data is no longer in use, or %NULL.
1217 * Sets the callback function for a source. The callback for a source is
1218 * called from the source's dispatch function.
1220 * The exact type of @func depends on the type of source; ie. you
1221 * should not count on @func being called with @data as its first
1224 * Typically, you won't use this function. Instead use functions specific
1225 * to the type of source you are using.
1228 g_source_set_callback (GSource *source,
1231 GDestroyNotify notify)
1233 GSourceCallback *new_callback;
1235 g_return_if_fail (source != NULL);
1237 new_callback = g_new (GSourceCallback, 1);
1239 new_callback->ref_count = 1;
1240 new_callback->func = func;
1241 new_callback->data = data;
1242 new_callback->notify = notify;
1244 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1249 * g_source_set_funcs:
1250 * @source: a #GSource
1251 * @funcs: the new #GSourceFuncs
1253 * Sets the source functions (can be used to override
1254 * default implementations) of an unattached source.
1259 g_source_set_funcs (GSource *source,
1260 GSourceFuncs *funcs)
1262 g_return_if_fail (source != NULL);
1263 g_return_if_fail (source->context == NULL);
1264 g_return_if_fail (source->ref_count > 0);
1265 g_return_if_fail (funcs != NULL);
1267 source->source_funcs = funcs;
1271 * g_source_set_priority:
1272 * @source: a #GSource
1273 * @priority: the new priority.
1275 * Sets the priority of a source. While the main loop is being
1276 * run, a source will be dispatched if it is ready to be dispatched and no sources
1277 * at a higher (numerically smaller) priority are ready to be dispatched.
1280 g_source_set_priority (GSource *source,
1284 GMainContext *context;
1286 g_return_if_fail (source != NULL);
1288 context = source->context;
1291 LOCK_CONTEXT (context);
1293 source->priority = priority;
1297 /* Remove the source from the context's source and then
1298 * add it back so it is sorted in the correct plcae
1300 g_source_list_remove (source, source->context);
1301 g_source_list_add (source, source->context);
1303 if (!SOURCE_BLOCKED (source))
1305 tmp_list = source->poll_fds;
1308 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1309 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1311 tmp_list = tmp_list->next;
1315 UNLOCK_CONTEXT (source->context);
1320 * g_source_get_priority:
1321 * @source: a #GSource
1323 * Gets the priority of a source.
1325 * Return value: the priority of the source
1328 g_source_get_priority (GSource *source)
1330 g_return_val_if_fail (source != NULL, 0);
1332 return source->priority;
1336 * g_source_set_can_recurse:
1337 * @source: a #GSource
1338 * @can_recurse: whether recursion is allowed for this source
1340 * Sets whether a source can be called recursively. If @can_recurse is
1341 * %TRUE, then while the source is being dispatched then this source
1342 * will be processed normally. Otherwise, all processing of this
1343 * source is blocked until the dispatch function returns.
1346 g_source_set_can_recurse (GSource *source,
1347 gboolean can_recurse)
1349 GMainContext *context;
1351 g_return_if_fail (source != NULL);
1353 context = source->context;
1356 LOCK_CONTEXT (context);
1359 source->flags |= G_SOURCE_CAN_RECURSE;
1361 source->flags &= ~G_SOURCE_CAN_RECURSE;
1364 UNLOCK_CONTEXT (context);
1368 * g_source_get_can_recurse:
1369 * @source: a #GSource
1371 * Checks whether a source is allowed to be called recursively.
1372 * see g_source_set_can_recurse().
1374 * Return value: whether recursion is allowed.
1377 g_source_get_can_recurse (GSource *source)
1379 g_return_val_if_fail (source != NULL, FALSE);
1381 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1386 * @source: a #GSource
1388 * Increases the reference count on a source by one.
1390 * Return value: @source
1393 g_source_ref (GSource *source)
1395 GMainContext *context;
1397 g_return_val_if_fail (source != NULL, NULL);
1399 context = source->context;
1402 LOCK_CONTEXT (context);
1404 source->ref_count++;
1407 UNLOCK_CONTEXT (context);
1412 /* g_source_unref() but possible to call within context lock
1415 g_source_unref_internal (GSource *source,
1416 GMainContext *context,
1419 gpointer old_cb_data = NULL;
1420 GSourceCallbackFuncs *old_cb_funcs = NULL;
1422 g_return_if_fail (source != NULL);
1424 if (!have_lock && context)
1425 LOCK_CONTEXT (context);
1427 source->ref_count--;
1428 if (source->ref_count == 0)
1430 old_cb_data = source->callback_data;
1431 old_cb_funcs = source->callback_funcs;
1433 source->callback_data = NULL;
1434 source->callback_funcs = NULL;
1436 if (context && !SOURCE_DESTROYED (source))
1438 g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1439 source->ref_count++;
1442 g_source_list_remove (source, context);
1444 if (source->source_funcs->finalize)
1445 source->source_funcs->finalize (source);
1447 g_slist_free (source->poll_fds);
1448 source->poll_fds = NULL;
1452 if (!have_lock && context)
1453 UNLOCK_CONTEXT (context);
1458 UNLOCK_CONTEXT (context);
1460 old_cb_funcs->unref (old_cb_data);
1463 LOCK_CONTEXT (context);
1469 * @source: a #GSource
1471 * Decreases the reference count of a source by one. If the
1472 * resulting reference count is zero the source and associated
1473 * memory will be destroyed.
1476 g_source_unref (GSource *source)
1478 g_return_if_fail (source != NULL);
1480 g_source_unref_internal (source, source->context, FALSE);
1484 * g_main_context_find_source_by_id:
1485 * @context: a #GMainContext (if %NULL, the default context will be used)
1486 * @source_id: the source ID, as returned by g_source_get_id().
1488 * Finds a #GSource given a pair of context and ID.
1490 * Return value: the #GSource if found, otherwise, %NULL
1493 g_main_context_find_source_by_id (GMainContext *context,
1498 g_return_val_if_fail (source_id > 0, NULL);
1500 if (context == NULL)
1501 context = g_main_context_default ();
1503 LOCK_CONTEXT (context);
1505 source = context->source_list;
1508 if (!SOURCE_DESTROYED (source) &&
1509 source->source_id == source_id)
1511 source = source->next;
1514 UNLOCK_CONTEXT (context);
1520 * g_main_context_find_source_by_funcs_user_data:
1521 * @context: a #GMainContext (if %NULL, the default context will be used).
1522 * @funcs: the @source_funcs passed to g_source_new().
1523 * @user_data: the user data from the callback.
1525 * Finds a source with the given source functions and user data. If
1526 * multiple sources exist with the same source function and user data,
1527 * the first one found will be returned.
1529 * Return value: the source, if one was found, otherwise %NULL
1532 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1533 GSourceFuncs *funcs,
1538 g_return_val_if_fail (funcs != NULL, NULL);
1540 if (context == NULL)
1541 context = g_main_context_default ();
1543 LOCK_CONTEXT (context);
1545 source = context->source_list;
1548 if (!SOURCE_DESTROYED (source) &&
1549 source->source_funcs == funcs &&
1550 source->callback_funcs)
1552 GSourceFunc callback;
1553 gpointer callback_data;
1555 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1557 if (callback_data == user_data)
1560 source = source->next;
1563 UNLOCK_CONTEXT (context);
1569 * g_main_context_find_source_by_user_data:
1570 * @context: a #GMainContext
1571 * @user_data: the user_data for the callback.
1573 * Finds a source with the given user data for the callback. If
1574 * multiple sources exist with the same user data, the first
1575 * one found will be returned.
1577 * Return value: the source, if one was found, otherwise %NULL
1580 g_main_context_find_source_by_user_data (GMainContext *context,
1585 if (context == NULL)
1586 context = g_main_context_default ();
1588 LOCK_CONTEXT (context);
1590 source = context->source_list;
1593 if (!SOURCE_DESTROYED (source) &&
1594 source->callback_funcs)
1596 GSourceFunc callback;
1597 gpointer callback_data = NULL;
1599 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1601 if (callback_data == user_data)
1604 source = source->next;
1607 UNLOCK_CONTEXT (context);
1614 * @tag: the ID of the source to remove.
1616 * Removes the source with the given id from the default main context.
1618 * a #GSource is given by g_source_get_id(), or will be returned by the
1619 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1620 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1621 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1623 * See also g_source_destroy().
1625 * Return value: %TRUE if the source was found and removed.
1628 g_source_remove (guint tag)
1632 g_return_val_if_fail (tag > 0, FALSE);
1634 source = g_main_context_find_source_by_id (NULL, tag);
1636 g_source_destroy (source);
1638 return source != NULL;
1642 * g_source_remove_by_user_data:
1643 * @user_data: the user_data for the callback.
1645 * Removes a source from the default main loop context given the user
1646 * data for the callback. If multiple sources exist with the same user
1647 * data, only one will be destroyed.
1649 * Return value: %TRUE if a source was found and removed.
1652 g_source_remove_by_user_data (gpointer user_data)
1656 source = g_main_context_find_source_by_user_data (NULL, user_data);
1659 g_source_destroy (source);
1667 * g_source_remove_by_funcs_user_data:
1668 * @funcs: The @source_funcs passed to g_source_new()
1669 * @user_data: the user data for the callback
1671 * Removes a source from the default main loop context given the
1672 * source functions and user data. If multiple sources exist with the
1673 * same source functions and user data, only one will be destroyed.
1675 * Return value: %TRUE if a source was found and removed.
1678 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1683 g_return_val_if_fail (funcs != NULL, FALSE);
1685 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1688 g_source_destroy (source);
1696 * g_get_current_time:
1697 * @result: #GTimeVal structure in which to store current time.
1699 * Equivalent to the UNIX gettimeofday() function, but portable.
1702 g_get_current_time (GTimeVal *result)
1707 g_return_if_fail (result != NULL);
1709 /*this is required on alpha, there the timeval structs are int's
1710 not longs and a cast only would fail horribly*/
1711 gettimeofday (&r, NULL);
1712 result->tv_sec = r.tv_sec;
1713 result->tv_usec = r.tv_usec;
1716 guint64 *time64 = (guint64 *) &ft;
1718 g_return_if_fail (result != NULL);
1720 GetSystemTimeAsFileTime (&ft);
1722 /* Convert from 100s of nanoseconds since 1601-01-01
1723 * to Unix epoch. Yes, this is Y2038 unsafe.
1725 *time64 -= G_GINT64_CONSTANT (116444736000000000);
1728 result->tv_sec = *time64 / 1000000;
1729 result->tv_usec = *time64 % 1000000;
1734 g_main_dispatch_free (gpointer dispatch)
1736 g_slice_free (GMainDispatch, dispatch);
1739 /* Running the main loop */
1741 static GMainDispatch *
1744 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
1745 GMainDispatch *dispatch = g_static_private_get (&depth_private);
1748 dispatch = g_slice_new0 (GMainDispatch);
1749 g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
1758 * Returns the depth of the stack of calls to
1759 * g_main_context_dispatch() on any #GMainContext in the current thread.
1760 * That is, when called from the toplevel, it gives 0. When
1761 * called from within a callback from g_main_context_iteration()
1762 * (or g_main_loop_run(), etc.) it returns 1. When called from within
1763 * a callback to a recursive call to g_main_context_iterate(),
1764 * it returns 2. And so forth.
1766 * This function is useful in a situation like the following:
1767 * Imagine an extremely simple "garbage collected" system.
1770 * static GList *free_list;
1773 * allocate_memory (gsize size)
1775 * gpointer result = g_malloc (size);
1776 * free_list = g_list_prepend (free_list, result);
1781 * free_allocated_memory (void)
1784 * for (l = free_list; l; l = l->next);
1786 * g_list_free (free_list);
1794 * g_main_context_iteration (NULL, TRUE);
1795 * free_allocated_memory();
1799 * This works from an application, however, if you want to do the same
1800 * thing from a library, it gets more difficult, since you no longer
1801 * control the main loop. You might think you can simply use an idle
1802 * function to make the call to free_allocated_memory(), but that
1803 * doesn't work, since the idle function could be called from a
1804 * recursive callback. This can be fixed by using g_main_depth()
1808 * allocate_memory (gsize size)
1810 * FreeListBlock *block = g_new (FreeListBlock, 1);
1811 * block->mem = g_malloc (size);
1812 * block->depth = g_main_depth ();
1813 * free_list = g_list_prepend (free_list, block);
1814 * return block->mem;
1818 * free_allocated_memory (void)
1822 * int depth = g_main_depth ();
1823 * for (l = free_list; l; );
1825 * GList *next = l->next;
1826 * FreeListBlock *block = l->data;
1827 * if (block->depth > depth)
1829 * g_free (block->mem);
1831 * free_list = g_list_delete_link (free_list, l);
1839 * There is a temptation to use g_main_depth() to solve
1840 * problems with reentrancy. For instance, while waiting for data
1841 * to be received from the network in response to a menu item,
1842 * the menu item might be selected again. It might seem that
1843 * one could make the menu item's callback return immediately
1844 * and do nothing if g_main_depth() returns a value greater than 1.
1845 * However, this should be avoided since the user then sees selecting
1846 * the menu item do nothing. Furthermore, you'll find yourself adding
1847 * these checks all over your code, since there are doubtless many,
1848 * many things that the user could do. Instead, you can use the
1849 * following techniques:
1854 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
1855 * the user from interacting with elements while the main
1856 * loop is recursing.
1861 * Avoid main loop recursion in situations where you can't handle
1862 * arbitrary callbacks. Instead, structure your code so that you
1863 * simply return to the main loop and then get called again when
1864 * there is more work to do.
1869 * Return value: The main loop recursion level in the current thread
1874 GMainDispatch *dispatch = get_dispatch ();
1875 return dispatch->depth;
1879 * g_main_current_source:
1881 * Returns the currently firing source for this thread.
1883 * Return value: The currently firing source or %NULL.
1888 g_main_current_source (void)
1890 GMainDispatch *dispatch = get_dispatch ();
1891 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
1895 * g_source_is_destroyed:
1896 * @source: a #GSource
1898 * Returns whether @source has been destroyed.
1900 * This is important when you operate upon your objects
1901 * from within idle handlers, but may have freed the object
1902 * before the dispatch of your idle handler.
1906 * idle_callback (gpointer data)
1908 * SomeWidget *self = data;
1910 * GDK_THREADS_ENTER (<!-- -->);
1911 * /<!-- -->* do stuff with self *<!-- -->/
1912 * self->idle_id = 0;
1913 * GDK_THREADS_LEAVE (<!-- -->);
1919 * some_widget_do_stuff_later (SomeWidget *self)
1921 * self->idle_id = g_idle_add (idle_callback, self);
1925 * some_widget_finalize (GObject *object)
1927 * SomeWidget *self = SOME_WIDGET (object);
1929 * if (self->idle_id)
1930 * g_source_remove (self->idle_id);
1932 * G_OBJECT_CLASS (parent_class)->finalize (object);
1936 * This will fail in a multi-threaded application if the
1937 * widget is destroyed before the idle handler fires due
1938 * to the use after free in the callback. A solution, to
1939 * this particular problem, is to check to if the source
1940 * has already been destroy within the callback.
1944 * idle_callback (gpointer data)
1946 * SomeWidget *self = data;
1948 * GDK_THREADS_ENTER ();
1949 * if (!g_source_is_destroyed (g_main_current_source ()))
1951 * /<!-- -->* do stuff with self *<!-- -->/
1953 * GDK_THREADS_LEAVE ();
1959 * Return value: %TRUE if the source has been destroyed
1964 g_source_is_destroyed (GSource *source)
1966 return SOURCE_DESTROYED (source);
1970 /* Temporarily remove all this source's file descriptors from the
1971 * poll(), so that if data comes available for one of the file descriptors
1972 * we don't continually spin in the poll()
1974 /* HOLDS: source->context's lock */
1976 block_source (GSource *source)
1980 g_return_if_fail (!SOURCE_BLOCKED (source));
1982 tmp_list = source->poll_fds;
1985 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
1986 tmp_list = tmp_list->next;
1990 /* HOLDS: source->context's lock */
1992 unblock_source (GSource *source)
1996 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
1997 g_return_if_fail (!SOURCE_DESTROYED (source));
1999 tmp_list = source->poll_fds;
2002 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2003 tmp_list = tmp_list->next;
2007 /* HOLDS: context's lock */
2009 g_main_dispatch (GMainContext *context)
2011 GMainDispatch *current = get_dispatch ();
2014 for (i = 0; i < context->pending_dispatches->len; i++)
2016 GSource *source = context->pending_dispatches->pdata[i];
2018 context->pending_dispatches->pdata[i] = NULL;
2021 source->flags &= ~G_SOURCE_READY;
2023 if (!SOURCE_DESTROYED (source))
2025 gboolean was_in_call;
2026 gpointer user_data = NULL;
2027 GSourceFunc callback = NULL;
2028 GSourceCallbackFuncs *cb_funcs;
2030 gboolean need_destroy;
2032 gboolean (*dispatch) (GSource *,
2035 GSList current_source_link;
2037 dispatch = source->source_funcs->dispatch;
2038 cb_funcs = source->callback_funcs;
2039 cb_data = source->callback_data;
2042 cb_funcs->ref (cb_data);
2044 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2045 block_source (source);
2047 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2048 source->flags |= G_HOOK_FLAG_IN_CALL;
2051 cb_funcs->get (cb_data, source, &callback, &user_data);
2053 UNLOCK_CONTEXT (context);
2056 /* The on-stack allocation of the GSList is unconventional, but
2057 * we know that the lifetime of the link is bounded to this
2058 * function as the link is kept in a thread specific list and
2059 * not manipulated outside of this function and its descendants.
2060 * Avoiding the overhead of a g_slist_alloc() is useful as many
2061 * applications do little more than dispatch events.
2063 * This is a performance hack - do not revert to g_slist_prepend()!
2065 current_source_link.data = source;
2066 current_source_link.next = current->dispatching_sources;
2067 current->dispatching_sources = ¤t_source_link;
2068 need_destroy = ! dispatch (source,
2071 g_assert (current->dispatching_sources == ¤t_source_link);
2072 current->dispatching_sources = current_source_link.next;
2076 cb_funcs->unref (cb_data);
2078 LOCK_CONTEXT (context);
2081 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2083 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2084 !SOURCE_DESTROYED (source))
2085 unblock_source (source);
2087 /* Note: this depends on the fact that we can't switch
2088 * sources from one main context to another
2090 if (need_destroy && !SOURCE_DESTROYED (source))
2092 g_assert (source->context == context);
2093 g_source_destroy_internal (source, context, TRUE);
2097 SOURCE_UNREF (source, context);
2100 g_ptr_array_set_size (context->pending_dispatches, 0);
2103 /* Holds context's lock */
2104 static inline GSource *
2105 next_valid_source (GMainContext *context,
2108 GSource *new_source = source ? source->next : context->source_list;
2112 if (!SOURCE_DESTROYED (new_source))
2114 new_source->ref_count++;
2118 new_source = new_source->next;
2122 SOURCE_UNREF (source, context);
2128 * g_main_context_acquire:
2129 * @context: a #GMainContext
2131 * Tries to become the owner of the specified context.
2132 * If some other thread is the owner of the context,
2133 * returns %FALSE immediately. Ownership is properly
2134 * recursive: the owner can require ownership again
2135 * and will release ownership when g_main_context_release()
2136 * is called as many times as g_main_context_acquire().
2138 * You must be the owner of a context before you
2139 * can call g_main_context_prepare(), g_main_context_query(),
2140 * g_main_context_check(), g_main_context_dispatch().
2142 * Return value: %TRUE if the operation succeeded, and
2143 * this thread is now the owner of @context.
2146 g_main_context_acquire (GMainContext *context)
2148 #ifdef G_THREADS_ENABLED
2149 gboolean result = FALSE;
2150 GThread *self = G_THREAD_SELF;
2152 if (context == NULL)
2153 context = g_main_context_default ();
2155 LOCK_CONTEXT (context);
2157 if (!context->owner)
2159 context->owner = self;
2160 g_assert (context->owner_count == 0);
2163 if (context->owner == self)
2165 context->owner_count++;
2169 UNLOCK_CONTEXT (context);
2172 #else /* !G_THREADS_ENABLED */
2174 #endif /* G_THREADS_ENABLED */
2178 * g_main_context_release:
2179 * @context: a #GMainContext
2181 * Releases ownership of a context previously acquired by this thread
2182 * with g_main_context_acquire(). If the context was acquired multiple
2183 * times, the ownership will be released only when g_main_context_release()
2184 * is called as many times as it was acquired.
2187 g_main_context_release (GMainContext *context)
2189 #ifdef G_THREADS_ENABLED
2190 if (context == NULL)
2191 context = g_main_context_default ();
2193 LOCK_CONTEXT (context);
2195 context->owner_count--;
2196 if (context->owner_count == 0)
2198 context->owner = NULL;
2200 if (context->waiters)
2202 GMainWaiter *waiter = context->waiters->data;
2203 gboolean loop_internal_waiter =
2204 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
2205 context->waiters = g_slist_delete_link (context->waiters,
2207 if (!loop_internal_waiter)
2208 g_mutex_lock (waiter->mutex);
2210 g_cond_signal (waiter->cond);
2212 if (!loop_internal_waiter)
2213 g_mutex_unlock (waiter->mutex);
2217 UNLOCK_CONTEXT (context);
2218 #endif /* G_THREADS_ENABLED */
2222 * g_main_context_wait:
2223 * @context: a #GMainContext
2224 * @cond: a condition variable
2225 * @mutex: a mutex, currently held
2227 * Tries to become the owner of the specified context,
2228 * as with g_main_context_acquire(). But if another thread
2229 * is the owner, atomically drop @mutex and wait on @cond until
2230 * that owner releases ownership or until @cond is signaled, then
2231 * try again (once) to become the owner.
2233 * Return value: %TRUE if the operation succeeded, and
2234 * this thread is now the owner of @context.
2237 g_main_context_wait (GMainContext *context,
2241 #ifdef G_THREADS_ENABLED
2242 gboolean result = FALSE;
2243 GThread *self = G_THREAD_SELF;
2244 gboolean loop_internal_waiter;
2246 if (context == NULL)
2247 context = g_main_context_default ();
2249 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2251 if (!loop_internal_waiter)
2252 LOCK_CONTEXT (context);
2254 if (context->owner && context->owner != self)
2259 waiter.mutex = mutex;
2261 context->waiters = g_slist_append (context->waiters, &waiter);
2263 if (!loop_internal_waiter)
2264 UNLOCK_CONTEXT (context);
2265 g_cond_wait (cond, mutex);
2266 if (!loop_internal_waiter)
2267 LOCK_CONTEXT (context);
2269 context->waiters = g_slist_remove (context->waiters, &waiter);
2272 if (!context->owner)
2274 context->owner = self;
2275 g_assert (context->owner_count == 0);
2278 if (context->owner == self)
2280 context->owner_count++;
2284 if (!loop_internal_waiter)
2285 UNLOCK_CONTEXT (context);
2288 #else /* !G_THREADS_ENABLED */
2290 #endif /* G_THREADS_ENABLED */
2294 * g_main_context_prepare:
2295 * @context: a #GMainContext
2296 * @priority: location to store priority of highest priority
2297 * source already ready.
2299 * Prepares to poll sources within a main loop. The resulting information
2300 * for polling is determined by calling g_main_context_query ().
2302 * Return value: %TRUE if some source is ready to be dispatched
2306 g_main_context_prepare (GMainContext *context,
2311 gint current_priority = G_MAXINT;
2314 if (context == NULL)
2315 context = g_main_context_default ();
2317 LOCK_CONTEXT (context);
2319 context->time_is_current = FALSE;
2321 if (context->in_check_or_prepare)
2323 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2324 "prepare() member.");
2325 UNLOCK_CONTEXT (context);
2329 #ifdef G_THREADS_ENABLED
2330 if (context->poll_waiting)
2332 g_warning("g_main_context_prepare(): main loop already active in another thread");
2333 UNLOCK_CONTEXT (context);
2337 context->poll_waiting = TRUE;
2338 #endif /* G_THREADS_ENABLED */
2341 /* If recursing, finish up current dispatch, before starting over */
2342 if (context->pending_dispatches)
2345 g_main_dispatch (context, ¤t_time);
2347 UNLOCK_CONTEXT (context);
2352 /* If recursing, clear list of pending dispatches */
2354 for (i = 0; i < context->pending_dispatches->len; i++)
2356 if (context->pending_dispatches->pdata[i])
2357 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2359 g_ptr_array_set_size (context->pending_dispatches, 0);
2361 /* Prepare all sources */
2363 context->timeout = -1;
2365 source = next_valid_source (context, NULL);
2368 gint source_timeout = -1;
2370 if ((n_ready > 0) && (source->priority > current_priority))
2372 SOURCE_UNREF (source, context);
2375 if (SOURCE_BLOCKED (source))
2378 if (!(source->flags & G_SOURCE_READY))
2381 gboolean (*prepare) (GSource *source,
2384 prepare = source->source_funcs->prepare;
2385 context->in_check_or_prepare++;
2386 UNLOCK_CONTEXT (context);
2388 result = (*prepare) (source, &source_timeout);
2390 LOCK_CONTEXT (context);
2391 context->in_check_or_prepare--;
2394 source->flags |= G_SOURCE_READY;
2397 if (source->flags & G_SOURCE_READY)
2400 current_priority = source->priority;
2401 context->timeout = 0;
2404 if (source_timeout >= 0)
2406 if (context->timeout < 0)
2407 context->timeout = source_timeout;
2409 context->timeout = MIN (context->timeout, source_timeout);
2413 source = next_valid_source (context, source);
2416 UNLOCK_CONTEXT (context);
2419 *priority = current_priority;
2421 return (n_ready > 0);
2425 * g_main_context_query:
2426 * @context: a #GMainContext
2427 * @max_priority: maximum priority source to check
2428 * @timeout_: location to store timeout to be used in polling
2429 * @fds: location to store #GPollFD records that need to be polled.
2430 * @n_fds: length of @fds.
2432 * Determines information necessary to poll this main loop.
2434 * Return value: the number of records actually stored in @fds,
2435 * or, if more than @n_fds records need to be stored, the number
2436 * of records that need to be stored.
2439 g_main_context_query (GMainContext *context,
2448 LOCK_CONTEXT (context);
2450 pollrec = context->poll_records;
2452 while (pollrec && max_priority >= pollrec->priority)
2454 if (pollrec->fd->events)
2458 fds[n_poll].fd = pollrec->fd->fd;
2459 /* In direct contradiction to the Unix98 spec, IRIX runs into
2460 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2461 * flags in the events field of the pollfd while it should
2462 * just ignoring them. So we mask them out here.
2464 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2465 fds[n_poll].revents = 0;
2470 pollrec = pollrec->next;
2473 #ifdef G_THREADS_ENABLED
2474 context->poll_changed = FALSE;
2479 *timeout = context->timeout;
2481 context->time_is_current = FALSE;
2484 UNLOCK_CONTEXT (context);
2490 * g_main_context_check:
2491 * @context: a #GMainContext
2492 * @max_priority: the maximum numerical priority of sources to check
2493 * @fds: array of #GPollFD's that was passed to the last call to
2494 * g_main_context_query()
2495 * @n_fds: return value of g_main_context_query()
2497 * Passes the results of polling back to the main loop.
2499 * Return value: %TRUE if some sources are ready to be dispatched.
2502 g_main_context_check (GMainContext *context,
2512 LOCK_CONTEXT (context);
2514 if (context->in_check_or_prepare)
2516 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2517 "prepare() member.");
2518 UNLOCK_CONTEXT (context);
2522 #ifdef G_THREADS_ENABLED
2523 if (!context->poll_waiting)
2527 read (context->wake_up_pipe[0], &a, 1);
2531 context->poll_waiting = FALSE;
2533 /* If the set of poll file descriptors changed, bail out
2534 * and let the main loop rerun
2536 if (context->poll_changed)
2538 UNLOCK_CONTEXT (context);
2541 #endif /* G_THREADS_ENABLED */
2543 pollrec = context->poll_records;
2547 if (pollrec->fd->events)
2549 pollrec->fd->revents = fds[i].revents;
2552 pollrec = pollrec->next;
2555 source = next_valid_source (context, NULL);
2558 if ((n_ready > 0) && (source->priority > max_priority))
2560 SOURCE_UNREF (source, context);
2563 if (SOURCE_BLOCKED (source))
2566 if (!(source->flags & G_SOURCE_READY))
2569 gboolean (*check) (GSource *source);
2571 check = source->source_funcs->check;
2573 context->in_check_or_prepare++;
2574 UNLOCK_CONTEXT (context);
2576 result = (*check) (source);
2578 LOCK_CONTEXT (context);
2579 context->in_check_or_prepare--;
2582 source->flags |= G_SOURCE_READY;
2585 if (source->flags & G_SOURCE_READY)
2587 source->ref_count++;
2588 g_ptr_array_add (context->pending_dispatches, source);
2592 /* never dispatch sources with less priority than the first
2593 * one we choose to dispatch
2595 max_priority = source->priority;
2599 source = next_valid_source (context, source);
2602 UNLOCK_CONTEXT (context);
2608 * g_main_context_dispatch:
2609 * @context: a #GMainContext
2611 * Dispatches all pending sources.
2614 g_main_context_dispatch (GMainContext *context)
2616 LOCK_CONTEXT (context);
2618 if (context->pending_dispatches->len > 0)
2620 g_main_dispatch (context);
2623 UNLOCK_CONTEXT (context);
2626 /* HOLDS context lock */
2628 g_main_context_iterate (GMainContext *context,
2635 gboolean some_ready;
2636 gint nfds, allocated_nfds;
2637 GPollFD *fds = NULL;
2639 UNLOCK_CONTEXT (context);
2641 #ifdef G_THREADS_ENABLED
2642 if (!g_main_context_acquire (context))
2644 gboolean got_ownership;
2646 g_return_val_if_fail (g_thread_supported (), FALSE);
2651 LOCK_CONTEXT (context);
2654 context->cond = g_cond_new ();
2656 got_ownership = g_main_context_wait (context,
2658 g_static_mutex_get_mutex (&context->mutex));
2662 UNLOCK_CONTEXT (context);
2667 LOCK_CONTEXT (context);
2668 #endif /* G_THREADS_ENABLED */
2670 if (!context->cached_poll_array)
2672 context->cached_poll_array_size = context->n_poll_records;
2673 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2676 allocated_nfds = context->cached_poll_array_size;
2677 fds = context->cached_poll_array;
2679 UNLOCK_CONTEXT (context);
2681 g_main_context_prepare (context, &max_priority);
2683 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
2684 allocated_nfds)) > allocated_nfds)
2686 LOCK_CONTEXT (context);
2688 context->cached_poll_array_size = allocated_nfds = nfds;
2689 context->cached_poll_array = fds = g_new (GPollFD, nfds);
2690 UNLOCK_CONTEXT (context);
2696 g_main_context_poll (context, timeout, max_priority, fds, nfds);
2698 some_ready = g_main_context_check (context, max_priority, fds, nfds);
2701 g_main_context_dispatch (context);
2703 #ifdef G_THREADS_ENABLED
2704 g_main_context_release (context);
2705 #endif /* G_THREADS_ENABLED */
2707 LOCK_CONTEXT (context);
2713 * g_main_context_pending:
2714 * @context: a #GMainContext (if %NULL, the default context will be used)
2716 * Checks if any sources have pending events for the given context.
2718 * Return value: %TRUE if events are pending.
2721 g_main_context_pending (GMainContext *context)
2726 context = g_main_context_default();
2728 LOCK_CONTEXT (context);
2729 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
2730 UNLOCK_CONTEXT (context);
2736 * g_main_context_iteration:
2737 * @context: a #GMainContext (if %NULL, the default context will be used)
2738 * @may_block: whether the call may block.
2740 * Runs a single iteration for the given main loop. This involves
2741 * checking to see if any event sources are ready to be processed,
2742 * then if no events sources are ready and @may_block is %TRUE, waiting
2743 * for a source to become ready, then dispatching the highest priority
2744 * events sources that are ready. Otherwise, if @may_block is %FALSE
2745 * sources are not waited to become ready, only those highest priority
2746 * events sources will be dispatched (if any), that are ready at this
2747 * given moment without further waiting.
2749 * Note that even when @may_block is %TRUE, it is still possible for
2750 * g_main_context_iteration() to return %FALSE, since the the wait may
2751 * be interrupted for other reasons than an event source becoming ready.
2753 * Return value: %TRUE if events were dispatched.
2756 g_main_context_iteration (GMainContext *context, gboolean may_block)
2761 context = g_main_context_default();
2763 LOCK_CONTEXT (context);
2764 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
2765 UNLOCK_CONTEXT (context);
2772 * @context: a #GMainContext (if %NULL, the default context will be used).
2773 * @is_running: set to %TRUE to indicate that the loop is running. This
2774 * is not very important since calling g_main_loop_run() will set this to
2777 * Creates a new #GMainLoop structure.
2779 * Return value: a new #GMainLoop.
2782 g_main_loop_new (GMainContext *context,
2783 gboolean is_running)
2786 #ifdef G_MAIN_POLL_DEBUG
2787 static gboolean beenhere = FALSE;
2790 #ifdef G_MAIN_POLL_DEBUG
2796 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
2797 g_main_poll_debug = TRUE;
2799 G_UNLOCK (main_loop);
2803 context = g_main_context_default();
2805 g_main_context_ref (context);
2807 loop = g_new0 (GMainLoop, 1);
2808 loop->context = context;
2809 loop->is_running = is_running != FALSE;
2810 loop->ref_count = 1;
2817 * @loop: a #GMainLoop
2819 * Increases the reference count on a #GMainLoop object by one.
2821 * Return value: @loop
2824 g_main_loop_ref (GMainLoop *loop)
2826 g_return_val_if_fail (loop != NULL, NULL);
2827 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2829 g_atomic_int_inc (&loop->ref_count);
2835 * g_main_loop_unref:
2836 * @loop: a #GMainLoop
2838 * Decreases the reference count on a #GMainLoop object by one. If
2839 * the result is zero, free the loop and free all associated memory.
2842 g_main_loop_unref (GMainLoop *loop)
2844 g_return_if_fail (loop != NULL);
2845 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2847 if (!g_atomic_int_dec_and_test (&loop->ref_count))
2850 g_main_context_unref (loop->context);
2856 * @loop: a #GMainLoop
2858 * Runs a main loop until g_main_loop_quit() is called on the loop.
2859 * If this is called for the thread of the loop's #GMainContext,
2860 * it will process events from the loop, otherwise it will
2864 g_main_loop_run (GMainLoop *loop)
2866 GThread *self = G_THREAD_SELF;
2868 g_return_if_fail (loop != NULL);
2869 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2871 #ifdef G_THREADS_ENABLED
2872 if (!g_main_context_acquire (loop->context))
2874 gboolean got_ownership = FALSE;
2876 /* Another thread owns this context */
2877 if (!g_thread_supported ())
2879 g_warning ("g_main_loop_run() was called from second thread but "
2880 "g_thread_init() was never called.");
2884 LOCK_CONTEXT (loop->context);
2886 g_atomic_int_inc (&loop->ref_count);
2888 if (!loop->is_running)
2889 loop->is_running = TRUE;
2891 if (!loop->context->cond)
2892 loop->context->cond = g_cond_new ();
2894 while (loop->is_running && !got_ownership)
2895 got_ownership = g_main_context_wait (loop->context,
2896 loop->context->cond,
2897 g_static_mutex_get_mutex (&loop->context->mutex));
2899 if (!loop->is_running)
2901 UNLOCK_CONTEXT (loop->context);
2903 g_main_context_release (loop->context);
2904 g_main_loop_unref (loop);
2908 g_assert (got_ownership);
2911 LOCK_CONTEXT (loop->context);
2912 #endif /* G_THREADS_ENABLED */
2914 if (loop->context->in_check_or_prepare)
2916 g_warning ("g_main_loop_run(): called recursively from within a source's "
2917 "check() or prepare() member, iteration not possible.");
2921 g_atomic_int_inc (&loop->ref_count);
2922 loop->is_running = TRUE;
2923 while (loop->is_running)
2924 g_main_context_iterate (loop->context, TRUE, TRUE, self);
2926 UNLOCK_CONTEXT (loop->context);
2928 #ifdef G_THREADS_ENABLED
2929 g_main_context_release (loop->context);
2930 #endif /* G_THREADS_ENABLED */
2932 g_main_loop_unref (loop);
2937 * @loop: a #GMainLoop
2939 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
2940 * for the loop will return.
2942 * Note that sources that have already been dispatched when
2943 * g_main_loop_quit() is called will still be executed.
2946 g_main_loop_quit (GMainLoop *loop)
2948 g_return_if_fail (loop != NULL);
2949 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2951 LOCK_CONTEXT (loop->context);
2952 loop->is_running = FALSE;
2953 g_main_context_wakeup_unlocked (loop->context);
2955 #ifdef G_THREADS_ENABLED
2956 if (loop->context->cond)
2957 g_cond_broadcast (loop->context->cond);
2958 #endif /* G_THREADS_ENABLED */
2960 UNLOCK_CONTEXT (loop->context);
2964 * g_main_loop_is_running:
2965 * @loop: a #GMainLoop.
2967 * Checks to see if the main loop is currently being run via g_main_loop_run().
2969 * Return value: %TRUE if the mainloop is currently being run.
2972 g_main_loop_is_running (GMainLoop *loop)
2974 g_return_val_if_fail (loop != NULL, FALSE);
2975 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
2977 return loop->is_running;
2981 * g_main_loop_get_context:
2982 * @loop: a #GMainLoop.
2984 * Returns the #GMainContext of @loop.
2986 * Return value: the #GMainContext of @loop
2989 g_main_loop_get_context (GMainLoop *loop)
2991 g_return_val_if_fail (loop != NULL, NULL);
2992 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2994 return loop->context;
2997 /* HOLDS: context's lock */
2999 g_main_context_poll (GMainContext *context,
3005 #ifdef G_MAIN_POLL_DEBUG
3011 GPollFunc poll_func;
3013 if (n_fds || timeout != 0)
3015 #ifdef G_MAIN_POLL_DEBUG
3016 if (g_main_poll_debug)
3018 g_print ("polling context=%p n=%d timeout=%d\n",
3019 context, n_fds, timeout);
3020 poll_timer = g_timer_new ();
3024 LOCK_CONTEXT (context);
3026 poll_func = context->poll_func;
3028 UNLOCK_CONTEXT (context);
3029 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3032 g_warning ("poll(2) failed due to: %s.",
3033 g_strerror (errno));
3035 /* If g_poll () returns -1, it has already called g_warning() */
3039 #ifdef G_MAIN_POLL_DEBUG
3040 if (g_main_poll_debug)
3042 LOCK_CONTEXT (context);
3044 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3047 g_timer_elapsed (poll_timer, NULL));
3048 g_timer_destroy (poll_timer);
3049 pollrec = context->poll_records;
3051 while (pollrec != NULL)
3056 if (fds[i].fd == pollrec->fd->fd &&
3057 pollrec->fd->events &&
3060 g_print (" [" GPOLLFD_FORMAT " :", fds[i].fd);
3061 if (fds[i].revents & G_IO_IN)
3063 if (fds[i].revents & G_IO_OUT)
3065 if (fds[i].revents & G_IO_PRI)
3067 if (fds[i].revents & G_IO_ERR)
3069 if (fds[i].revents & G_IO_HUP)
3071 if (fds[i].revents & G_IO_NVAL)
3077 pollrec = pollrec->next;
3081 UNLOCK_CONTEXT (context);
3084 } /* if (n_fds || timeout != 0) */
3088 * g_main_context_add_poll:
3089 * @context: a #GMainContext (or %NULL for the default context)
3090 * @fd: a #GPollFD structure holding information about a file
3091 * descriptor to watch.
3092 * @priority: the priority for this file descriptor which should be
3093 * the same as the priority used for g_source_attach() to ensure that the
3094 * file descriptor is polled whenever the results may be needed.
3096 * Adds a file descriptor to the set of file descriptors polled for
3097 * this context. This will very seldomly be used directly. Instead
3098 * a typical event source will use g_source_add_poll() instead.
3101 g_main_context_add_poll (GMainContext *context,
3106 context = g_main_context_default ();
3108 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3109 g_return_if_fail (fd);
3111 LOCK_CONTEXT (context);
3112 g_main_context_add_poll_unlocked (context, priority, fd);
3113 UNLOCK_CONTEXT (context);
3116 /* HOLDS: main_loop_lock */
3118 g_main_context_add_poll_unlocked (GMainContext *context,
3122 GPollRec *lastrec, *pollrec;
3123 GPollRec *newrec = g_slice_new (GPollRec);
3125 /* This file descriptor may be checked before we ever poll */
3128 newrec->priority = priority;
3131 pollrec = context->poll_records;
3132 while (pollrec && priority >= pollrec->priority)
3135 pollrec = pollrec->next;
3139 lastrec->next = newrec;
3141 context->poll_records = newrec;
3143 newrec->next = pollrec;
3145 context->n_poll_records++;
3147 #ifdef G_THREADS_ENABLED
3148 context->poll_changed = TRUE;
3150 /* Now wake up the main loop if it is waiting in the poll() */
3151 g_main_context_wakeup_unlocked (context);
3156 * g_main_context_remove_poll:
3157 * @context:a #GMainContext
3158 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3160 * Removes file descriptor from the set of file descriptors to be
3161 * polled for a particular context.
3164 g_main_context_remove_poll (GMainContext *context,
3168 context = g_main_context_default ();
3170 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3171 g_return_if_fail (fd);
3173 LOCK_CONTEXT (context);
3174 g_main_context_remove_poll_unlocked (context, fd);
3175 UNLOCK_CONTEXT (context);
3179 g_main_context_remove_poll_unlocked (GMainContext *context,
3182 GPollRec *pollrec, *lastrec;
3185 pollrec = context->poll_records;
3189 if (pollrec->fd == fd)
3191 if (lastrec != NULL)
3192 lastrec->next = pollrec->next;
3194 context->poll_records = pollrec->next;
3196 g_slice_free (GPollRec, pollrec);
3198 context->n_poll_records--;
3202 pollrec = pollrec->next;
3205 #ifdef G_THREADS_ENABLED
3206 context->poll_changed = TRUE;
3208 /* Now wake up the main loop if it is waiting in the poll() */
3209 g_main_context_wakeup_unlocked (context);
3214 * g_source_get_current_time:
3215 * @source: a #GSource
3216 * @timeval: #GTimeVal structure in which to store current time.
3218 * Gets the "current time" to be used when checking
3219 * this source. The advantage of calling this function over
3220 * calling g_get_current_time() directly is that when
3221 * checking multiple sources, GLib can cache a single value
3222 * instead of having to repeatedly get the system time.
3225 g_source_get_current_time (GSource *source,
3228 GMainContext *context;
3230 g_return_if_fail (source->context != NULL);
3232 context = source->context;
3234 LOCK_CONTEXT (context);
3236 if (!context->time_is_current)
3238 g_get_current_time (&context->current_time);
3239 context->time_is_current = TRUE;
3242 *timeval = context->current_time;
3244 UNLOCK_CONTEXT (context);
3248 * g_main_context_set_poll_func:
3249 * @context: a #GMainContext
3250 * @func: the function to call to poll all file descriptors
3252 * Sets the function to use to handle polling of file descriptors. It
3253 * will be used instead of the poll() system call
3254 * (or GLib's replacement function, which is used where
3255 * poll() isn't available).
3257 * This function could possibly be used to integrate the GLib event
3258 * loop with an external event loop.
3261 g_main_context_set_poll_func (GMainContext *context,
3265 context = g_main_context_default ();
3267 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3269 LOCK_CONTEXT (context);
3272 context->poll_func = func;
3276 context->poll_func = (GPollFunc) poll;
3278 context->poll_func = (GPollFunc) g_poll;
3282 UNLOCK_CONTEXT (context);
3286 * g_main_context_get_poll_func:
3287 * @context: a #GMainContext
3289 * Gets the poll function set by g_main_context_set_poll_func().
3291 * Return value: the poll function
3294 g_main_context_get_poll_func (GMainContext *context)
3299 context = g_main_context_default ();
3301 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3303 LOCK_CONTEXT (context);
3304 result = context->poll_func;
3305 UNLOCK_CONTEXT (context);
3310 /* HOLDS: context's lock */
3311 /* Wake the main loop up from a poll() */
3313 g_main_context_wakeup_unlocked (GMainContext *context)
3315 #ifdef G_THREADS_ENABLED
3316 if (g_thread_supported() && context->poll_waiting)
3318 context->poll_waiting = FALSE;
3320 write (context->wake_up_pipe[1], "A", 1);
3322 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
3329 * g_main_context_wakeup:
3330 * @context: a #GMainContext
3332 * If @context is currently waiting in a poll(), interrupt
3333 * the poll(), and continue the iteration process.
3336 g_main_context_wakeup (GMainContext *context)
3339 context = g_main_context_default ();
3341 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3343 LOCK_CONTEXT (context);
3344 g_main_context_wakeup_unlocked (context);
3345 UNLOCK_CONTEXT (context);
3349 * g_main_context_is_owner:
3350 * @context: a #GMainContext
3352 * Determines whether this thread holds the (recursive)
3353 * ownership of this #GMaincontext. This is useful to
3354 * know before waiting on another thread that may be
3355 * blocking to get ownership of @context.
3357 * Returns: %TRUE if current thread is owner of @context.
3362 g_main_context_is_owner (GMainContext *context)
3367 context = g_main_context_default ();
3369 #ifdef G_THREADS_ENABLED
3370 LOCK_CONTEXT (context);
3371 is_owner = context->owner == G_THREAD_SELF;
3372 UNLOCK_CONTEXT (context);
3383 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3384 GTimeVal *current_time)
3386 guint seconds = timeout_source->interval / 1000;
3387 guint msecs = timeout_source->interval - seconds * 1000;
3389 timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
3390 timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
3391 if (timeout_source->expiration.tv_usec >= 1000000)
3393 timeout_source->expiration.tv_usec -= 1000000;
3394 timeout_source->expiration.tv_sec++;
3396 if (timer_perturb==-1)
3399 * we want a per machine/session unique 'random' value; try the dbus
3400 * address first, that has a UUID in it. If there is no dbus, use the
3401 * hostname for hashing.
3403 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3404 if (!session_bus_address)
3405 session_bus_address = g_getenv ("HOSTNAME");
3406 if (session_bus_address)
3407 timer_perturb = ABS ((gint) g_str_hash (session_bus_address));
3411 if (timeout_source->granularity)
3414 gint gran; /* in usecs */
3417 gran = timeout_source->granularity * 1000;
3418 perturb = timer_perturb % gran;
3420 * We want to give each machine a per machine pertubation;
3421 * shift time back first, and forward later after the rounding
3424 timeout_source->expiration.tv_usec -= perturb;
3425 if (timeout_source->expiration.tv_usec < 0)
3427 timeout_source->expiration.tv_usec += 1000000;
3428 timeout_source->expiration.tv_sec--;
3431 remainder = timeout_source->expiration.tv_usec % gran;
3432 if (remainder >= gran/4) /* round up */
3433 timeout_source->expiration.tv_usec += gran;
3434 timeout_source->expiration.tv_usec -= remainder;
3436 timeout_source->expiration.tv_usec += perturb;
3438 /* the rounding may have overflown tv_usec */
3439 while (timeout_source->expiration.tv_usec > 1000000)
3441 timeout_source->expiration.tv_usec -= 1000000;
3442 timeout_source->expiration.tv_sec++;
3448 g_timeout_prepare (GSource *source,
3453 GTimeVal current_time;
3455 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3457 g_source_get_current_time (source, ¤t_time);
3459 sec = timeout_source->expiration.tv_sec - current_time.tv_sec;
3460 msec = (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000;
3462 /* We do the following in a rather convoluted fashion to deal with
3463 * the fact that we don't have an integral type big enough to hold
3464 * the difference of two timevals in millseconds.
3466 if (sec < 0 || (sec == 0 && msec < 0))
3470 glong interval_sec = timeout_source->interval / 1000;
3471 glong interval_msec = timeout_source->interval % 1000;
3479 if (sec > interval_sec ||
3480 (sec == interval_sec && msec > interval_msec))
3482 /* The system time has been set backwards, so we
3483 * reset the expiration time to now + timeout_source->interval;
3484 * this at least avoids hanging for long periods of time.
3486 g_timeout_set_expiration (timeout_source, ¤t_time);
3487 msec = MIN (G_MAXINT, timeout_source->interval);
3491 msec = MIN (G_MAXINT, (guint)msec + 1000 * (guint)sec);
3495 *timeout = (gint)msec;
3501 g_timeout_check (GSource *source)
3503 GTimeVal current_time;
3504 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3506 g_source_get_current_time (source, ¤t_time);
3508 return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
3509 ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
3510 (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
3514 g_timeout_dispatch (GSource *source,
3515 GSourceFunc callback,
3518 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3522 g_warning ("Timeout source dispatched without callback\n"
3523 "You must call g_source_set_callback().");
3527 if (callback (user_data))
3529 GTimeVal current_time;
3531 g_source_get_current_time (source, ¤t_time);
3532 g_timeout_set_expiration (timeout_source, ¤t_time);
3541 * g_timeout_source_new:
3542 * @interval: the timeout interval in milliseconds.
3544 * Creates a new timeout source.
3546 * The source will not initially be associated with any #GMainContext
3547 * and must be added to one with g_source_attach() before it will be
3550 * Return value: the newly-created timeout source
3553 g_timeout_source_new (guint interval)
3555 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3556 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3557 GTimeVal current_time;
3559 timeout_source->interval = interval;
3561 g_get_current_time (¤t_time);
3562 g_timeout_set_expiration (timeout_source, ¤t_time);
3568 * g_timeout_source_new_seconds:
3569 * @interval: the timeout interval in seconds
3571 * Creates a new timeout source.
3573 * The source will not initially be associated with any #GMainContext
3574 * and must be added to one with g_source_attach() before it will be
3577 * The scheduling granularity/accuracy of this timeout source will be
3580 * Return value: the newly-created timeout source
3585 g_timeout_source_new_seconds (guint interval)
3587 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3588 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3589 GTimeVal current_time;
3591 timeout_source->interval = 1000*interval;
3592 timeout_source->granularity = 1000;
3594 g_get_current_time (¤t_time);
3595 g_timeout_set_expiration (timeout_source, ¤t_time);
3602 * g_timeout_add_full:
3603 * @priority: the priority of the timeout source. Typically this will be in
3604 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3605 * @interval: the time between calls to the function, in milliseconds
3606 * (1/1000ths of a second)
3607 * @function: function to call
3608 * @data: data to pass to @function
3609 * @notify: function to call when the timeout is removed, or %NULL
3611 * Sets a function to be called at regular intervals, with the given
3612 * priority. The function is called repeatedly until it returns
3613 * %FALSE, at which point the timeout is automatically destroyed and
3614 * the function will not be called again. The @notify function is
3615 * called when the timeout is destroyed. The first call to the
3616 * function will be at the end of the first @interval.
3618 * Note that timeout functions may be delayed, due to the processing of other
3619 * event sources. Thus they should not be relied on for precise timing.
3620 * After each call to the timeout function, the time of the next
3621 * timeout is recalculated based on the current time and the given interval
3622 * (it does not try to 'catch up' time lost in delays).
3624 * Return value: the ID (greater than 0) of the event source.
3627 g_timeout_add_full (gint priority,
3629 GSourceFunc function,
3631 GDestroyNotify notify)
3636 g_return_val_if_fail (function != NULL, 0);
3638 source = g_timeout_source_new (interval);
3640 if (priority != G_PRIORITY_DEFAULT)
3641 g_source_set_priority (source, priority);
3643 g_source_set_callback (source, function, data, notify);
3644 id = g_source_attach (source, NULL);
3645 g_source_unref (source);
3652 * @interval: the time between calls to the function, in milliseconds
3653 * (1/1000ths of a second)
3654 * @function: function to call
3655 * @data: data to pass to @function
3657 * Sets a function to be called at regular intervals, with the default
3658 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
3659 * until it returns %FALSE, at which point the timeout is automatically
3660 * destroyed and the function will not be called again. The first call
3661 * to the function will be at the end of the first @interval.
3663 * Note that timeout functions may be delayed, due to the processing of other
3664 * event sources. Thus they should not be relied on for precise timing.
3665 * After each call to the timeout function, the time of the next
3666 * timeout is recalculated based on the current time and the given interval
3667 * (it does not try to 'catch up' time lost in delays).
3669 * If you want to have a timer in the "seconds" range and do not care
3670 * about the exact time of the first call of the timer, use the
3671 * g_timeout_add_seconds() function; this function allows for more
3672 * optimizations and more efficient system power usage.
3674 * Return value: the ID (greater than 0) of the event source.
3677 g_timeout_add (guint32 interval,
3678 GSourceFunc function,
3681 return g_timeout_add_full (G_PRIORITY_DEFAULT,
3682 interval, function, data, NULL);
3686 * g_timeout_add_seconds_full:
3687 * @priority: the priority of the timeout source. Typically this will be in
3688 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3689 * @interval: the time between calls to the function, in seconds
3690 * @function: function to call
3691 * @data: data to pass to @function
3692 * @notify: function to call when the timeout is removed, or %NULL
3694 * Sets a function to be called at regular intervals, with @priority.
3695 * The function is called repeatedly until it returns %FALSE, at which
3696 * point the timeout is automatically destroyed and the function will
3697 * not be called again.
3699 * Unlike g_timeout_add(), this function operates at whole second granularity.
3700 * The initial starting point of the timer is determined by the implementation
3701 * and the implementation is expected to group multiple timers together so that
3702 * they fire all at the same time.
3703 * To allow this grouping, the @interval to the first timer is rounded
3704 * and can deviate up to one second from the specified interval.
3705 * Subsequent timer iterations will generally run at the specified interval.
3707 * Note that timeout functions may be delayed, due to the processing of other
3708 * event sources. Thus they should not be relied on for precise timing.
3709 * After each call to the timeout function, the time of the next
3710 * timeout is recalculated based on the current time and the given @interval
3712 * If you want timing more precise than whole seconds, use g_timeout_add()
3715 * The grouping of timers to fire at the same time results in a more power
3716 * and CPU efficient behavior so if your timer is in multiples of seconds
3717 * and you don't require the first timer exactly one second from now, the
3718 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
3720 * Return value: the ID (greater than 0) of the event source.
3725 g_timeout_add_seconds_full (gint priority,
3727 GSourceFunc function,
3729 GDestroyNotify notify)
3734 g_return_val_if_fail (function != NULL, 0);
3736 source = g_timeout_source_new_seconds (interval);
3738 if (priority != G_PRIORITY_DEFAULT)
3739 g_source_set_priority (source, priority);
3741 g_source_set_callback (source, function, data, notify);
3742 id = g_source_attach (source, NULL);
3743 g_source_unref (source);
3749 * g_timeout_add_seconds:
3750 * @interval: the time between calls to the function, in seconds
3751 * @function: function to call
3752 * @data: data to pass to @function
3754 * Sets a function to be called at regular intervals with the default
3755 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
3756 * it returns %FALSE, at which point the timeout is automatically destroyed
3757 * and the function will not be called again.
3759 * See g_timeout_add_seconds_full() for the differences between
3760 * g_timeout_add() and g_timeout_add_seconds().
3762 * Return value: the ID (greater than 0) of the event source.
3767 g_timeout_add_seconds (guint interval,
3768 GSourceFunc function,
3771 g_return_val_if_fail (function != NULL, 0);
3773 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
3776 /* Child watch functions */
3781 g_child_watch_prepare (GSource *source,
3790 g_child_watch_check (GSource *source)
3792 GChildWatchSource *child_watch_source;
3793 gboolean child_exited;
3795 child_watch_source = (GChildWatchSource *) source;
3797 child_exited = child_watch_source->poll.revents & G_IO_IN;
3804 * Note: We do _not_ check for the special value of STILL_ACTIVE
3805 * since we know that the process has exited and doing so runs into
3806 * problems if the child process "happens to return STILL_ACTIVE(259)"
3807 * as Microsoft's Platform SDK puts it.
3809 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
3811 gchar *emsg = g_win32_error_message (GetLastError ());
3812 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
3815 child_watch_source->child_status = -1;
3818 child_watch_source->child_status = child_status;
3821 return child_exited;
3824 #else /* G_OS_WIN32 */
3827 check_for_child_exited (GSource *source)
3829 GChildWatchSource *child_watch_source;
3832 /* protect against another SIGCHLD in the middle of this call */
3833 count = child_watch_count;
3835 child_watch_source = (GChildWatchSource *) source;
3837 if (child_watch_source->child_exited)
3840 if (child_watch_source->count < count)
3844 if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
3846 child_watch_source->child_status = child_status;
3847 child_watch_source->child_exited = TRUE;
3849 child_watch_source->count = count;
3852 return child_watch_source->child_exited;
3856 g_child_watch_prepare (GSource *source,
3861 return check_for_child_exited (source);
3866 g_child_watch_check (GSource *source)
3868 return check_for_child_exited (source);
3871 #endif /* G_OS_WIN32 */
3874 g_child_watch_dispatch (GSource *source,
3875 GSourceFunc callback,
3878 GChildWatchSource *child_watch_source;
3879 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
3881 child_watch_source = (GChildWatchSource *) source;
3885 g_warning ("Child watch source dispatched without callback\n"
3886 "You must call g_source_set_callback().");
3890 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
3892 /* We never keep a child watch source around as the child is gone */
3899 g_child_watch_signal_handler (int signum)
3901 child_watch_count ++;
3903 if (child_watch_init_state == CHILD_WATCH_INITIALIZED_THREADED)
3905 write (child_watch_wake_up_pipe[1], "B", 1);
3909 /* We count on the signal interrupting the poll in the same thread.
3915 g_child_watch_source_init_single (void)
3917 struct sigaction action;
3919 g_assert (! g_thread_supported());
3920 g_assert (child_watch_init_state == CHILD_WATCH_UNINITIALIZED);
3922 child_watch_init_state = CHILD_WATCH_INITIALIZED_SINGLE;
3924 action.sa_handler = g_child_watch_signal_handler;
3925 sigemptyset (&action.sa_mask);
3926 action.sa_flags = SA_NOCLDSTOP;
3927 sigaction (SIGCHLD, &action, NULL);
3931 child_watch_helper_thread (gpointer data)
3938 read (child_watch_wake_up_pipe[0], b, 20);
3940 /* We were woken up. Wake up all other contexts in all other threads */
3941 G_LOCK (main_context_list);
3942 for (list = main_context_list; list; list = list->next)
3944 GMainContext *context;
3946 context = list->data;
3947 if (g_atomic_int_get (&context->ref_count) > 0)
3948 /* Due to racing conditions we can find ref_count == 0, in
3949 * that case, however, the context is still not destroyed
3950 * and no poll can be active, otherwise the ref_count
3952 g_main_context_wakeup (context);
3954 G_UNLOCK (main_context_list);
3961 g_child_watch_source_init_multi_threaded (void)
3963 GError *error = NULL;
3964 struct sigaction action;
3966 g_assert (g_thread_supported());
3968 if (pipe (child_watch_wake_up_pipe) < 0)
3969 g_error ("Cannot create wake up pipe: %s\n", g_strerror (errno));
3970 fcntl (child_watch_wake_up_pipe[1], F_SETFL, O_NONBLOCK | fcntl (child_watch_wake_up_pipe[1], F_GETFL));
3972 /* We create a helper thread that polls on the wakeup pipe indefinitely */
3973 /* FIXME: Think this through for races */
3974 if (g_thread_create (child_watch_helper_thread, NULL, FALSE, &error) == NULL)
3975 g_error ("Cannot create a thread to monitor child exit status: %s\n", error->message);
3976 child_watch_init_state = CHILD_WATCH_INITIALIZED_THREADED;
3978 action.sa_handler = g_child_watch_signal_handler;
3979 sigemptyset (&action.sa_mask);
3980 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
3981 sigaction (SIGCHLD, &action, NULL);
3985 g_child_watch_source_init_promote_single_to_threaded (void)
3987 g_child_watch_source_init_multi_threaded ();
3991 g_child_watch_source_init (void)
3993 if (g_thread_supported())
3995 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
3996 g_child_watch_source_init_multi_threaded ();
3997 else if (child_watch_init_state == CHILD_WATCH_INITIALIZED_SINGLE)
3998 g_child_watch_source_init_promote_single_to_threaded ();
4002 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
4003 g_child_watch_source_init_single ();
4007 #endif /* !G_OS_WIN32 */
4010 * g_child_watch_source_new:
4011 * @pid: process to watch. On POSIX the pid of a child process. On
4012 * Windows a handle for a process (which doesn't have to be a child).
4014 * Creates a new child_watch source.
4016 * The source will not initially be associated with any #GMainContext
4017 * and must be added to one with g_source_attach() before it will be
4020 * Note that child watch sources can only be used in conjunction with
4021 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4024 * Note that on platforms where #GPid must be explicitly closed
4025 * (see g_spawn_close_pid()) @pid must not be closed while the
4026 * source is still active. Typically, you will want to call
4027 * g_spawn_close_pid() in the callback function for the source.
4029 * Note further that using g_child_watch_source_new() is not
4030 * compatible with calling <literal>waitpid(-1)</literal> in
4031 * the application. Calling waitpid() for individual pids will
4034 * Return value: the newly-created child watch source
4039 g_child_watch_source_new (GPid pid)
4041 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4042 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4045 child_watch_source->poll.fd = (int)pid;
4046 child_watch_source->poll.events = G_IO_IN;
4048 g_source_add_poll (source, &child_watch_source->poll);
4049 #else /* G_OS_WIN32 */
4050 g_child_watch_source_init ();
4051 #endif /* G_OS_WIN32 */
4053 child_watch_source->pid = pid;
4059 * g_child_watch_add_full:
4060 * @priority: the priority of the idle source. Typically this will be in the
4061 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4062 * @pid: process to watch. On POSIX the pid of a child process. On
4063 * Windows a handle for a process (which doesn't have to be a child).
4064 * @function: function to call
4065 * @data: data to pass to @function
4066 * @notify: function to call when the idle is removed, or %NULL
4068 * Sets a function to be called when the child indicated by @pid
4069 * exits, at the priority @priority.
4071 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4072 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4073 * the spawn function for the child watching to work.
4075 * Note that on platforms where #GPid must be explicitly closed
4076 * (see g_spawn_close_pid()) @pid must not be closed while the
4077 * source is still active. Typically, you will want to call
4078 * g_spawn_close_pid() in the callback function for the source.
4080 * GLib supports only a single callback per process id.
4082 * Return value: the ID (greater than 0) of the event source.
4087 g_child_watch_add_full (gint priority,
4089 GChildWatchFunc function,
4091 GDestroyNotify notify)
4096 g_return_val_if_fail (function != NULL, 0);
4098 source = g_child_watch_source_new (pid);
4100 if (priority != G_PRIORITY_DEFAULT)
4101 g_source_set_priority (source, priority);
4103 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4104 id = g_source_attach (source, NULL);
4105 g_source_unref (source);
4111 * g_child_watch_add:
4112 * @pid: process id to watch. On POSIX the pid of a child process. On
4113 * Windows a handle for a process (which doesn't have to be a child).
4114 * @function: function to call
4115 * @data: data to pass to @function
4117 * Sets a function to be called when the child indicated by @pid
4118 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4120 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4121 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4122 * the spawn function for the child watching to work.
4124 * Note that on platforms where #GPid must be explicitly closed
4125 * (see g_spawn_close_pid()) @pid must not be closed while the
4126 * source is still active. Typically, you will want to call
4127 * g_spawn_close_pid() in the callback function for the source.
4129 * GLib supports only a single callback per process id.
4131 * Return value: the ID (greater than 0) of the event source.
4136 g_child_watch_add (GPid pid,
4137 GChildWatchFunc function,
4140 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4144 /* Idle functions */
4147 g_idle_prepare (GSource *source,
4156 g_idle_check (GSource *source)
4162 g_idle_dispatch (GSource *source,
4163 GSourceFunc callback,
4168 g_warning ("Idle source dispatched without callback\n"
4169 "You must call g_source_set_callback().");
4173 return callback (user_data);
4177 * g_idle_source_new:
4179 * Creates a new idle source.
4181 * The source will not initially be associated with any #GMainContext
4182 * and must be added to one with g_source_attach() before it will be
4183 * executed. Note that the default priority for idle sources is
4184 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4185 * have a default priority of %G_PRIORITY_DEFAULT.
4187 * Return value: the newly-created idle source
4190 g_idle_source_new (void)
4194 source = g_source_new (&g_idle_funcs, sizeof (GSource));
4195 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4202 * @priority: the priority of the idle source. Typically this will be in the
4203 * range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4204 * @function: function to call
4205 * @data: data to pass to @function
4206 * @notify: function to call when the idle is removed, or %NULL
4208 * Adds a function to be called whenever there are no higher priority
4209 * events pending. If the function returns %FALSE it is automatically
4210 * removed from the list of event sources and will not be called again.
4212 * Return value: the ID (greater than 0) of the event source.
4215 g_idle_add_full (gint priority,
4216 GSourceFunc function,
4218 GDestroyNotify notify)
4223 g_return_val_if_fail (function != NULL, 0);
4225 source = g_idle_source_new ();
4227 if (priority != G_PRIORITY_DEFAULT_IDLE)
4228 g_source_set_priority (source, priority);
4230 g_source_set_callback (source, function, data, notify);
4231 id = g_source_attach (source, NULL);
4232 g_source_unref (source);
4239 * @function: function to call
4240 * @data: data to pass to @function.
4242 * Adds a function to be called whenever there are no higher priority
4243 * events pending to the default main loop. The function is given the
4244 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4245 * returns %FALSE it is automatically removed from the list of event
4246 * sources and will not be called again.
4248 * Return value: the ID (greater than 0) of the event source.
4251 g_idle_add (GSourceFunc function,
4254 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4258 * g_idle_remove_by_data:
4259 * @data: the data for the idle source's callback.
4261 * Removes the idle function with the given data.
4263 * Return value: %TRUE if an idle source was found and removed.
4266 g_idle_remove_by_data (gpointer data)
4268 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4271 #define __G_MAIN_C__
4272 #include "galiasdef.c"