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 */
94 #define GPOLLFD_FORMAT "%#I64x"
96 #define GPOLLFD_FORMAT "%#x"
99 #define GPOLLFD_FORMAT "%d"
104 typedef struct _GTimeoutSource GTimeoutSource;
105 typedef struct _GChildWatchSource GChildWatchSource;
106 typedef struct _GPollRec GPollRec;
107 typedef struct _GSourceCallback GSourceCallback;
111 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
112 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
115 #ifdef G_THREADS_ENABLED
116 typedef struct _GMainWaiter GMainWaiter;
125 typedef struct _GMainDispatch GMainDispatch;
127 struct _GMainDispatch
130 GSList *dispatching_sources; /* stack of current sources */
133 #ifdef G_MAIN_POLL_DEBUG
134 static gboolean g_main_poll_debug = FALSE;
139 #ifdef G_THREADS_ENABLED
140 /* The following lock is used for both the list of sources
141 * and the list of poll records
152 GPtrArray *pending_dispatches;
153 gint timeout; /* Timeout for current iteration */
156 GSource *source_list;
157 gint in_check_or_prepare;
159 GPollRec *poll_records;
160 guint n_poll_records;
161 GPollFD *cached_poll_array;
162 guint cached_poll_array_size;
164 #ifdef G_THREADS_ENABLED
166 /* this pipe is used to wake up the main loop when a source is added.
168 gint wake_up_pipe[2];
169 #else /* G_OS_WIN32 */
170 HANDLE wake_up_semaphore;
171 #endif /* G_OS_WIN32 */
174 gboolean poll_waiting;
176 /* Flag indicating whether the set of fd's changed during a poll */
177 gboolean poll_changed;
178 #endif /* G_THREADS_ENABLED */
182 GTimeVal current_time;
183 gboolean time_is_current;
186 struct _GSourceCallback
191 GDestroyNotify notify;
196 GMainContext *context;
201 struct _GTimeoutSource
209 struct _GChildWatchSource
216 #else /* G_OS_WIN32 */
218 gboolean child_exited;
219 #endif /* G_OS_WIN32 */
229 #ifdef G_THREADS_ENABLED
230 #define LOCK_CONTEXT(context) g_static_mutex_lock (&context->mutex)
231 #define UNLOCK_CONTEXT(context) g_static_mutex_unlock (&context->mutex)
232 #define G_THREAD_SELF g_thread_self ()
234 #define LOCK_CONTEXT(context) (void)0
235 #define UNLOCK_CONTEXT(context) (void)0
236 #define G_THREAD_SELF NULL
239 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
240 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
241 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
243 #define SOURCE_UNREF(source, context) \
245 if ((source)->ref_count > 1) \
246 (source)->ref_count--; \
248 g_source_unref_internal ((source), (context), TRUE); \
252 /* Forward declarations */
254 static void g_source_unref_internal (GSource *source,
255 GMainContext *context,
257 static void g_source_destroy_internal (GSource *source,
258 GMainContext *context,
260 static void g_main_context_poll (GMainContext *context,
265 static void g_main_context_add_poll_unlocked (GMainContext *context,
268 static void g_main_context_remove_poll_unlocked (GMainContext *context,
270 static void g_main_context_wakeup_unlocked (GMainContext *context);
272 static gboolean g_timeout_prepare (GSource *source,
274 static gboolean g_timeout_check (GSource *source);
275 static gboolean g_timeout_dispatch (GSource *source,
276 GSourceFunc callback,
278 static gboolean g_child_watch_prepare (GSource *source,
280 static gboolean g_child_watch_check (GSource *source);
281 static gboolean g_child_watch_dispatch (GSource *source,
282 GSourceFunc callback,
284 static gboolean g_idle_prepare (GSource *source,
286 static gboolean g_idle_check (GSource *source);
287 static gboolean g_idle_dispatch (GSource *source,
288 GSourceFunc callback,
291 G_LOCK_DEFINE_STATIC (main_loop);
292 static GMainContext *default_main_context;
293 static GSList *main_contexts_without_pipe = NULL;
296 /* Child status monitoring code */
298 CHILD_WATCH_UNINITIALIZED,
299 CHILD_WATCH_INITIALIZED_SINGLE,
300 CHILD_WATCH_INITIALIZED_THREADED
302 static gint child_watch_init_state = CHILD_WATCH_UNINITIALIZED;
303 static gint child_watch_count = 1;
304 static gint child_watch_wake_up_pipe[2] = {0, 0};
305 #endif /* !G_OS_WIN32 */
306 G_LOCK_DEFINE_STATIC (main_context_list);
307 static GSList *main_context_list = NULL;
309 static gint timer_perturb = -1;
311 GSourceFuncs g_timeout_funcs =
319 GSourceFuncs g_child_watch_funcs =
321 g_child_watch_prepare,
323 g_child_watch_dispatch,
327 GSourceFuncs g_idle_funcs =
336 /* SunOS has poll, but doesn't provide a prototype. */
337 # if defined (sun) && !defined (__SVR4)
338 extern gint poll (GPollFD *ufds, guint nfsd, gint timeout);
340 #else /* !HAVE_POLL */
345 poll_rest (gboolean poll_msgs,
358 /* Wait for either messages or handles
359 * -> Use MsgWaitForMultipleObjectsEx
361 if (g_main_poll_debug)
362 g_print (" MsgWaitForMultipleObjectsEx(%d, %d)\n", nhandles, timeout);
364 ready = MsgWaitForMultipleObjectsEx (nhandles, handles, timeout,
365 QS_ALLINPUT, MWMO_ALERTABLE);
367 if (ready == WAIT_FAILED)
369 gchar *emsg = g_win32_error_message (GetLastError ());
370 g_warning ("MsgWaitForMultipleObjectsEx failed: %s", emsg);
374 else if (nhandles == 0)
376 /* No handles to wait for, just the timeout */
377 if (timeout == INFINITE)
381 SleepEx (timeout, TRUE);
382 ready = WAIT_TIMEOUT;
387 /* Wait for just handles
388 * -> Use WaitForMultipleObjectsEx
390 if (g_main_poll_debug)
391 g_print (" WaitForMultipleObjectsEx(%d, %d)\n", nhandles, timeout);
393 ready = WaitForMultipleObjectsEx (nhandles, handles, FALSE, timeout, TRUE);
394 if (ready == WAIT_FAILED)
396 gchar *emsg = g_win32_error_message (GetLastError ());
397 g_warning ("WaitForMultipleObjectsEx failed: %s", emsg);
402 if (g_main_poll_debug)
403 g_print (" wait returns %ld%s\n",
405 (ready == WAIT_FAILED ? " (WAIT_FAILED)" :
406 (ready == WAIT_TIMEOUT ? " (WAIT_TIMEOUT)" :
407 (poll_msgs && ready == WAIT_OBJECT_0 + nhandles ? " (msg)" : ""))));
409 if (ready == WAIT_FAILED)
411 else if (ready == WAIT_TIMEOUT ||
412 ready == WAIT_IO_COMPLETION)
414 else if (poll_msgs && ready == WAIT_OBJECT_0 + nhandles)
416 for (f = fds; f < &fds[nfds]; ++f)
417 if (f->fd == G_WIN32_MSG_HANDLE && f->events & G_IO_IN)
418 f->revents |= G_IO_IN;
420 /* If we have a timeout, or no handles to poll, be satisfied
421 * with just noticing we have messages waiting.
423 if (timeout != 0 || nhandles == 0)
426 /* If no timeout and handles to poll, recurse to poll them,
429 recursed_result = poll_rest (FALSE, handles, nhandles, fds, nfds, 0);
430 return (recursed_result == -1) ? -1 : 1 + recursed_result;
432 else if (ready >= WAIT_OBJECT_0 && ready < WAIT_OBJECT_0 + nhandles)
434 for (f = fds; f < &fds[nfds]; ++f)
436 if ((HANDLE) f->fd == handles[ready - WAIT_OBJECT_0])
438 f->revents = f->events;
439 if (g_main_poll_debug)
440 g_print (" got event %p\n", (HANDLE) f->fd);
444 /* If no timeout and polling several handles, recurse to poll
447 if (timeout == 0 && nhandles > 1)
449 /* Remove the handle that fired */
450 if (ready < nhandles - 1)
451 memmove (handles + ready - WAIT_OBJECT_0, handles + ready - WAIT_OBJECT_0 + 1, nhandles - ready - 1);
453 recursed_result = poll_rest (FALSE, handles, nhandles, fds, nfds, 0);
454 return (recursed_result == -1) ? -1 : 1 + recursed_result;
464 g_poll (GPollFD *fds,
468 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
469 gboolean poll_msgs = FALSE;
474 if (g_main_poll_debug)
475 g_print ("g_poll: waiting for");
477 for (f = fds; f < &fds[nfds]; ++f)
478 if (f->fd == G_WIN32_MSG_HANDLE && (f->events & G_IO_IN))
480 if (g_main_poll_debug && !poll_msgs)
486 /* Don't add the same handle several times into the array, as
487 * docs say that is not allowed, even if it actually does seem
492 for (i = 0; i < nhandles; i++)
493 if (handles[i] == (HANDLE) f->fd)
498 if (nhandles == MAXIMUM_WAIT_OBJECTS)
500 g_warning ("Too many handles to wait for!\n");
505 if (g_main_poll_debug)
506 g_print (" %p", (HANDLE) f->fd);
507 handles[nhandles++] = (HANDLE) f->fd;
512 if (g_main_poll_debug)
515 for (f = fds; f < &fds[nfds]; ++f)
521 /* Polling for several things? */
522 if (nhandles > 1 || (nhandles > 0 && poll_msgs))
524 /* First check if one or several of them are immediately
527 retval = poll_rest (poll_msgs, handles, nhandles, fds, nfds, 0);
529 /* If not, and we have a significant timeout, poll again with
530 * timeout then. Note that this will return indication for only
531 * one event, or only for messages. We ignore timeouts less than
532 * ten milliseconds as they are mostly pointless on Windows, the
533 * MsgWaitForMultipleObjectsEx() call will timeout right away
536 if (retval == 0 && (timeout == INFINITE || timeout >= 10))
537 retval = poll_rest (poll_msgs, handles, nhandles, fds, nfds, timeout);
541 /* Just polling for one thing, so no need to check first if
542 * available immediately
544 retval = poll_rest (poll_msgs, handles, nhandles, fds, nfds, timeout);
548 for (f = fds; f < &fds[nfds]; ++f)
554 #else /* !G_OS_WIN32 */
556 /* The following implementation of poll() comes from the GNU C Library.
557 * Copyright (C) 1994, 1996, 1997 Free Software Foundation, Inc.
560 #include <string.h> /* for bzero on BSD systems */
562 #ifdef HAVE_SYS_SELECT_H
563 #include <sys/select.h>
564 #endif /* HAVE_SYS_SELECT_H */
568 #endif /* G_OS_BEOS */
571 # define SELECT_MASK fd_set
572 #else /* !NO_FD_SET */
574 typedef long fd_mask;
577 # define SELECT_MASK void
579 # define SELECT_MASK int
580 # endif /* !_IBMR2 */
581 #endif /* !NO_FD_SET */
584 g_poll (GPollFD *fds,
589 SELECT_MASK rset, wset, xset;
598 for (f = fds; f < &fds[nfds]; ++f)
601 if (f->events & G_IO_IN)
602 FD_SET (f->fd, &rset);
603 if (f->events & G_IO_OUT)
604 FD_SET (f->fd, &wset);
605 if (f->events & G_IO_PRI)
606 FD_SET (f->fd, &xset);
607 if (f->fd > maxfd && (f->events & (G_IO_IN|G_IO_OUT|G_IO_PRI)))
611 tv.tv_sec = timeout / 1000;
612 tv.tv_usec = (timeout % 1000) * 1000;
614 ready = select (maxfd + 1, &rset, &wset, &xset,
615 timeout == -1 ? NULL : &tv);
617 for (f = fds; f < &fds[nfds]; ++f)
622 if (FD_ISSET (f->fd, &rset))
623 f->revents |= G_IO_IN;
624 if (FD_ISSET (f->fd, &wset))
625 f->revents |= G_IO_OUT;
626 if (FD_ISSET (f->fd, &xset))
627 f->revents |= G_IO_PRI;
634 #endif /* !G_OS_WIN32 */
636 #endif /* !HAVE_POLL */
639 * g_main_context_ref:
640 * @context: a #GMainContext
642 * Increases the reference count on a #GMainContext object by one.
644 * Returns: the @context that was passed in (since 2.6)
647 g_main_context_ref (GMainContext *context)
649 g_return_val_if_fail (context != NULL, NULL);
650 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
652 g_atomic_int_inc (&context->ref_count);
658 poll_rec_list_free (GMainContext *context,
661 g_slice_free_chain (GPollRec, list, next);
665 * g_main_context_unref:
666 * @context: a #GMainContext
668 * Decreases the reference count on a #GMainContext object by one. If
669 * the result is zero, free the context and free all associated memory.
672 g_main_context_unref (GMainContext *context)
675 g_return_if_fail (context != NULL);
676 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
678 if (!g_atomic_int_dec_and_test (&context->ref_count))
681 G_LOCK (main_context_list);
682 main_context_list = g_slist_remove (main_context_list, context);
683 G_UNLOCK (main_context_list);
685 source = context->source_list;
688 GSource *next = source->next;
689 g_source_destroy_internal (source, context, FALSE);
693 #ifdef G_THREADS_ENABLED
694 g_static_mutex_free (&context->mutex);
697 g_ptr_array_free (context->pending_dispatches, TRUE);
698 g_free (context->cached_poll_array);
700 poll_rec_list_free (context, context->poll_records);
702 #ifdef G_THREADS_ENABLED
703 if (g_thread_supported())
706 close (context->wake_up_pipe[0]);
707 close (context->wake_up_pipe[1]);
709 CloseHandle (context->wake_up_semaphore);
713 main_contexts_without_pipe = g_slist_remove (main_contexts_without_pipe,
716 if (context->cond != NULL)
717 g_cond_free (context->cond);
723 #ifdef G_THREADS_ENABLED
725 g_main_context_init_pipe (GMainContext *context)
728 if (context->wake_up_pipe[0] != -1)
730 if (pipe (context->wake_up_pipe) < 0)
731 g_error ("Cannot create pipe main loop wake-up: %s\n",
734 fcntl (context->wake_up_pipe[0], F_SETFD, FD_CLOEXEC);
735 fcntl (context->wake_up_pipe[1], F_SETFD, FD_CLOEXEC);
737 context->wake_up_rec.fd = context->wake_up_pipe[0];
738 context->wake_up_rec.events = G_IO_IN;
740 if (context->wake_up_semaphore != NULL)
742 context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
743 if (context->wake_up_semaphore == NULL)
744 g_error ("Cannot create wake-up semaphore: %s",
745 g_win32_error_message (GetLastError ()));
746 context->wake_up_rec.fd = (gintptr) context->wake_up_semaphore;
747 context->wake_up_rec.events = G_IO_IN;
749 if (g_main_poll_debug)
750 g_print ("wake-up semaphore: %p\n", context->wake_up_semaphore);
752 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
756 _g_main_thread_init (void)
758 GSList *curr = main_contexts_without_pipe;
761 g_main_context_init_pipe ((GMainContext *)curr->data);
764 g_slist_free (main_contexts_without_pipe);
765 main_contexts_without_pipe = NULL;
767 #endif /* G_THREADS_ENABLED */
770 * g_main_context_new:
772 * Creates a new #GMainContext structure.
774 * Return value: the new #GMainContext
777 g_main_context_new (void)
779 GMainContext *context = g_new0 (GMainContext, 1);
781 #ifdef G_MAIN_POLL_DEBUG
783 static gboolean beenhere = FALSE;
787 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
788 g_main_poll_debug = TRUE;
794 #ifdef G_THREADS_ENABLED
795 g_static_mutex_init (&context->mutex);
797 context->owner = NULL;
798 context->waiters = NULL;
801 context->wake_up_pipe[0] = -1;
802 context->wake_up_pipe[1] = -1;
804 context->wake_up_semaphore = NULL;
808 context->ref_count = 1;
810 context->next_id = 1;
812 context->source_list = NULL;
815 context->poll_func = (GPollFunc)poll;
817 context->poll_func = g_poll;
820 context->cached_poll_array = NULL;
821 context->cached_poll_array_size = 0;
823 context->pending_dispatches = g_ptr_array_new ();
825 context->time_is_current = FALSE;
827 #ifdef G_THREADS_ENABLED
828 if (g_thread_supported ())
829 g_main_context_init_pipe (context);
831 main_contexts_without_pipe = g_slist_prepend (main_contexts_without_pipe,
835 G_LOCK (main_context_list);
836 main_context_list = g_slist_append (main_context_list, context);
838 #ifdef G_MAIN_POLL_DEBUG
839 if (g_main_poll_debug)
840 g_print ("created context=%p\n", context);
843 G_UNLOCK (main_context_list);
849 * g_main_context_default:
851 * Returns the default main context. This is the main context used
852 * for main loop functions when a main loop is not explicitly
855 * Return value: the default main context.
858 g_main_context_default (void)
864 if (!default_main_context)
866 default_main_context = g_main_context_new ();
867 #ifdef G_MAIN_POLL_DEBUG
868 if (g_main_poll_debug)
869 g_print ("default context=%p\n", default_main_context);
873 G_UNLOCK (main_loop);
875 return default_main_context;
878 /* Hooks for adding to the main loop */
882 * @source_funcs: structure containing functions that implement
883 * the sources behavior.
884 * @struct_size: size of the #GSource structure to create.
886 * Creates a new #GSource structure. The size is specified to
887 * allow creating structures derived from #GSource that contain
888 * additional data. The size passed in must be at least
889 * <literal>sizeof (GSource)</literal>.
891 * The source will not initially be associated with any #GMainContext
892 * and must be added to one with g_source_attach() before it will be
895 * Return value: the newly-created #GSource.
898 g_source_new (GSourceFuncs *source_funcs,
903 g_return_val_if_fail (source_funcs != NULL, NULL);
904 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
906 source = (GSource*) g_malloc0 (struct_size);
908 source->source_funcs = source_funcs;
909 source->ref_count = 1;
911 source->priority = G_PRIORITY_DEFAULT;
913 source->flags = G_HOOK_FLAG_ACTIVE;
915 /* NULL/0 initialization for all other fields */
920 /* Holds context's lock
923 g_source_list_add (GSource *source,
924 GMainContext *context)
926 GSource *tmp_source, *last_source;
929 tmp_source = context->source_list;
930 while (tmp_source && tmp_source->priority <= source->priority)
932 last_source = tmp_source;
933 tmp_source = tmp_source->next;
936 source->next = tmp_source;
938 tmp_source->prev = source;
940 source->prev = last_source;
942 last_source->next = source;
944 context->source_list = source;
947 /* Holds context's lock
950 g_source_list_remove (GSource *source,
951 GMainContext *context)
954 source->prev->next = source->next;
956 context->source_list = source->next;
959 source->next->prev = source->prev;
967 * @source: a #GSource
968 * @context: a #GMainContext (if %NULL, the default context will be used)
970 * Adds a #GSource to a @context so that it will be executed within
973 * Return value: the ID (greater than 0) for the source within the
977 g_source_attach (GSource *source,
978 GMainContext *context)
983 g_return_val_if_fail (source->context == NULL, 0);
984 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
987 context = g_main_context_default ();
989 LOCK_CONTEXT (context);
991 source->context = context;
992 result = source->source_id = context->next_id++;
995 g_source_list_add (source, context);
997 tmp_list = source->poll_fds;
1000 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
1001 tmp_list = tmp_list->next;
1004 #ifdef G_THREADS_ENABLED
1005 /* Now wake up the main loop if it is waiting in the poll() */
1006 g_main_context_wakeup_unlocked (context);
1009 UNLOCK_CONTEXT (context);
1015 g_source_destroy_internal (GSource *source,
1016 GMainContext *context,
1020 LOCK_CONTEXT (context);
1022 if (!SOURCE_DESTROYED (source))
1025 gpointer old_cb_data;
1026 GSourceCallbackFuncs *old_cb_funcs;
1028 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1030 old_cb_data = source->callback_data;
1031 old_cb_funcs = source->callback_funcs;
1033 source->callback_data = NULL;
1034 source->callback_funcs = NULL;
1038 UNLOCK_CONTEXT (context);
1039 old_cb_funcs->unref (old_cb_data);
1040 LOCK_CONTEXT (context);
1043 if (!SOURCE_BLOCKED (source))
1045 tmp_list = source->poll_fds;
1048 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1049 tmp_list = tmp_list->next;
1053 g_source_unref_internal (source, context, TRUE);
1057 UNLOCK_CONTEXT (context);
1062 * @source: a #GSource
1064 * Removes a source from its #GMainContext, if any, and mark it as
1065 * destroyed. The source cannot be subsequently added to another
1069 g_source_destroy (GSource *source)
1071 GMainContext *context;
1073 g_return_if_fail (source != NULL);
1075 context = source->context;
1078 g_source_destroy_internal (source, context, FALSE);
1080 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1085 * @source: a #GSource
1087 * Returns the numeric ID for a particular source. The ID of a source
1088 * is a positive integer which is unique within a particular main loop
1089 * context. The reverse
1090 * mapping from ID to source is done by g_main_context_find_source_by_id().
1092 * Return value: the ID (greater than 0) for the source
1095 g_source_get_id (GSource *source)
1099 g_return_val_if_fail (source != NULL, 0);
1100 g_return_val_if_fail (source->context != NULL, 0);
1102 LOCK_CONTEXT (source->context);
1103 result = source->source_id;
1104 UNLOCK_CONTEXT (source->context);
1110 * g_source_get_context:
1111 * @source: a #GSource
1113 * Gets the #GMainContext with which the source is associated.
1114 * Calling this function on a destroyed source is an error.
1116 * Return value: the #GMainContext with which the source is associated,
1117 * or %NULL if the context has not yet been added
1121 g_source_get_context (GSource *source)
1123 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1125 return source->context;
1129 * g_source_add_poll:
1130 * @source:a #GSource
1131 * @fd: a #GPollFD structure holding information about a file
1132 * descriptor to watch.
1134 * Adds a file descriptor to the set of file descriptors polled for
1135 * this source. This is usually combined with g_source_new() to add an
1136 * event source. The event source's check function will typically test
1137 * the @revents field in the #GPollFD struct and return %TRUE if events need
1141 g_source_add_poll (GSource *source,
1144 GMainContext *context;
1146 g_return_if_fail (source != NULL);
1147 g_return_if_fail (fd != NULL);
1148 g_return_if_fail (!SOURCE_DESTROYED (source));
1150 context = source->context;
1153 LOCK_CONTEXT (context);
1155 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1159 if (!SOURCE_BLOCKED (source))
1160 g_main_context_add_poll_unlocked (context, source->priority, fd);
1161 UNLOCK_CONTEXT (context);
1166 * g_source_remove_poll:
1167 * @source:a #GSource
1168 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1170 * Removes a file descriptor from the set of file descriptors polled for
1174 g_source_remove_poll (GSource *source,
1177 GMainContext *context;
1179 g_return_if_fail (source != NULL);
1180 g_return_if_fail (fd != NULL);
1181 g_return_if_fail (!SOURCE_DESTROYED (source));
1183 context = source->context;
1186 LOCK_CONTEXT (context);
1188 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1192 if (!SOURCE_BLOCKED (source))
1193 g_main_context_remove_poll_unlocked (context, fd);
1194 UNLOCK_CONTEXT (context);
1199 * g_source_set_callback_indirect:
1200 * @source: the source
1201 * @callback_data: pointer to callback data "object"
1202 * @callback_funcs: functions for reference counting @callback_data
1203 * and getting the callback and data
1205 * Sets the callback function storing the data as a refcounted callback
1206 * "object". This is used internally. Note that calling
1207 * g_source_set_callback_indirect() assumes
1208 * an initial reference count on @callback_data, and thus
1209 * @callback_funcs->unref will eventually be called once more
1210 * than @callback_funcs->ref.
1213 g_source_set_callback_indirect (GSource *source,
1214 gpointer callback_data,
1215 GSourceCallbackFuncs *callback_funcs)
1217 GMainContext *context;
1218 gpointer old_cb_data;
1219 GSourceCallbackFuncs *old_cb_funcs;
1221 g_return_if_fail (source != NULL);
1222 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1224 context = source->context;
1227 LOCK_CONTEXT (context);
1229 old_cb_data = source->callback_data;
1230 old_cb_funcs = source->callback_funcs;
1232 source->callback_data = callback_data;
1233 source->callback_funcs = callback_funcs;
1236 UNLOCK_CONTEXT (context);
1239 old_cb_funcs->unref (old_cb_data);
1243 g_source_callback_ref (gpointer cb_data)
1245 GSourceCallback *callback = cb_data;
1247 callback->ref_count++;
1252 g_source_callback_unref (gpointer cb_data)
1254 GSourceCallback *callback = cb_data;
1256 callback->ref_count--;
1257 if (callback->ref_count == 0)
1259 if (callback->notify)
1260 callback->notify (callback->data);
1266 g_source_callback_get (gpointer cb_data,
1271 GSourceCallback *callback = cb_data;
1273 *func = callback->func;
1274 *data = callback->data;
1277 static GSourceCallbackFuncs g_source_callback_funcs = {
1278 g_source_callback_ref,
1279 g_source_callback_unref,
1280 g_source_callback_get,
1284 * g_source_set_callback:
1285 * @source: the source
1286 * @func: a callback function
1287 * @data: the data to pass to callback function
1288 * @notify: a function to call when @data is no longer in use, or %NULL.
1290 * Sets the callback function for a source. The callback for a source is
1291 * called from the source's dispatch function.
1293 * The exact type of @func depends on the type of source; ie. you
1294 * should not count on @func being called with @data as its first
1297 * Typically, you won't use this function. Instead use functions specific
1298 * to the type of source you are using.
1301 g_source_set_callback (GSource *source,
1304 GDestroyNotify notify)
1306 GSourceCallback *new_callback;
1308 g_return_if_fail (source != NULL);
1310 new_callback = g_new (GSourceCallback, 1);
1312 new_callback->ref_count = 1;
1313 new_callback->func = func;
1314 new_callback->data = data;
1315 new_callback->notify = notify;
1317 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1322 * g_source_set_funcs:
1323 * @source: a #GSource
1324 * @funcs: the new #GSourceFuncs
1326 * Sets the source functions (can be used to override
1327 * default implementations) of an unattached source.
1332 g_source_set_funcs (GSource *source,
1333 GSourceFuncs *funcs)
1335 g_return_if_fail (source != NULL);
1336 g_return_if_fail (source->context == NULL);
1337 g_return_if_fail (source->ref_count > 0);
1338 g_return_if_fail (funcs != NULL);
1340 source->source_funcs = funcs;
1344 * g_source_set_priority:
1345 * @source: a #GSource
1346 * @priority: the new priority.
1348 * Sets the priority of a source. While the main loop is being
1349 * run, a source will be dispatched if it is ready to be dispatched and no sources
1350 * at a higher (numerically smaller) priority are ready to be dispatched.
1353 g_source_set_priority (GSource *source,
1357 GMainContext *context;
1359 g_return_if_fail (source != NULL);
1361 context = source->context;
1364 LOCK_CONTEXT (context);
1366 source->priority = priority;
1370 /* Remove the source from the context's source and then
1371 * add it back so it is sorted in the correct plcae
1373 g_source_list_remove (source, source->context);
1374 g_source_list_add (source, source->context);
1376 if (!SOURCE_BLOCKED (source))
1378 tmp_list = source->poll_fds;
1381 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1382 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1384 tmp_list = tmp_list->next;
1388 UNLOCK_CONTEXT (source->context);
1393 * g_source_get_priority:
1394 * @source: a #GSource
1396 * Gets the priority of a source.
1398 * Return value: the priority of the source
1401 g_source_get_priority (GSource *source)
1403 g_return_val_if_fail (source != NULL, 0);
1405 return source->priority;
1409 * g_source_set_can_recurse:
1410 * @source: a #GSource
1411 * @can_recurse: whether recursion is allowed for this source
1413 * Sets whether a source can be called recursively. If @can_recurse is
1414 * %TRUE, then while the source is being dispatched then this source
1415 * will be processed normally. Otherwise, all processing of this
1416 * source is blocked until the dispatch function returns.
1419 g_source_set_can_recurse (GSource *source,
1420 gboolean can_recurse)
1422 GMainContext *context;
1424 g_return_if_fail (source != NULL);
1426 context = source->context;
1429 LOCK_CONTEXT (context);
1432 source->flags |= G_SOURCE_CAN_RECURSE;
1434 source->flags &= ~G_SOURCE_CAN_RECURSE;
1437 UNLOCK_CONTEXT (context);
1441 * g_source_get_can_recurse:
1442 * @source: a #GSource
1444 * Checks whether a source is allowed to be called recursively.
1445 * see g_source_set_can_recurse().
1447 * Return value: whether recursion is allowed.
1450 g_source_get_can_recurse (GSource *source)
1452 g_return_val_if_fail (source != NULL, FALSE);
1454 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1459 * @source: a #GSource
1461 * Increases the reference count on a source by one.
1463 * Return value: @source
1466 g_source_ref (GSource *source)
1468 GMainContext *context;
1470 g_return_val_if_fail (source != NULL, NULL);
1472 context = source->context;
1475 LOCK_CONTEXT (context);
1477 source->ref_count++;
1480 UNLOCK_CONTEXT (context);
1485 /* g_source_unref() but possible to call within context lock
1488 g_source_unref_internal (GSource *source,
1489 GMainContext *context,
1492 gpointer old_cb_data = NULL;
1493 GSourceCallbackFuncs *old_cb_funcs = NULL;
1495 g_return_if_fail (source != NULL);
1497 if (!have_lock && context)
1498 LOCK_CONTEXT (context);
1500 source->ref_count--;
1501 if (source->ref_count == 0)
1503 old_cb_data = source->callback_data;
1504 old_cb_funcs = source->callback_funcs;
1506 source->callback_data = NULL;
1507 source->callback_funcs = NULL;
1509 if (context && !SOURCE_DESTROYED (source))
1511 g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1512 source->ref_count++;
1515 g_source_list_remove (source, context);
1517 if (source->source_funcs->finalize)
1518 source->source_funcs->finalize (source);
1520 g_slist_free (source->poll_fds);
1521 source->poll_fds = NULL;
1525 if (!have_lock && context)
1526 UNLOCK_CONTEXT (context);
1531 UNLOCK_CONTEXT (context);
1533 old_cb_funcs->unref (old_cb_data);
1536 LOCK_CONTEXT (context);
1542 * @source: a #GSource
1544 * Decreases the reference count of a source by one. If the
1545 * resulting reference count is zero the source and associated
1546 * memory will be destroyed.
1549 g_source_unref (GSource *source)
1551 g_return_if_fail (source != NULL);
1553 g_source_unref_internal (source, source->context, FALSE);
1557 * g_main_context_find_source_by_id:
1558 * @context: a #GMainContext (if %NULL, the default context will be used)
1559 * @source_id: the source ID, as returned by g_source_get_id().
1561 * Finds a #GSource given a pair of context and ID.
1563 * Return value: the #GSource if found, otherwise, %NULL
1566 g_main_context_find_source_by_id (GMainContext *context,
1571 g_return_val_if_fail (source_id > 0, NULL);
1573 if (context == NULL)
1574 context = g_main_context_default ();
1576 LOCK_CONTEXT (context);
1578 source = context->source_list;
1581 if (!SOURCE_DESTROYED (source) &&
1582 source->source_id == source_id)
1584 source = source->next;
1587 UNLOCK_CONTEXT (context);
1593 * g_main_context_find_source_by_funcs_user_data:
1594 * @context: a #GMainContext (if %NULL, the default context will be used).
1595 * @funcs: the @source_funcs passed to g_source_new().
1596 * @user_data: the user data from the callback.
1598 * Finds a source with the given source functions and user data. If
1599 * multiple sources exist with the same source function and user data,
1600 * the first one found will be returned.
1602 * Return value: the source, if one was found, otherwise %NULL
1605 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1606 GSourceFuncs *funcs,
1611 g_return_val_if_fail (funcs != NULL, NULL);
1613 if (context == NULL)
1614 context = g_main_context_default ();
1616 LOCK_CONTEXT (context);
1618 source = context->source_list;
1621 if (!SOURCE_DESTROYED (source) &&
1622 source->source_funcs == funcs &&
1623 source->callback_funcs)
1625 GSourceFunc callback;
1626 gpointer callback_data;
1628 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1630 if (callback_data == user_data)
1633 source = source->next;
1636 UNLOCK_CONTEXT (context);
1642 * g_main_context_find_source_by_user_data:
1643 * @context: a #GMainContext
1644 * @user_data: the user_data for the callback.
1646 * Finds a source with the given user data for the callback. If
1647 * multiple sources exist with the same user data, the first
1648 * one found will be returned.
1650 * Return value: the source, if one was found, otherwise %NULL
1653 g_main_context_find_source_by_user_data (GMainContext *context,
1658 if (context == NULL)
1659 context = g_main_context_default ();
1661 LOCK_CONTEXT (context);
1663 source = context->source_list;
1666 if (!SOURCE_DESTROYED (source) &&
1667 source->callback_funcs)
1669 GSourceFunc callback;
1670 gpointer callback_data = NULL;
1672 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1674 if (callback_data == user_data)
1677 source = source->next;
1680 UNLOCK_CONTEXT (context);
1687 * @tag: the ID of the source to remove.
1689 * Removes the source with the given id from the default main context.
1691 * a #GSource is given by g_source_get_id(), or will be returned by the
1692 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1693 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1694 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1696 * See also g_source_destroy().
1698 * Return value: %TRUE if the source was found and removed.
1701 g_source_remove (guint tag)
1705 g_return_val_if_fail (tag > 0, FALSE);
1707 source = g_main_context_find_source_by_id (NULL, tag);
1709 g_source_destroy (source);
1711 return source != NULL;
1715 * g_source_remove_by_user_data:
1716 * @user_data: the user_data for the callback.
1718 * Removes a source from the default main loop context given the user
1719 * data for the callback. If multiple sources exist with the same user
1720 * data, only one will be destroyed.
1722 * Return value: %TRUE if a source was found and removed.
1725 g_source_remove_by_user_data (gpointer user_data)
1729 source = g_main_context_find_source_by_user_data (NULL, user_data);
1732 g_source_destroy (source);
1740 * g_source_remove_by_funcs_user_data:
1741 * @funcs: The @source_funcs passed to g_source_new()
1742 * @user_data: the user data for the callback
1744 * Removes a source from the default main loop context given the
1745 * source functions and user data. If multiple sources exist with the
1746 * same source functions and user data, only one will be destroyed.
1748 * Return value: %TRUE if a source was found and removed.
1751 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1756 g_return_val_if_fail (funcs != NULL, FALSE);
1758 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1761 g_source_destroy (source);
1769 * g_get_current_time:
1770 * @result: #GTimeVal structure in which to store current time.
1772 * Equivalent to the UNIX gettimeofday() function, but portable.
1775 g_get_current_time (GTimeVal *result)
1780 g_return_if_fail (result != NULL);
1782 /*this is required on alpha, there the timeval structs are int's
1783 not longs and a cast only would fail horribly*/
1784 gettimeofday (&r, NULL);
1785 result->tv_sec = r.tv_sec;
1786 result->tv_usec = r.tv_usec;
1791 g_return_if_fail (result != NULL);
1793 GetSystemTimeAsFileTime (&ft);
1794 memmove (&time64, &ft, sizeof (FILETIME));
1796 /* Convert from 100s of nanoseconds since 1601-01-01
1797 * to Unix epoch. Yes, this is Y2038 unsafe.
1799 time64 -= G_GINT64_CONSTANT (116444736000000000);
1802 result->tv_sec = time64 / 1000000;
1803 result->tv_usec = time64 % 1000000;
1808 g_main_dispatch_free (gpointer dispatch)
1810 g_slice_free (GMainDispatch, dispatch);
1813 /* Running the main loop */
1815 static GMainDispatch *
1818 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
1819 GMainDispatch *dispatch = g_static_private_get (&depth_private);
1822 dispatch = g_slice_new0 (GMainDispatch);
1823 g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
1832 * Returns the depth of the stack of calls to
1833 * g_main_context_dispatch() on any #GMainContext in the current thread.
1834 * That is, when called from the toplevel, it gives 0. When
1835 * called from within a callback from g_main_context_iteration()
1836 * (or g_main_loop_run(), etc.) it returns 1. When called from within
1837 * a callback to a recursive call to g_main_context_iterate(),
1838 * it returns 2. And so forth.
1840 * This function is useful in a situation like the following:
1841 * Imagine an extremely simple "garbage collected" system.
1844 * static GList *free_list;
1847 * allocate_memory (gsize size)
1849 * gpointer result = g_malloc (size);
1850 * free_list = g_list_prepend (free_list, result);
1855 * free_allocated_memory (void)
1858 * for (l = free_list; l; l = l->next);
1860 * g_list_free (free_list);
1868 * g_main_context_iteration (NULL, TRUE);
1869 * free_allocated_memory();
1873 * This works from an application, however, if you want to do the same
1874 * thing from a library, it gets more difficult, since you no longer
1875 * control the main loop. You might think you can simply use an idle
1876 * function to make the call to free_allocated_memory(), but that
1877 * doesn't work, since the idle function could be called from a
1878 * recursive callback. This can be fixed by using g_main_depth()
1882 * allocate_memory (gsize size)
1884 * FreeListBlock *block = g_new (FreeListBlock, 1);
1885 * block->mem = g_malloc (size);
1886 * block->depth = g_main_depth ();
1887 * free_list = g_list_prepend (free_list, block);
1888 * return block->mem;
1892 * free_allocated_memory (void)
1896 * int depth = g_main_depth ();
1897 * for (l = free_list; l; );
1899 * GList *next = l->next;
1900 * FreeListBlock *block = l->data;
1901 * if (block->depth > depth)
1903 * g_free (block->mem);
1905 * free_list = g_list_delete_link (free_list, l);
1913 * There is a temptation to use g_main_depth() to solve
1914 * problems with reentrancy. For instance, while waiting for data
1915 * to be received from the network in response to a menu item,
1916 * the menu item might be selected again. It might seem that
1917 * one could make the menu item's callback return immediately
1918 * and do nothing if g_main_depth() returns a value greater than 1.
1919 * However, this should be avoided since the user then sees selecting
1920 * the menu item do nothing. Furthermore, you'll find yourself adding
1921 * these checks all over your code, since there are doubtless many,
1922 * many things that the user could do. Instead, you can use the
1923 * following techniques:
1928 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
1929 * the user from interacting with elements while the main
1930 * loop is recursing.
1935 * Avoid main loop recursion in situations where you can't handle
1936 * arbitrary callbacks. Instead, structure your code so that you
1937 * simply return to the main loop and then get called again when
1938 * there is more work to do.
1943 * Return value: The main loop recursion level in the current thread
1948 GMainDispatch *dispatch = get_dispatch ();
1949 return dispatch->depth;
1953 * g_main_current_source:
1955 * Returns the currently firing source for this thread.
1957 * Return value: The currently firing source or %NULL.
1962 g_main_current_source (void)
1964 GMainDispatch *dispatch = get_dispatch ();
1965 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
1969 * g_source_is_destroyed:
1970 * @source: a #GSource
1972 * Returns whether @source has been destroyed.
1974 * This is important when you operate upon your objects
1975 * from within idle handlers, but may have freed the object
1976 * before the dispatch of your idle handler.
1980 * idle_callback (gpointer data)
1982 * SomeWidget *self = data;
1984 * GDK_THREADS_ENTER (<!-- -->);
1985 * /<!-- -->* do stuff with self *<!-- -->/
1986 * self->idle_id = 0;
1987 * GDK_THREADS_LEAVE (<!-- -->);
1993 * some_widget_do_stuff_later (SomeWidget *self)
1995 * self->idle_id = g_idle_add (idle_callback, self);
1999 * some_widget_finalize (GObject *object)
2001 * SomeWidget *self = SOME_WIDGET (object);
2003 * if (self->idle_id)
2004 * g_source_remove (self->idle_id);
2006 * G_OBJECT_CLASS (parent_class)->finalize (object);
2010 * This will fail in a multi-threaded application if the
2011 * widget is destroyed before the idle handler fires due
2012 * to the use after free in the callback. A solution, to
2013 * this particular problem, is to check to if the source
2014 * has already been destroy within the callback.
2018 * idle_callback (gpointer data)
2020 * SomeWidget *self = data;
2022 * GDK_THREADS_ENTER ();
2023 * if (!g_source_is_destroyed (g_main_current_source ()))
2025 * /<!-- -->* do stuff with self *<!-- -->/
2027 * GDK_THREADS_LEAVE ();
2033 * Return value: %TRUE if the source has been destroyed
2038 g_source_is_destroyed (GSource *source)
2040 return SOURCE_DESTROYED (source);
2044 /* Temporarily remove all this source's file descriptors from the
2045 * poll(), so that if data comes available for one of the file descriptors
2046 * we don't continually spin in the poll()
2048 /* HOLDS: source->context's lock */
2050 block_source (GSource *source)
2054 g_return_if_fail (!SOURCE_BLOCKED (source));
2056 tmp_list = source->poll_fds;
2059 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2060 tmp_list = tmp_list->next;
2064 /* HOLDS: source->context's lock */
2066 unblock_source (GSource *source)
2070 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
2071 g_return_if_fail (!SOURCE_DESTROYED (source));
2073 tmp_list = source->poll_fds;
2076 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2077 tmp_list = tmp_list->next;
2081 /* HOLDS: context's lock */
2083 g_main_dispatch (GMainContext *context)
2085 GMainDispatch *current = get_dispatch ();
2088 for (i = 0; i < context->pending_dispatches->len; i++)
2090 GSource *source = context->pending_dispatches->pdata[i];
2092 context->pending_dispatches->pdata[i] = NULL;
2095 source->flags &= ~G_SOURCE_READY;
2097 if (!SOURCE_DESTROYED (source))
2099 gboolean was_in_call;
2100 gpointer user_data = NULL;
2101 GSourceFunc callback = NULL;
2102 GSourceCallbackFuncs *cb_funcs;
2104 gboolean need_destroy;
2106 gboolean (*dispatch) (GSource *,
2109 GSList current_source_link;
2111 dispatch = source->source_funcs->dispatch;
2112 cb_funcs = source->callback_funcs;
2113 cb_data = source->callback_data;
2116 cb_funcs->ref (cb_data);
2118 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2119 block_source (source);
2121 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2122 source->flags |= G_HOOK_FLAG_IN_CALL;
2125 cb_funcs->get (cb_data, source, &callback, &user_data);
2127 UNLOCK_CONTEXT (context);
2130 /* The on-stack allocation of the GSList is unconventional, but
2131 * we know that the lifetime of the link is bounded to this
2132 * function as the link is kept in a thread specific list and
2133 * not manipulated outside of this function and its descendants.
2134 * Avoiding the overhead of a g_slist_alloc() is useful as many
2135 * applications do little more than dispatch events.
2137 * This is a performance hack - do not revert to g_slist_prepend()!
2139 current_source_link.data = source;
2140 current_source_link.next = current->dispatching_sources;
2141 current->dispatching_sources = ¤t_source_link;
2142 need_destroy = ! dispatch (source,
2145 g_assert (current->dispatching_sources == ¤t_source_link);
2146 current->dispatching_sources = current_source_link.next;
2150 cb_funcs->unref (cb_data);
2152 LOCK_CONTEXT (context);
2155 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2157 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2158 !SOURCE_DESTROYED (source))
2159 unblock_source (source);
2161 /* Note: this depends on the fact that we can't switch
2162 * sources from one main context to another
2164 if (need_destroy && !SOURCE_DESTROYED (source))
2166 g_assert (source->context == context);
2167 g_source_destroy_internal (source, context, TRUE);
2171 SOURCE_UNREF (source, context);
2174 g_ptr_array_set_size (context->pending_dispatches, 0);
2177 /* Holds context's lock */
2178 static inline GSource *
2179 next_valid_source (GMainContext *context,
2182 GSource *new_source = source ? source->next : context->source_list;
2186 if (!SOURCE_DESTROYED (new_source))
2188 new_source->ref_count++;
2192 new_source = new_source->next;
2196 SOURCE_UNREF (source, context);
2202 * g_main_context_acquire:
2203 * @context: a #GMainContext
2205 * Tries to become the owner of the specified context.
2206 * If some other thread is the owner of the context,
2207 * returns %FALSE immediately. Ownership is properly
2208 * recursive: the owner can require ownership again
2209 * and will release ownership when g_main_context_release()
2210 * is called as many times as g_main_context_acquire().
2212 * You must be the owner of a context before you
2213 * can call g_main_context_prepare(), g_main_context_query(),
2214 * g_main_context_check(), g_main_context_dispatch().
2216 * Return value: %TRUE if the operation succeeded, and
2217 * this thread is now the owner of @context.
2220 g_main_context_acquire (GMainContext *context)
2222 #ifdef G_THREADS_ENABLED
2223 gboolean result = FALSE;
2224 GThread *self = G_THREAD_SELF;
2226 if (context == NULL)
2227 context = g_main_context_default ();
2229 LOCK_CONTEXT (context);
2231 if (!context->owner)
2233 context->owner = self;
2234 g_assert (context->owner_count == 0);
2237 if (context->owner == self)
2239 context->owner_count++;
2243 UNLOCK_CONTEXT (context);
2246 #else /* !G_THREADS_ENABLED */
2248 #endif /* G_THREADS_ENABLED */
2252 * g_main_context_release:
2253 * @context: a #GMainContext
2255 * Releases ownership of a context previously acquired by this thread
2256 * with g_main_context_acquire(). If the context was acquired multiple
2257 * times, the ownership will be released only when g_main_context_release()
2258 * is called as many times as it was acquired.
2261 g_main_context_release (GMainContext *context)
2263 #ifdef G_THREADS_ENABLED
2264 if (context == NULL)
2265 context = g_main_context_default ();
2267 LOCK_CONTEXT (context);
2269 context->owner_count--;
2270 if (context->owner_count == 0)
2272 context->owner = NULL;
2274 if (context->waiters)
2276 GMainWaiter *waiter = context->waiters->data;
2277 gboolean loop_internal_waiter =
2278 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
2279 context->waiters = g_slist_delete_link (context->waiters,
2281 if (!loop_internal_waiter)
2282 g_mutex_lock (waiter->mutex);
2284 g_cond_signal (waiter->cond);
2286 if (!loop_internal_waiter)
2287 g_mutex_unlock (waiter->mutex);
2291 UNLOCK_CONTEXT (context);
2292 #endif /* G_THREADS_ENABLED */
2296 * g_main_context_wait:
2297 * @context: a #GMainContext
2298 * @cond: a condition variable
2299 * @mutex: a mutex, currently held
2301 * Tries to become the owner of the specified context,
2302 * as with g_main_context_acquire(). But if another thread
2303 * is the owner, atomically drop @mutex and wait on @cond until
2304 * that owner releases ownership or until @cond is signaled, then
2305 * try again (once) to become the owner.
2307 * Return value: %TRUE if the operation succeeded, and
2308 * this thread is now the owner of @context.
2311 g_main_context_wait (GMainContext *context,
2315 #ifdef G_THREADS_ENABLED
2316 gboolean result = FALSE;
2317 GThread *self = G_THREAD_SELF;
2318 gboolean loop_internal_waiter;
2320 if (context == NULL)
2321 context = g_main_context_default ();
2323 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2325 if (!loop_internal_waiter)
2326 LOCK_CONTEXT (context);
2328 if (context->owner && context->owner != self)
2333 waiter.mutex = mutex;
2335 context->waiters = g_slist_append (context->waiters, &waiter);
2337 if (!loop_internal_waiter)
2338 UNLOCK_CONTEXT (context);
2339 g_cond_wait (cond, mutex);
2340 if (!loop_internal_waiter)
2341 LOCK_CONTEXT (context);
2343 context->waiters = g_slist_remove (context->waiters, &waiter);
2346 if (!context->owner)
2348 context->owner = self;
2349 g_assert (context->owner_count == 0);
2352 if (context->owner == self)
2354 context->owner_count++;
2358 if (!loop_internal_waiter)
2359 UNLOCK_CONTEXT (context);
2362 #else /* !G_THREADS_ENABLED */
2364 #endif /* G_THREADS_ENABLED */
2368 * g_main_context_prepare:
2369 * @context: a #GMainContext
2370 * @priority: location to store priority of highest priority
2371 * source already ready.
2373 * Prepares to poll sources within a main loop. The resulting information
2374 * for polling is determined by calling g_main_context_query ().
2376 * Return value: %TRUE if some source is ready to be dispatched
2380 g_main_context_prepare (GMainContext *context,
2385 gint current_priority = G_MAXINT;
2388 if (context == NULL)
2389 context = g_main_context_default ();
2391 LOCK_CONTEXT (context);
2393 context->time_is_current = FALSE;
2395 if (context->in_check_or_prepare)
2397 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2398 "prepare() member.");
2399 UNLOCK_CONTEXT (context);
2403 #ifdef G_THREADS_ENABLED
2404 if (context->poll_waiting)
2406 g_warning("g_main_context_prepare(): main loop already active in another thread");
2407 UNLOCK_CONTEXT (context);
2411 context->poll_waiting = TRUE;
2412 #endif /* G_THREADS_ENABLED */
2415 /* If recursing, finish up current dispatch, before starting over */
2416 if (context->pending_dispatches)
2419 g_main_dispatch (context, ¤t_time);
2421 UNLOCK_CONTEXT (context);
2426 /* If recursing, clear list of pending dispatches */
2428 for (i = 0; i < context->pending_dispatches->len; i++)
2430 if (context->pending_dispatches->pdata[i])
2431 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2433 g_ptr_array_set_size (context->pending_dispatches, 0);
2435 /* Prepare all sources */
2437 context->timeout = -1;
2439 source = next_valid_source (context, NULL);
2442 gint source_timeout = -1;
2444 if ((n_ready > 0) && (source->priority > current_priority))
2446 SOURCE_UNREF (source, context);
2449 if (SOURCE_BLOCKED (source))
2452 if (!(source->flags & G_SOURCE_READY))
2455 gboolean (*prepare) (GSource *source,
2458 prepare = source->source_funcs->prepare;
2459 context->in_check_or_prepare++;
2460 UNLOCK_CONTEXT (context);
2462 result = (*prepare) (source, &source_timeout);
2464 LOCK_CONTEXT (context);
2465 context->in_check_or_prepare--;
2468 source->flags |= G_SOURCE_READY;
2471 if (source->flags & G_SOURCE_READY)
2474 current_priority = source->priority;
2475 context->timeout = 0;
2478 if (source_timeout >= 0)
2480 if (context->timeout < 0)
2481 context->timeout = source_timeout;
2483 context->timeout = MIN (context->timeout, source_timeout);
2487 source = next_valid_source (context, source);
2490 UNLOCK_CONTEXT (context);
2493 *priority = current_priority;
2495 return (n_ready > 0);
2499 * g_main_context_query:
2500 * @context: a #GMainContext
2501 * @max_priority: maximum priority source to check
2502 * @timeout_: location to store timeout to be used in polling
2503 * @fds: location to store #GPollFD records that need to be polled.
2504 * @n_fds: length of @fds.
2506 * Determines information necessary to poll this main loop.
2508 * Return value: the number of records actually stored in @fds,
2509 * or, if more than @n_fds records need to be stored, the number
2510 * of records that need to be stored.
2513 g_main_context_query (GMainContext *context,
2522 LOCK_CONTEXT (context);
2524 pollrec = context->poll_records;
2526 while (pollrec && max_priority >= pollrec->priority)
2528 if (pollrec->fd->events)
2532 fds[n_poll].fd = pollrec->fd->fd;
2533 /* In direct contradiction to the Unix98 spec, IRIX runs into
2534 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2535 * flags in the events field of the pollfd while it should
2536 * just ignoring them. So we mask them out here.
2538 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2539 fds[n_poll].revents = 0;
2544 pollrec = pollrec->next;
2547 #ifdef G_THREADS_ENABLED
2548 context->poll_changed = FALSE;
2553 *timeout = context->timeout;
2555 context->time_is_current = FALSE;
2558 UNLOCK_CONTEXT (context);
2564 * g_main_context_check:
2565 * @context: a #GMainContext
2566 * @max_priority: the maximum numerical priority of sources to check
2567 * @fds: array of #GPollFD's that was passed to the last call to
2568 * g_main_context_query()
2569 * @n_fds: return value of g_main_context_query()
2571 * Passes the results of polling back to the main loop.
2573 * Return value: %TRUE if some sources are ready to be dispatched.
2576 g_main_context_check (GMainContext *context,
2586 LOCK_CONTEXT (context);
2588 if (context->in_check_or_prepare)
2590 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2591 "prepare() member.");
2592 UNLOCK_CONTEXT (context);
2596 #ifdef G_THREADS_ENABLED
2597 if (!context->poll_waiting)
2601 read (context->wake_up_pipe[0], &a, 1);
2605 context->poll_waiting = FALSE;
2607 /* If the set of poll file descriptors changed, bail out
2608 * and let the main loop rerun
2610 if (context->poll_changed)
2612 UNLOCK_CONTEXT (context);
2615 #endif /* G_THREADS_ENABLED */
2617 pollrec = context->poll_records;
2621 if (pollrec->fd->events)
2623 pollrec->fd->revents = fds[i].revents;
2626 pollrec = pollrec->next;
2629 source = next_valid_source (context, NULL);
2632 if ((n_ready > 0) && (source->priority > max_priority))
2634 SOURCE_UNREF (source, context);
2637 if (SOURCE_BLOCKED (source))
2640 if (!(source->flags & G_SOURCE_READY))
2643 gboolean (*check) (GSource *source);
2645 check = source->source_funcs->check;
2647 context->in_check_or_prepare++;
2648 UNLOCK_CONTEXT (context);
2650 result = (*check) (source);
2652 LOCK_CONTEXT (context);
2653 context->in_check_or_prepare--;
2656 source->flags |= G_SOURCE_READY;
2659 if (source->flags & G_SOURCE_READY)
2661 source->ref_count++;
2662 g_ptr_array_add (context->pending_dispatches, source);
2666 /* never dispatch sources with less priority than the first
2667 * one we choose to dispatch
2669 max_priority = source->priority;
2673 source = next_valid_source (context, source);
2676 UNLOCK_CONTEXT (context);
2682 * g_main_context_dispatch:
2683 * @context: a #GMainContext
2685 * Dispatches all pending sources.
2688 g_main_context_dispatch (GMainContext *context)
2690 LOCK_CONTEXT (context);
2692 if (context->pending_dispatches->len > 0)
2694 g_main_dispatch (context);
2697 UNLOCK_CONTEXT (context);
2700 /* HOLDS context lock */
2702 g_main_context_iterate (GMainContext *context,
2709 gboolean some_ready;
2710 gint nfds, allocated_nfds;
2711 GPollFD *fds = NULL;
2713 UNLOCK_CONTEXT (context);
2715 #ifdef G_THREADS_ENABLED
2716 if (!g_main_context_acquire (context))
2718 gboolean got_ownership;
2720 g_return_val_if_fail (g_thread_supported (), FALSE);
2725 LOCK_CONTEXT (context);
2728 context->cond = g_cond_new ();
2730 got_ownership = g_main_context_wait (context,
2732 g_static_mutex_get_mutex (&context->mutex));
2736 UNLOCK_CONTEXT (context);
2741 LOCK_CONTEXT (context);
2742 #endif /* G_THREADS_ENABLED */
2744 if (!context->cached_poll_array)
2746 context->cached_poll_array_size = context->n_poll_records;
2747 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2750 allocated_nfds = context->cached_poll_array_size;
2751 fds = context->cached_poll_array;
2753 UNLOCK_CONTEXT (context);
2755 g_main_context_prepare (context, &max_priority);
2757 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
2758 allocated_nfds)) > allocated_nfds)
2760 LOCK_CONTEXT (context);
2762 context->cached_poll_array_size = allocated_nfds = nfds;
2763 context->cached_poll_array = fds = g_new (GPollFD, nfds);
2764 UNLOCK_CONTEXT (context);
2770 g_main_context_poll (context, timeout, max_priority, fds, nfds);
2772 some_ready = g_main_context_check (context, max_priority, fds, nfds);
2775 g_main_context_dispatch (context);
2777 #ifdef G_THREADS_ENABLED
2778 g_main_context_release (context);
2779 #endif /* G_THREADS_ENABLED */
2781 LOCK_CONTEXT (context);
2787 * g_main_context_pending:
2788 * @context: a #GMainContext (if %NULL, the default context will be used)
2790 * Checks if any sources have pending events for the given context.
2792 * Return value: %TRUE if events are pending.
2795 g_main_context_pending (GMainContext *context)
2800 context = g_main_context_default();
2802 LOCK_CONTEXT (context);
2803 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
2804 UNLOCK_CONTEXT (context);
2810 * g_main_context_iteration:
2811 * @context: a #GMainContext (if %NULL, the default context will be used)
2812 * @may_block: whether the call may block.
2814 * Runs a single iteration for the given main loop. This involves
2815 * checking to see if any event sources are ready to be processed,
2816 * then if no events sources are ready and @may_block is %TRUE, waiting
2817 * for a source to become ready, then dispatching the highest priority
2818 * events sources that are ready. Otherwise, if @may_block is %FALSE
2819 * sources are not waited to become ready, only those highest priority
2820 * events sources will be dispatched (if any), that are ready at this
2821 * given moment without further waiting.
2823 * Note that even when @may_block is %TRUE, it is still possible for
2824 * g_main_context_iteration() to return %FALSE, since the the wait may
2825 * be interrupted for other reasons than an event source becoming ready.
2827 * Return value: %TRUE if events were dispatched.
2830 g_main_context_iteration (GMainContext *context, gboolean may_block)
2835 context = g_main_context_default();
2837 LOCK_CONTEXT (context);
2838 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
2839 UNLOCK_CONTEXT (context);
2846 * @context: a #GMainContext (if %NULL, the default context will be used).
2847 * @is_running: set to %TRUE to indicate that the loop is running. This
2848 * is not very important since calling g_main_loop_run() will set this to
2851 * Creates a new #GMainLoop structure.
2853 * Return value: a new #GMainLoop.
2856 g_main_loop_new (GMainContext *context,
2857 gboolean is_running)
2862 context = g_main_context_default();
2864 g_main_context_ref (context);
2866 loop = g_new0 (GMainLoop, 1);
2867 loop->context = context;
2868 loop->is_running = is_running != FALSE;
2869 loop->ref_count = 1;
2876 * @loop: a #GMainLoop
2878 * Increases the reference count on a #GMainLoop object by one.
2880 * Return value: @loop
2883 g_main_loop_ref (GMainLoop *loop)
2885 g_return_val_if_fail (loop != NULL, NULL);
2886 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2888 g_atomic_int_inc (&loop->ref_count);
2894 * g_main_loop_unref:
2895 * @loop: a #GMainLoop
2897 * Decreases the reference count on a #GMainLoop object by one. If
2898 * the result is zero, free the loop and free all associated memory.
2901 g_main_loop_unref (GMainLoop *loop)
2903 g_return_if_fail (loop != NULL);
2904 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2906 if (!g_atomic_int_dec_and_test (&loop->ref_count))
2909 g_main_context_unref (loop->context);
2915 * @loop: a #GMainLoop
2917 * Runs a main loop until g_main_loop_quit() is called on the loop.
2918 * If this is called for the thread of the loop's #GMainContext,
2919 * it will process events from the loop, otherwise it will
2923 g_main_loop_run (GMainLoop *loop)
2925 GThread *self = G_THREAD_SELF;
2927 g_return_if_fail (loop != NULL);
2928 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2930 #ifdef G_THREADS_ENABLED
2931 if (!g_main_context_acquire (loop->context))
2933 gboolean got_ownership = FALSE;
2935 /* Another thread owns this context */
2936 if (!g_thread_supported ())
2938 g_warning ("g_main_loop_run() was called from second thread but "
2939 "g_thread_init() was never called.");
2943 LOCK_CONTEXT (loop->context);
2945 g_atomic_int_inc (&loop->ref_count);
2947 if (!loop->is_running)
2948 loop->is_running = TRUE;
2950 if (!loop->context->cond)
2951 loop->context->cond = g_cond_new ();
2953 while (loop->is_running && !got_ownership)
2954 got_ownership = g_main_context_wait (loop->context,
2955 loop->context->cond,
2956 g_static_mutex_get_mutex (&loop->context->mutex));
2958 if (!loop->is_running)
2960 UNLOCK_CONTEXT (loop->context);
2962 g_main_context_release (loop->context);
2963 g_main_loop_unref (loop);
2967 g_assert (got_ownership);
2970 LOCK_CONTEXT (loop->context);
2971 #endif /* G_THREADS_ENABLED */
2973 if (loop->context->in_check_or_prepare)
2975 g_warning ("g_main_loop_run(): called recursively from within a source's "
2976 "check() or prepare() member, iteration not possible.");
2980 g_atomic_int_inc (&loop->ref_count);
2981 loop->is_running = TRUE;
2982 while (loop->is_running)
2983 g_main_context_iterate (loop->context, TRUE, TRUE, self);
2985 UNLOCK_CONTEXT (loop->context);
2987 #ifdef G_THREADS_ENABLED
2988 g_main_context_release (loop->context);
2989 #endif /* G_THREADS_ENABLED */
2991 g_main_loop_unref (loop);
2996 * @loop: a #GMainLoop
2998 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
2999 * for the loop will return.
3001 * Note that sources that have already been dispatched when
3002 * g_main_loop_quit() is called will still be executed.
3005 g_main_loop_quit (GMainLoop *loop)
3007 g_return_if_fail (loop != NULL);
3008 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3010 LOCK_CONTEXT (loop->context);
3011 loop->is_running = FALSE;
3012 g_main_context_wakeup_unlocked (loop->context);
3014 #ifdef G_THREADS_ENABLED
3015 if (loop->context->cond)
3016 g_cond_broadcast (loop->context->cond);
3017 #endif /* G_THREADS_ENABLED */
3019 UNLOCK_CONTEXT (loop->context);
3023 * g_main_loop_is_running:
3024 * @loop: a #GMainLoop.
3026 * Checks to see if the main loop is currently being run via g_main_loop_run().
3028 * Return value: %TRUE if the mainloop is currently being run.
3031 g_main_loop_is_running (GMainLoop *loop)
3033 g_return_val_if_fail (loop != NULL, FALSE);
3034 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3036 return loop->is_running;
3040 * g_main_loop_get_context:
3041 * @loop: a #GMainLoop.
3043 * Returns the #GMainContext of @loop.
3045 * Return value: the #GMainContext of @loop
3048 g_main_loop_get_context (GMainLoop *loop)
3050 g_return_val_if_fail (loop != NULL, NULL);
3051 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3053 return loop->context;
3056 /* HOLDS: context's lock */
3058 g_main_context_poll (GMainContext *context,
3064 #ifdef G_MAIN_POLL_DEBUG
3070 GPollFunc poll_func;
3072 if (n_fds || timeout != 0)
3074 #ifdef G_MAIN_POLL_DEBUG
3075 if (g_main_poll_debug)
3077 g_print ("polling context=%p n=%d timeout=%d\n",
3078 context, n_fds, timeout);
3079 poll_timer = g_timer_new ();
3083 LOCK_CONTEXT (context);
3085 poll_func = context->poll_func;
3087 UNLOCK_CONTEXT (context);
3088 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3091 g_warning ("poll(2) failed due to: %s.",
3092 g_strerror (errno));
3094 /* If g_poll () returns -1, it has already called g_warning() */
3098 #ifdef G_MAIN_POLL_DEBUG
3099 if (g_main_poll_debug)
3101 LOCK_CONTEXT (context);
3103 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3106 g_timer_elapsed (poll_timer, NULL));
3107 g_timer_destroy (poll_timer);
3108 pollrec = context->poll_records;
3110 while (pollrec != NULL)
3115 if (fds[i].fd == pollrec->fd->fd &&
3116 pollrec->fd->events &&
3119 g_print (" [" GPOLLFD_FORMAT " :", fds[i].fd);
3120 if (fds[i].revents & G_IO_IN)
3122 if (fds[i].revents & G_IO_OUT)
3124 if (fds[i].revents & G_IO_PRI)
3126 if (fds[i].revents & G_IO_ERR)
3128 if (fds[i].revents & G_IO_HUP)
3130 if (fds[i].revents & G_IO_NVAL)
3136 pollrec = pollrec->next;
3140 UNLOCK_CONTEXT (context);
3143 } /* if (n_fds || timeout != 0) */
3147 * g_main_context_add_poll:
3148 * @context: a #GMainContext (or %NULL for the default context)
3149 * @fd: a #GPollFD structure holding information about a file
3150 * descriptor to watch.
3151 * @priority: the priority for this file descriptor which should be
3152 * the same as the priority used for g_source_attach() to ensure that the
3153 * file descriptor is polled whenever the results may be needed.
3155 * Adds a file descriptor to the set of file descriptors polled for
3156 * this context. This will very seldomly be used directly. Instead
3157 * a typical event source will use g_source_add_poll() instead.
3160 g_main_context_add_poll (GMainContext *context,
3165 context = g_main_context_default ();
3167 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3168 g_return_if_fail (fd);
3170 LOCK_CONTEXT (context);
3171 g_main_context_add_poll_unlocked (context, priority, fd);
3172 UNLOCK_CONTEXT (context);
3175 /* HOLDS: main_loop_lock */
3177 g_main_context_add_poll_unlocked (GMainContext *context,
3181 GPollRec *lastrec, *pollrec;
3182 GPollRec *newrec = g_slice_new (GPollRec);
3184 /* This file descriptor may be checked before we ever poll */
3187 newrec->priority = priority;
3190 pollrec = context->poll_records;
3191 while (pollrec && priority >= pollrec->priority)
3194 pollrec = pollrec->next;
3198 lastrec->next = newrec;
3200 context->poll_records = newrec;
3202 newrec->next = pollrec;
3204 context->n_poll_records++;
3206 #ifdef G_THREADS_ENABLED
3207 context->poll_changed = TRUE;
3209 /* Now wake up the main loop if it is waiting in the poll() */
3210 g_main_context_wakeup_unlocked (context);
3215 * g_main_context_remove_poll:
3216 * @context:a #GMainContext
3217 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3219 * Removes file descriptor from the set of file descriptors to be
3220 * polled for a particular context.
3223 g_main_context_remove_poll (GMainContext *context,
3227 context = g_main_context_default ();
3229 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3230 g_return_if_fail (fd);
3232 LOCK_CONTEXT (context);
3233 g_main_context_remove_poll_unlocked (context, fd);
3234 UNLOCK_CONTEXT (context);
3238 g_main_context_remove_poll_unlocked (GMainContext *context,
3241 GPollRec *pollrec, *lastrec;
3244 pollrec = context->poll_records;
3248 if (pollrec->fd == fd)
3250 if (lastrec != NULL)
3251 lastrec->next = pollrec->next;
3253 context->poll_records = pollrec->next;
3255 g_slice_free (GPollRec, pollrec);
3257 context->n_poll_records--;
3261 pollrec = pollrec->next;
3264 #ifdef G_THREADS_ENABLED
3265 context->poll_changed = TRUE;
3267 /* Now wake up the main loop if it is waiting in the poll() */
3268 g_main_context_wakeup_unlocked (context);
3273 * g_source_get_current_time:
3274 * @source: a #GSource
3275 * @timeval: #GTimeVal structure in which to store current time.
3277 * Gets the "current time" to be used when checking
3278 * this source. The advantage of calling this function over
3279 * calling g_get_current_time() directly is that when
3280 * checking multiple sources, GLib can cache a single value
3281 * instead of having to repeatedly get the system time.
3284 g_source_get_current_time (GSource *source,
3287 GMainContext *context;
3289 g_return_if_fail (source->context != NULL);
3291 context = source->context;
3293 LOCK_CONTEXT (context);
3295 if (!context->time_is_current)
3297 g_get_current_time (&context->current_time);
3298 context->time_is_current = TRUE;
3301 *timeval = context->current_time;
3303 UNLOCK_CONTEXT (context);
3307 * g_main_context_set_poll_func:
3308 * @context: a #GMainContext
3309 * @func: the function to call to poll all file descriptors
3311 * Sets the function to use to handle polling of file descriptors. It
3312 * will be used instead of the poll() system call
3313 * (or GLib's replacement function, which is used where
3314 * poll() isn't available).
3316 * This function could possibly be used to integrate the GLib event
3317 * loop with an external event loop.
3320 g_main_context_set_poll_func (GMainContext *context,
3324 context = g_main_context_default ();
3326 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3328 LOCK_CONTEXT (context);
3331 context->poll_func = func;
3335 context->poll_func = (GPollFunc) poll;
3337 context->poll_func = (GPollFunc) g_poll;
3341 UNLOCK_CONTEXT (context);
3345 * g_main_context_get_poll_func:
3346 * @context: a #GMainContext
3348 * Gets the poll function set by g_main_context_set_poll_func().
3350 * Return value: the poll function
3353 g_main_context_get_poll_func (GMainContext *context)
3358 context = g_main_context_default ();
3360 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3362 LOCK_CONTEXT (context);
3363 result = context->poll_func;
3364 UNLOCK_CONTEXT (context);
3369 /* HOLDS: context's lock */
3370 /* Wake the main loop up from a poll() */
3372 g_main_context_wakeup_unlocked (GMainContext *context)
3374 #ifdef G_THREADS_ENABLED
3375 if (g_thread_supported() && context->poll_waiting)
3377 context->poll_waiting = FALSE;
3379 write (context->wake_up_pipe[1], "A", 1);
3381 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
3388 * g_main_context_wakeup:
3389 * @context: a #GMainContext
3391 * If @context is currently waiting in a poll(), interrupt
3392 * the poll(), and continue the iteration process.
3395 g_main_context_wakeup (GMainContext *context)
3398 context = g_main_context_default ();
3400 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3402 LOCK_CONTEXT (context);
3403 g_main_context_wakeup_unlocked (context);
3404 UNLOCK_CONTEXT (context);
3408 * g_main_context_is_owner:
3409 * @context: a #GMainContext
3411 * Determines whether this thread holds the (recursive)
3412 * ownership of this #GMaincontext. This is useful to
3413 * know before waiting on another thread that may be
3414 * blocking to get ownership of @context.
3416 * Returns: %TRUE if current thread is owner of @context.
3421 g_main_context_is_owner (GMainContext *context)
3426 context = g_main_context_default ();
3428 #ifdef G_THREADS_ENABLED
3429 LOCK_CONTEXT (context);
3430 is_owner = context->owner == G_THREAD_SELF;
3431 UNLOCK_CONTEXT (context);
3442 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3443 GTimeVal *current_time)
3445 guint seconds = timeout_source->interval / 1000;
3446 guint msecs = timeout_source->interval - seconds * 1000;
3448 timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
3449 timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
3450 if (timeout_source->expiration.tv_usec >= 1000000)
3452 timeout_source->expiration.tv_usec -= 1000000;
3453 timeout_source->expiration.tv_sec++;
3455 if (timer_perturb==-1)
3458 * we want a per machine/session unique 'random' value; try the dbus
3459 * address first, that has a UUID in it. If there is no dbus, use the
3460 * hostname for hashing.
3462 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3463 if (!session_bus_address)
3464 session_bus_address = g_getenv ("HOSTNAME");
3465 if (session_bus_address)
3466 timer_perturb = ABS ((gint) g_str_hash (session_bus_address));
3470 if (timeout_source->granularity)
3473 gint gran; /* in usecs */
3476 gran = timeout_source->granularity * 1000;
3477 perturb = timer_perturb % gran;
3479 * We want to give each machine a per machine pertubation;
3480 * shift time back first, and forward later after the rounding
3483 timeout_source->expiration.tv_usec -= perturb;
3484 if (timeout_source->expiration.tv_usec < 0)
3486 timeout_source->expiration.tv_usec += 1000000;
3487 timeout_source->expiration.tv_sec--;
3490 remainder = timeout_source->expiration.tv_usec % gran;
3491 if (remainder >= gran/4) /* round up */
3492 timeout_source->expiration.tv_usec += gran;
3493 timeout_source->expiration.tv_usec -= remainder;
3495 timeout_source->expiration.tv_usec += perturb;
3497 /* the rounding may have overflown tv_usec */
3498 while (timeout_source->expiration.tv_usec > 1000000)
3500 timeout_source->expiration.tv_usec -= 1000000;
3501 timeout_source->expiration.tv_sec++;
3507 g_timeout_prepare (GSource *source,
3512 GTimeVal current_time;
3514 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3516 g_source_get_current_time (source, ¤t_time);
3518 sec = timeout_source->expiration.tv_sec - current_time.tv_sec;
3519 msec = (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000;
3521 /* We do the following in a rather convoluted fashion to deal with
3522 * the fact that we don't have an integral type big enough to hold
3523 * the difference of two timevals in millseconds.
3525 if (sec < 0 || (sec == 0 && msec < 0))
3529 glong interval_sec = timeout_source->interval / 1000;
3530 glong interval_msec = timeout_source->interval % 1000;
3538 if (sec > interval_sec ||
3539 (sec == interval_sec && msec > interval_msec))
3541 /* The system time has been set backwards, so we
3542 * reset the expiration time to now + timeout_source->interval;
3543 * this at least avoids hanging for long periods of time.
3545 g_timeout_set_expiration (timeout_source, ¤t_time);
3546 msec = MIN (G_MAXINT, timeout_source->interval);
3550 msec = MIN (G_MAXINT, (guint)msec + 1000 * (guint)sec);
3554 *timeout = (gint)msec;
3560 g_timeout_check (GSource *source)
3562 GTimeVal current_time;
3563 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3565 g_source_get_current_time (source, ¤t_time);
3567 return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
3568 ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
3569 (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
3573 g_timeout_dispatch (GSource *source,
3574 GSourceFunc callback,
3577 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3581 g_warning ("Timeout source dispatched without callback\n"
3582 "You must call g_source_set_callback().");
3586 if (callback (user_data))
3588 GTimeVal current_time;
3590 g_source_get_current_time (source, ¤t_time);
3591 g_timeout_set_expiration (timeout_source, ¤t_time);
3600 * g_timeout_source_new:
3601 * @interval: the timeout interval in milliseconds.
3603 * Creates a new timeout source.
3605 * The source will not initially be associated with any #GMainContext
3606 * and must be added to one with g_source_attach() before it will be
3609 * Return value: the newly-created timeout source
3612 g_timeout_source_new (guint interval)
3614 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3615 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3616 GTimeVal current_time;
3618 timeout_source->interval = interval;
3620 g_get_current_time (¤t_time);
3621 g_timeout_set_expiration (timeout_source, ¤t_time);
3627 * g_timeout_source_new_seconds:
3628 * @interval: the timeout interval in seconds
3630 * Creates a new timeout source.
3632 * The source will not initially be associated with any #GMainContext
3633 * and must be added to one with g_source_attach() before it will be
3636 * The scheduling granularity/accuracy of this timeout source will be
3639 * Return value: the newly-created timeout source
3644 g_timeout_source_new_seconds (guint interval)
3646 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3647 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3648 GTimeVal current_time;
3650 timeout_source->interval = 1000*interval;
3651 timeout_source->granularity = 1000;
3653 g_get_current_time (¤t_time);
3654 g_timeout_set_expiration (timeout_source, ¤t_time);
3661 * g_timeout_add_full:
3662 * @priority: the priority of the timeout source. Typically this will be in
3663 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3664 * @interval: the time between calls to the function, in milliseconds
3665 * (1/1000ths of a second)
3666 * @function: function to call
3667 * @data: data to pass to @function
3668 * @notify: function to call when the timeout is removed, or %NULL
3670 * Sets a function to be called at regular intervals, with the given
3671 * priority. The function is called repeatedly until it returns
3672 * %FALSE, at which point the timeout is automatically destroyed and
3673 * the function will not be called again. The @notify function is
3674 * called when the timeout is destroyed. The first call to the
3675 * function will be at the end of the first @interval.
3677 * Note that timeout functions may be delayed, due to the processing of other
3678 * event sources. Thus they should not be relied on for precise timing.
3679 * After each call to the timeout function, the time of the next
3680 * timeout is recalculated based on the current time and the given interval
3681 * (it does not try to 'catch up' time lost in delays).
3683 * Return value: the ID (greater than 0) of the event source.
3686 g_timeout_add_full (gint priority,
3688 GSourceFunc function,
3690 GDestroyNotify notify)
3695 g_return_val_if_fail (function != NULL, 0);
3697 source = g_timeout_source_new (interval);
3699 if (priority != G_PRIORITY_DEFAULT)
3700 g_source_set_priority (source, priority);
3702 g_source_set_callback (source, function, data, notify);
3703 id = g_source_attach (source, NULL);
3704 g_source_unref (source);
3711 * @interval: the time between calls to the function, in milliseconds
3712 * (1/1000ths of a second)
3713 * @function: function to call
3714 * @data: data to pass to @function
3716 * Sets a function to be called at regular intervals, with the default
3717 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
3718 * until it returns %FALSE, at which point the timeout is automatically
3719 * destroyed and the function will not be called again. The first call
3720 * to the function will be at the end of the first @interval.
3722 * Note that timeout functions may be delayed, due to the processing of other
3723 * event sources. Thus they should not be relied on for precise timing.
3724 * After each call to the timeout function, the time of the next
3725 * timeout is recalculated based on the current time and the given interval
3726 * (it does not try to 'catch up' time lost in delays).
3728 * If you want to have a timer in the "seconds" range and do not care
3729 * about the exact time of the first call of the timer, use the
3730 * g_timeout_add_seconds() function; this function allows for more
3731 * optimizations and more efficient system power usage.
3733 * Return value: the ID (greater than 0) of the event source.
3736 g_timeout_add (guint32 interval,
3737 GSourceFunc function,
3740 return g_timeout_add_full (G_PRIORITY_DEFAULT,
3741 interval, function, data, NULL);
3745 * g_timeout_add_seconds_full:
3746 * @priority: the priority of the timeout source. Typically this will be in
3747 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3748 * @interval: the time between calls to the function, in seconds
3749 * @function: function to call
3750 * @data: data to pass to @function
3751 * @notify: function to call when the timeout is removed, or %NULL
3753 * Sets a function to be called at regular intervals, with @priority.
3754 * The function is called repeatedly until it returns %FALSE, at which
3755 * point the timeout is automatically destroyed and the function will
3756 * not be called again.
3758 * Unlike g_timeout_add(), this function operates at whole second granularity.
3759 * The initial starting point of the timer is determined by the implementation
3760 * and the implementation is expected to group multiple timers together so that
3761 * they fire all at the same time.
3762 * To allow this grouping, the @interval to the first timer is rounded
3763 * and can deviate up to one second from the specified interval.
3764 * Subsequent timer iterations will generally run at the specified interval.
3766 * Note that timeout functions may be delayed, due to the processing of other
3767 * event sources. Thus they should not be relied on for precise timing.
3768 * After each call to the timeout function, the time of the next
3769 * timeout is recalculated based on the current time and the given @interval
3771 * If you want timing more precise than whole seconds, use g_timeout_add()
3774 * The grouping of timers to fire at the same time results in a more power
3775 * and CPU efficient behavior so if your timer is in multiples of seconds
3776 * and you don't require the first timer exactly one second from now, the
3777 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
3779 * Return value: the ID (greater than 0) of the event source.
3784 g_timeout_add_seconds_full (gint priority,
3786 GSourceFunc function,
3788 GDestroyNotify notify)
3793 g_return_val_if_fail (function != NULL, 0);
3795 source = g_timeout_source_new_seconds (interval);
3797 if (priority != G_PRIORITY_DEFAULT)
3798 g_source_set_priority (source, priority);
3800 g_source_set_callback (source, function, data, notify);
3801 id = g_source_attach (source, NULL);
3802 g_source_unref (source);
3808 * g_timeout_add_seconds:
3809 * @interval: the time between calls to the function, in seconds
3810 * @function: function to call
3811 * @data: data to pass to @function
3813 * Sets a function to be called at regular intervals with the default
3814 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
3815 * it returns %FALSE, at which point the timeout is automatically destroyed
3816 * and the function will not be called again.
3818 * See g_timeout_add_seconds_full() for the differences between
3819 * g_timeout_add() and g_timeout_add_seconds().
3821 * Return value: the ID (greater than 0) of the event source.
3826 g_timeout_add_seconds (guint interval,
3827 GSourceFunc function,
3830 g_return_val_if_fail (function != NULL, 0);
3832 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
3835 /* Child watch functions */
3840 g_child_watch_prepare (GSource *source,
3849 g_child_watch_check (GSource *source)
3851 GChildWatchSource *child_watch_source;
3852 gboolean child_exited;
3854 child_watch_source = (GChildWatchSource *) source;
3856 child_exited = child_watch_source->poll.revents & G_IO_IN;
3863 * Note: We do _not_ check for the special value of STILL_ACTIVE
3864 * since we know that the process has exited and doing so runs into
3865 * problems if the child process "happens to return STILL_ACTIVE(259)"
3866 * as Microsoft's Platform SDK puts it.
3868 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
3870 gchar *emsg = g_win32_error_message (GetLastError ());
3871 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
3874 child_watch_source->child_status = -1;
3877 child_watch_source->child_status = child_status;
3880 return child_exited;
3883 #else /* G_OS_WIN32 */
3886 check_for_child_exited (GSource *source)
3888 GChildWatchSource *child_watch_source;
3891 /* protect against another SIGCHLD in the middle of this call */
3892 count = child_watch_count;
3894 child_watch_source = (GChildWatchSource *) source;
3896 if (child_watch_source->child_exited)
3899 if (child_watch_source->count < count)
3903 if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
3905 child_watch_source->child_status = child_status;
3906 child_watch_source->child_exited = TRUE;
3908 child_watch_source->count = count;
3911 return child_watch_source->child_exited;
3915 g_child_watch_prepare (GSource *source,
3920 return check_for_child_exited (source);
3925 g_child_watch_check (GSource *source)
3927 return check_for_child_exited (source);
3930 #endif /* G_OS_WIN32 */
3933 g_child_watch_dispatch (GSource *source,
3934 GSourceFunc callback,
3937 GChildWatchSource *child_watch_source;
3938 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
3940 child_watch_source = (GChildWatchSource *) source;
3944 g_warning ("Child watch source dispatched without callback\n"
3945 "You must call g_source_set_callback().");
3949 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
3951 /* We never keep a child watch source around as the child is gone */
3958 g_child_watch_signal_handler (int signum)
3960 child_watch_count ++;
3962 if (child_watch_init_state == CHILD_WATCH_INITIALIZED_THREADED)
3964 write (child_watch_wake_up_pipe[1], "B", 1);
3968 /* We count on the signal interrupting the poll in the same thread.
3974 g_child_watch_source_init_single (void)
3976 struct sigaction action;
3978 g_assert (! g_thread_supported());
3979 g_assert (child_watch_init_state == CHILD_WATCH_UNINITIALIZED);
3981 child_watch_init_state = CHILD_WATCH_INITIALIZED_SINGLE;
3983 action.sa_handler = g_child_watch_signal_handler;
3984 sigemptyset (&action.sa_mask);
3985 action.sa_flags = SA_NOCLDSTOP;
3986 sigaction (SIGCHLD, &action, NULL);
3990 child_watch_helper_thread (gpointer data)
3997 read (child_watch_wake_up_pipe[0], b, 20);
3999 /* We were woken up. Wake up all other contexts in all other threads */
4000 G_LOCK (main_context_list);
4001 for (list = main_context_list; list; list = list->next)
4003 GMainContext *context;
4005 context = list->data;
4006 if (g_atomic_int_get (&context->ref_count) > 0)
4007 /* Due to racing conditions we can find ref_count == 0, in
4008 * that case, however, the context is still not destroyed
4009 * and no poll can be active, otherwise the ref_count
4011 g_main_context_wakeup (context);
4013 G_UNLOCK (main_context_list);
4020 g_child_watch_source_init_multi_threaded (void)
4022 GError *error = NULL;
4023 struct sigaction action;
4025 g_assert (g_thread_supported());
4027 if (pipe (child_watch_wake_up_pipe) < 0)
4028 g_error ("Cannot create wake up pipe: %s\n", g_strerror (errno));
4029 fcntl (child_watch_wake_up_pipe[1], F_SETFL, O_NONBLOCK | fcntl (child_watch_wake_up_pipe[1], F_GETFL));
4031 /* We create a helper thread that polls on the wakeup pipe indefinitely */
4032 /* FIXME: Think this through for races */
4033 if (g_thread_create (child_watch_helper_thread, NULL, FALSE, &error) == NULL)
4034 g_error ("Cannot create a thread to monitor child exit status: %s\n", error->message);
4035 child_watch_init_state = CHILD_WATCH_INITIALIZED_THREADED;
4037 action.sa_handler = g_child_watch_signal_handler;
4038 sigemptyset (&action.sa_mask);
4039 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4040 sigaction (SIGCHLD, &action, NULL);
4044 g_child_watch_source_init_promote_single_to_threaded (void)
4046 g_child_watch_source_init_multi_threaded ();
4050 g_child_watch_source_init (void)
4052 if (g_thread_supported())
4054 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
4055 g_child_watch_source_init_multi_threaded ();
4056 else if (child_watch_init_state == CHILD_WATCH_INITIALIZED_SINGLE)
4057 g_child_watch_source_init_promote_single_to_threaded ();
4061 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
4062 g_child_watch_source_init_single ();
4066 #endif /* !G_OS_WIN32 */
4069 * g_child_watch_source_new:
4070 * @pid: process to watch. On POSIX the pid of a child process. On
4071 * Windows a handle for a process (which doesn't have to be a child).
4073 * Creates a new child_watch source.
4075 * The source will not initially be associated with any #GMainContext
4076 * and must be added to one with g_source_attach() before it will be
4079 * Note that child watch sources can only be used in conjunction with
4080 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4083 * Note that on platforms where #GPid must be explicitly closed
4084 * (see g_spawn_close_pid()) @pid must not be closed while the
4085 * source is still active. Typically, you will want to call
4086 * g_spawn_close_pid() in the callback function for the source.
4088 * Note further that using g_child_watch_source_new() is not
4089 * compatible with calling <literal>waitpid(-1)</literal> in
4090 * the application. Calling waitpid() for individual pids will
4093 * Return value: the newly-created child watch source
4098 g_child_watch_source_new (GPid pid)
4100 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4101 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4104 child_watch_source->poll.fd = (gintptr) pid;
4105 child_watch_source->poll.events = G_IO_IN;
4107 g_source_add_poll (source, &child_watch_source->poll);
4108 #else /* G_OS_WIN32 */
4109 g_child_watch_source_init ();
4110 #endif /* G_OS_WIN32 */
4112 child_watch_source->pid = pid;
4118 * g_child_watch_add_full:
4119 * @priority: the priority of the idle source. Typically this will be in the
4120 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4121 * @pid: process to watch. On POSIX the pid of a child process. On
4122 * Windows a handle for a process (which doesn't have to be a child).
4123 * @function: function to call
4124 * @data: data to pass to @function
4125 * @notify: function to call when the idle is removed, or %NULL
4127 * Sets a function to be called when the child indicated by @pid
4128 * exits, at the priority @priority.
4130 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4131 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4132 * the spawn function for the child watching to work.
4134 * Note that on platforms where #GPid must be explicitly closed
4135 * (see g_spawn_close_pid()) @pid must not be closed while the
4136 * source is still active. Typically, you will want to call
4137 * g_spawn_close_pid() in the callback function for the source.
4139 * GLib supports only a single callback per process id.
4141 * Return value: the ID (greater than 0) of the event source.
4146 g_child_watch_add_full (gint priority,
4148 GChildWatchFunc function,
4150 GDestroyNotify notify)
4155 g_return_val_if_fail (function != NULL, 0);
4157 source = g_child_watch_source_new (pid);
4159 if (priority != G_PRIORITY_DEFAULT)
4160 g_source_set_priority (source, priority);
4162 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4163 id = g_source_attach (source, NULL);
4164 g_source_unref (source);
4170 * g_child_watch_add:
4171 * @pid: process id to watch. On POSIX the pid of a child process. On
4172 * Windows a handle for a process (which doesn't have to be a child).
4173 * @function: function to call
4174 * @data: data to pass to @function
4176 * Sets a function to be called when the child indicated by @pid
4177 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4179 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4180 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4181 * the spawn function for the child watching to work.
4183 * Note that on platforms where #GPid must be explicitly closed
4184 * (see g_spawn_close_pid()) @pid must not be closed while the
4185 * source is still active. Typically, you will want to call
4186 * g_spawn_close_pid() in the callback function for the source.
4188 * GLib supports only a single callback per process id.
4190 * Return value: the ID (greater than 0) of the event source.
4195 g_child_watch_add (GPid pid,
4196 GChildWatchFunc function,
4199 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4203 /* Idle functions */
4206 g_idle_prepare (GSource *source,
4215 g_idle_check (GSource *source)
4221 g_idle_dispatch (GSource *source,
4222 GSourceFunc callback,
4227 g_warning ("Idle source dispatched without callback\n"
4228 "You must call g_source_set_callback().");
4232 return callback (user_data);
4236 * g_idle_source_new:
4238 * Creates a new idle source.
4240 * The source will not initially be associated with any #GMainContext
4241 * and must be added to one with g_source_attach() before it will be
4242 * executed. Note that the default priority for idle sources is
4243 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4244 * have a default priority of %G_PRIORITY_DEFAULT.
4246 * Return value: the newly-created idle source
4249 g_idle_source_new (void)
4253 source = g_source_new (&g_idle_funcs, sizeof (GSource));
4254 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4261 * @priority: the priority of the idle source. Typically this will be in the
4262 * range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4263 * @function: function to call
4264 * @data: data to pass to @function
4265 * @notify: function to call when the idle is removed, or %NULL
4267 * Adds a function to be called whenever there are no higher priority
4268 * events pending. If the function returns %FALSE it is automatically
4269 * removed from the list of event sources and will not be called again.
4271 * Return value: the ID (greater than 0) of the event source.
4274 g_idle_add_full (gint priority,
4275 GSourceFunc function,
4277 GDestroyNotify notify)
4282 g_return_val_if_fail (function != NULL, 0);
4284 source = g_idle_source_new ();
4286 if (priority != G_PRIORITY_DEFAULT_IDLE)
4287 g_source_set_priority (source, priority);
4289 g_source_set_callback (source, function, data, notify);
4290 id = g_source_attach (source, NULL);
4291 g_source_unref (source);
4298 * @function: function to call
4299 * @data: data to pass to @function.
4301 * Adds a function to be called whenever there are no higher priority
4302 * events pending to the default main loop. The function is given the
4303 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4304 * returns %FALSE it is automatically removed from the list of event
4305 * sources and will not be called again.
4307 * Return value: the ID (greater than 0) of the event source.
4310 g_idle_add (GSourceFunc function,
4313 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4317 * g_idle_remove_by_data:
4318 * @data: the data for the idle source's callback.
4320 * Removes the idle function with the given data.
4322 * Return value: %TRUE if an idle source was found and removed.
4325 g_idle_remove_by_data (gpointer data)
4327 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4330 #define __G_MAIN_C__
4331 #include "galiasdef.c"