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 */
451 if (ready < nhandles - 1)
452 for (i = ready - WAIT_OBJECT_0 + 1; i < nhandles; i++)
453 handles[i-1] = handles[i];
455 recursed_result = poll_rest (FALSE, handles, nhandles, fds, nfds, 0);
456 return (recursed_result == -1) ? -1 : 1 + recursed_result;
466 g_poll (GPollFD *fds,
470 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
471 gboolean poll_msgs = FALSE;
476 if (g_main_poll_debug)
477 g_print ("g_poll: waiting for");
479 for (f = fds; f < &fds[nfds]; ++f)
480 if (f->fd == G_WIN32_MSG_HANDLE && (f->events & G_IO_IN))
482 if (g_main_poll_debug && !poll_msgs)
488 /* Don't add the same handle several times into the array, as
489 * docs say that is not allowed, even if it actually does seem
494 for (i = 0; i < nhandles; i++)
495 if (handles[i] == (HANDLE) f->fd)
500 if (nhandles == MAXIMUM_WAIT_OBJECTS)
502 g_warning ("Too many handles to wait for!\n");
507 if (g_main_poll_debug)
508 g_print (" %p", (HANDLE) f->fd);
509 handles[nhandles++] = (HANDLE) f->fd;
514 if (g_main_poll_debug)
517 for (f = fds; f < &fds[nfds]; ++f)
523 /* Polling for several things? */
524 if (nhandles > 1 || (nhandles > 0 && poll_msgs))
526 /* First check if one or several of them are immediately
529 retval = poll_rest (poll_msgs, handles, nhandles, fds, nfds, 0);
531 /* If not, and we have a significant timeout, poll again with
532 * timeout then. Note that this will return indication for only
533 * one event, or only for messages. We ignore timeouts less than
534 * ten milliseconds as they are mostly pointless on Windows, the
535 * MsgWaitForMultipleObjectsEx() call will timeout right away
538 if (retval == 0 && (timeout == INFINITE || timeout >= 10))
539 retval = poll_rest (poll_msgs, handles, nhandles, fds, nfds, timeout);
543 /* Just polling for one thing, so no need to check first if
544 * available immediately
546 retval = poll_rest (poll_msgs, handles, nhandles, fds, nfds, timeout);
550 for (f = fds; f < &fds[nfds]; ++f)
556 #else /* !G_OS_WIN32 */
558 /* The following implementation of poll() comes from the GNU C Library.
559 * Copyright (C) 1994, 1996, 1997 Free Software Foundation, Inc.
562 #include <string.h> /* for bzero on BSD systems */
564 #ifdef HAVE_SYS_SELECT_H
565 #include <sys/select.h>
566 #endif /* HAVE_SYS_SELECT_H */
570 #endif /* G_OS_BEOS */
573 # define SELECT_MASK fd_set
574 #else /* !NO_FD_SET */
576 typedef long fd_mask;
579 # define SELECT_MASK void
581 # define SELECT_MASK int
582 # endif /* !_IBMR2 */
583 #endif /* !NO_FD_SET */
586 g_poll (GPollFD *fds,
591 SELECT_MASK rset, wset, xset;
600 for (f = fds; f < &fds[nfds]; ++f)
603 if (f->events & G_IO_IN)
604 FD_SET (f->fd, &rset);
605 if (f->events & G_IO_OUT)
606 FD_SET (f->fd, &wset);
607 if (f->events & G_IO_PRI)
608 FD_SET (f->fd, &xset);
609 if (f->fd > maxfd && (f->events & (G_IO_IN|G_IO_OUT|G_IO_PRI)))
613 tv.tv_sec = timeout / 1000;
614 tv.tv_usec = (timeout % 1000) * 1000;
616 ready = select (maxfd + 1, &rset, &wset, &xset,
617 timeout == -1 ? NULL : &tv);
619 for (f = fds; f < &fds[nfds]; ++f)
624 if (FD_ISSET (f->fd, &rset))
625 f->revents |= G_IO_IN;
626 if (FD_ISSET (f->fd, &wset))
627 f->revents |= G_IO_OUT;
628 if (FD_ISSET (f->fd, &xset))
629 f->revents |= G_IO_PRI;
636 #endif /* !G_OS_WIN32 */
638 #endif /* !HAVE_POLL */
641 * g_main_context_ref:
642 * @context: a #GMainContext
644 * Increases the reference count on a #GMainContext object by one.
646 * Returns: the @context that was passed in (since 2.6)
649 g_main_context_ref (GMainContext *context)
651 g_return_val_if_fail (context != NULL, NULL);
652 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
654 g_atomic_int_inc (&context->ref_count);
660 poll_rec_list_free (GMainContext *context,
663 g_slice_free_chain (GPollRec, list, next);
667 * g_main_context_unref:
668 * @context: a #GMainContext
670 * Decreases the reference count on a #GMainContext object by one. If
671 * the result is zero, free the context and free all associated memory.
674 g_main_context_unref (GMainContext *context)
677 g_return_if_fail (context != NULL);
678 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
680 if (!g_atomic_int_dec_and_test (&context->ref_count))
683 G_LOCK (main_context_list);
684 main_context_list = g_slist_remove (main_context_list, context);
685 G_UNLOCK (main_context_list);
687 source = context->source_list;
690 GSource *next = source->next;
691 g_source_destroy_internal (source, context, FALSE);
695 #ifdef G_THREADS_ENABLED
696 g_static_mutex_free (&context->mutex);
699 g_ptr_array_free (context->pending_dispatches, TRUE);
700 g_free (context->cached_poll_array);
702 poll_rec_list_free (context, context->poll_records);
704 #ifdef G_THREADS_ENABLED
705 if (g_thread_supported())
708 close (context->wake_up_pipe[0]);
709 close (context->wake_up_pipe[1]);
711 CloseHandle (context->wake_up_semaphore);
715 main_contexts_without_pipe = g_slist_remove (main_contexts_without_pipe,
718 if (context->cond != NULL)
719 g_cond_free (context->cond);
725 #ifdef G_THREADS_ENABLED
727 g_main_context_init_pipe (GMainContext *context)
730 if (context->wake_up_pipe[0] != -1)
732 if (pipe (context->wake_up_pipe) < 0)
733 g_error ("Cannot create pipe main loop wake-up: %s\n",
736 fcntl (context->wake_up_pipe[0], F_SETFD, FD_CLOEXEC);
737 fcntl (context->wake_up_pipe[1], F_SETFD, FD_CLOEXEC);
739 context->wake_up_rec.fd = context->wake_up_pipe[0];
740 context->wake_up_rec.events = G_IO_IN;
742 if (context->wake_up_semaphore != NULL)
744 context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
745 if (context->wake_up_semaphore == NULL)
746 g_error ("Cannot create wake-up semaphore: %s",
747 g_win32_error_message (GetLastError ()));
748 context->wake_up_rec.fd = (gintptr) context->wake_up_semaphore;
749 context->wake_up_rec.events = G_IO_IN;
751 if (g_main_poll_debug)
752 g_print ("wake-up semaphore: %p\n", context->wake_up_semaphore);
754 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
758 _g_main_thread_init (void)
760 GSList *curr = main_contexts_without_pipe;
763 g_main_context_init_pipe ((GMainContext *)curr->data);
766 g_slist_free (main_contexts_without_pipe);
767 main_contexts_without_pipe = NULL;
769 #endif /* G_THREADS_ENABLED */
772 * g_main_context_new:
774 * Creates a new #GMainContext structure.
776 * Return value: the new #GMainContext
779 g_main_context_new (void)
781 GMainContext *context = g_new0 (GMainContext, 1);
783 #ifdef G_MAIN_POLL_DEBUG
785 static gboolean beenhere = FALSE;
789 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
790 g_main_poll_debug = TRUE;
796 #ifdef G_THREADS_ENABLED
797 g_static_mutex_init (&context->mutex);
799 context->owner = NULL;
800 context->waiters = NULL;
803 context->wake_up_pipe[0] = -1;
804 context->wake_up_pipe[1] = -1;
806 context->wake_up_semaphore = NULL;
810 context->ref_count = 1;
812 context->next_id = 1;
814 context->source_list = NULL;
817 context->poll_func = (GPollFunc)poll;
819 context->poll_func = g_poll;
822 context->cached_poll_array = NULL;
823 context->cached_poll_array_size = 0;
825 context->pending_dispatches = g_ptr_array_new ();
827 context->time_is_current = FALSE;
829 #ifdef G_THREADS_ENABLED
830 if (g_thread_supported ())
831 g_main_context_init_pipe (context);
833 main_contexts_without_pipe = g_slist_prepend (main_contexts_without_pipe,
837 G_LOCK (main_context_list);
838 main_context_list = g_slist_append (main_context_list, context);
840 #ifdef G_MAIN_POLL_DEBUG
841 if (g_main_poll_debug)
842 g_print ("created context=%p\n", context);
845 G_UNLOCK (main_context_list);
851 * g_main_context_default:
853 * Returns the default main context. This is the main context used
854 * for main loop functions when a main loop is not explicitly
857 * Return value: the default main context.
860 g_main_context_default (void)
866 if (!default_main_context)
868 default_main_context = g_main_context_new ();
869 #ifdef G_MAIN_POLL_DEBUG
870 if (g_main_poll_debug)
871 g_print ("default context=%p\n", default_main_context);
875 G_UNLOCK (main_loop);
877 return default_main_context;
880 /* Hooks for adding to the main loop */
884 * @source_funcs: structure containing functions that implement
885 * the sources behavior.
886 * @struct_size: size of the #GSource structure to create.
888 * Creates a new #GSource structure. The size is specified to
889 * allow creating structures derived from #GSource that contain
890 * additional data. The size passed in must be at least
891 * <literal>sizeof (GSource)</literal>.
893 * The source will not initially be associated with any #GMainContext
894 * and must be added to one with g_source_attach() before it will be
897 * Return value: the newly-created #GSource.
900 g_source_new (GSourceFuncs *source_funcs,
905 g_return_val_if_fail (source_funcs != NULL, NULL);
906 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
908 source = (GSource*) g_malloc0 (struct_size);
910 source->source_funcs = source_funcs;
911 source->ref_count = 1;
913 source->priority = G_PRIORITY_DEFAULT;
915 source->flags = G_HOOK_FLAG_ACTIVE;
917 /* NULL/0 initialization for all other fields */
922 /* Holds context's lock
925 g_source_list_add (GSource *source,
926 GMainContext *context)
928 GSource *tmp_source, *last_source;
931 tmp_source = context->source_list;
932 while (tmp_source && tmp_source->priority <= source->priority)
934 last_source = tmp_source;
935 tmp_source = tmp_source->next;
938 source->next = tmp_source;
940 tmp_source->prev = source;
942 source->prev = last_source;
944 last_source->next = source;
946 context->source_list = source;
949 /* Holds context's lock
952 g_source_list_remove (GSource *source,
953 GMainContext *context)
956 source->prev->next = source->next;
958 context->source_list = source->next;
961 source->next->prev = source->prev;
969 * @source: a #GSource
970 * @context: a #GMainContext (if %NULL, the default context will be used)
972 * Adds a #GSource to a @context so that it will be executed within
975 * Return value: the ID (greater than 0) for the source within the
979 g_source_attach (GSource *source,
980 GMainContext *context)
985 g_return_val_if_fail (source->context == NULL, 0);
986 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
989 context = g_main_context_default ();
991 LOCK_CONTEXT (context);
993 source->context = context;
994 result = source->source_id = context->next_id++;
997 g_source_list_add (source, context);
999 tmp_list = source->poll_fds;
1002 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
1003 tmp_list = tmp_list->next;
1006 #ifdef G_THREADS_ENABLED
1007 /* Now wake up the main loop if it is waiting in the poll() */
1008 g_main_context_wakeup_unlocked (context);
1011 UNLOCK_CONTEXT (context);
1017 g_source_destroy_internal (GSource *source,
1018 GMainContext *context,
1022 LOCK_CONTEXT (context);
1024 if (!SOURCE_DESTROYED (source))
1027 gpointer old_cb_data;
1028 GSourceCallbackFuncs *old_cb_funcs;
1030 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1032 old_cb_data = source->callback_data;
1033 old_cb_funcs = source->callback_funcs;
1035 source->callback_data = NULL;
1036 source->callback_funcs = NULL;
1040 UNLOCK_CONTEXT (context);
1041 old_cb_funcs->unref (old_cb_data);
1042 LOCK_CONTEXT (context);
1045 if (!SOURCE_BLOCKED (source))
1047 tmp_list = source->poll_fds;
1050 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1051 tmp_list = tmp_list->next;
1055 g_source_unref_internal (source, context, TRUE);
1059 UNLOCK_CONTEXT (context);
1064 * @source: a #GSource
1066 * Removes a source from its #GMainContext, if any, and mark it as
1067 * destroyed. The source cannot be subsequently added to another
1071 g_source_destroy (GSource *source)
1073 GMainContext *context;
1075 g_return_if_fail (source != NULL);
1077 context = source->context;
1080 g_source_destroy_internal (source, context, FALSE);
1082 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1087 * @source: a #GSource
1089 * Returns the numeric ID for a particular source. The ID of a source
1090 * is a positive integer which is unique within a particular main loop
1091 * context. The reverse
1092 * mapping from ID to source is done by g_main_context_find_source_by_id().
1094 * Return value: the ID (greater than 0) for the source
1097 g_source_get_id (GSource *source)
1101 g_return_val_if_fail (source != NULL, 0);
1102 g_return_val_if_fail (source->context != NULL, 0);
1104 LOCK_CONTEXT (source->context);
1105 result = source->source_id;
1106 UNLOCK_CONTEXT (source->context);
1112 * g_source_get_context:
1113 * @source: a #GSource
1115 * Gets the #GMainContext with which the source is associated.
1116 * Calling this function on a destroyed source is an error.
1118 * Return value: the #GMainContext with which the source is associated,
1119 * or %NULL if the context has not yet been added
1123 g_source_get_context (GSource *source)
1125 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1127 return source->context;
1131 * g_source_add_poll:
1132 * @source:a #GSource
1133 * @fd: a #GPollFD structure holding information about a file
1134 * descriptor to watch.
1136 * Adds a file descriptor to the set of file descriptors polled for
1137 * this source. This is usually combined with g_source_new() to add an
1138 * event source. The event source's check function will typically test
1139 * the @revents field in the #GPollFD struct and return %TRUE if events need
1143 g_source_add_poll (GSource *source,
1146 GMainContext *context;
1148 g_return_if_fail (source != NULL);
1149 g_return_if_fail (fd != NULL);
1150 g_return_if_fail (!SOURCE_DESTROYED (source));
1152 context = source->context;
1155 LOCK_CONTEXT (context);
1157 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1161 if (!SOURCE_BLOCKED (source))
1162 g_main_context_add_poll_unlocked (context, source->priority, fd);
1163 UNLOCK_CONTEXT (context);
1168 * g_source_remove_poll:
1169 * @source:a #GSource
1170 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1172 * Removes a file descriptor from the set of file descriptors polled for
1176 g_source_remove_poll (GSource *source,
1179 GMainContext *context;
1181 g_return_if_fail (source != NULL);
1182 g_return_if_fail (fd != NULL);
1183 g_return_if_fail (!SOURCE_DESTROYED (source));
1185 context = source->context;
1188 LOCK_CONTEXT (context);
1190 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1194 if (!SOURCE_BLOCKED (source))
1195 g_main_context_remove_poll_unlocked (context, fd);
1196 UNLOCK_CONTEXT (context);
1201 * g_source_set_callback_indirect:
1202 * @source: the source
1203 * @callback_data: pointer to callback data "object"
1204 * @callback_funcs: functions for reference counting @callback_data
1205 * and getting the callback and data
1207 * Sets the callback function storing the data as a refcounted callback
1208 * "object". This is used internally. Note that calling
1209 * g_source_set_callback_indirect() assumes
1210 * an initial reference count on @callback_data, and thus
1211 * @callback_funcs->unref will eventually be called once more
1212 * than @callback_funcs->ref.
1215 g_source_set_callback_indirect (GSource *source,
1216 gpointer callback_data,
1217 GSourceCallbackFuncs *callback_funcs)
1219 GMainContext *context;
1220 gpointer old_cb_data;
1221 GSourceCallbackFuncs *old_cb_funcs;
1223 g_return_if_fail (source != NULL);
1224 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1226 context = source->context;
1229 LOCK_CONTEXT (context);
1231 old_cb_data = source->callback_data;
1232 old_cb_funcs = source->callback_funcs;
1234 source->callback_data = callback_data;
1235 source->callback_funcs = callback_funcs;
1238 UNLOCK_CONTEXT (context);
1241 old_cb_funcs->unref (old_cb_data);
1245 g_source_callback_ref (gpointer cb_data)
1247 GSourceCallback *callback = cb_data;
1249 callback->ref_count++;
1254 g_source_callback_unref (gpointer cb_data)
1256 GSourceCallback *callback = cb_data;
1258 callback->ref_count--;
1259 if (callback->ref_count == 0)
1261 if (callback->notify)
1262 callback->notify (callback->data);
1268 g_source_callback_get (gpointer cb_data,
1273 GSourceCallback *callback = cb_data;
1275 *func = callback->func;
1276 *data = callback->data;
1279 static GSourceCallbackFuncs g_source_callback_funcs = {
1280 g_source_callback_ref,
1281 g_source_callback_unref,
1282 g_source_callback_get,
1286 * g_source_set_callback:
1287 * @source: the source
1288 * @func: a callback function
1289 * @data: the data to pass to callback function
1290 * @notify: a function to call when @data is no longer in use, or %NULL.
1292 * Sets the callback function for a source. The callback for a source is
1293 * called from the source's dispatch function.
1295 * The exact type of @func depends on the type of source; ie. you
1296 * should not count on @func being called with @data as its first
1299 * Typically, you won't use this function. Instead use functions specific
1300 * to the type of source you are using.
1303 g_source_set_callback (GSource *source,
1306 GDestroyNotify notify)
1308 GSourceCallback *new_callback;
1310 g_return_if_fail (source != NULL);
1312 new_callback = g_new (GSourceCallback, 1);
1314 new_callback->ref_count = 1;
1315 new_callback->func = func;
1316 new_callback->data = data;
1317 new_callback->notify = notify;
1319 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1324 * g_source_set_funcs:
1325 * @source: a #GSource
1326 * @funcs: the new #GSourceFuncs
1328 * Sets the source functions (can be used to override
1329 * default implementations) of an unattached source.
1334 g_source_set_funcs (GSource *source,
1335 GSourceFuncs *funcs)
1337 g_return_if_fail (source != NULL);
1338 g_return_if_fail (source->context == NULL);
1339 g_return_if_fail (source->ref_count > 0);
1340 g_return_if_fail (funcs != NULL);
1342 source->source_funcs = funcs;
1346 * g_source_set_priority:
1347 * @source: a #GSource
1348 * @priority: the new priority.
1350 * Sets the priority of a source. While the main loop is being
1351 * run, a source will be dispatched if it is ready to be dispatched and no sources
1352 * at a higher (numerically smaller) priority are ready to be dispatched.
1355 g_source_set_priority (GSource *source,
1359 GMainContext *context;
1361 g_return_if_fail (source != NULL);
1363 context = source->context;
1366 LOCK_CONTEXT (context);
1368 source->priority = priority;
1372 /* Remove the source from the context's source and then
1373 * add it back so it is sorted in the correct plcae
1375 g_source_list_remove (source, source->context);
1376 g_source_list_add (source, source->context);
1378 if (!SOURCE_BLOCKED (source))
1380 tmp_list = source->poll_fds;
1383 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1384 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1386 tmp_list = tmp_list->next;
1390 UNLOCK_CONTEXT (source->context);
1395 * g_source_get_priority:
1396 * @source: a #GSource
1398 * Gets the priority of a source.
1400 * Return value: the priority of the source
1403 g_source_get_priority (GSource *source)
1405 g_return_val_if_fail (source != NULL, 0);
1407 return source->priority;
1411 * g_source_set_can_recurse:
1412 * @source: a #GSource
1413 * @can_recurse: whether recursion is allowed for this source
1415 * Sets whether a source can be called recursively. If @can_recurse is
1416 * %TRUE, then while the source is being dispatched then this source
1417 * will be processed normally. Otherwise, all processing of this
1418 * source is blocked until the dispatch function returns.
1421 g_source_set_can_recurse (GSource *source,
1422 gboolean can_recurse)
1424 GMainContext *context;
1426 g_return_if_fail (source != NULL);
1428 context = source->context;
1431 LOCK_CONTEXT (context);
1434 source->flags |= G_SOURCE_CAN_RECURSE;
1436 source->flags &= ~G_SOURCE_CAN_RECURSE;
1439 UNLOCK_CONTEXT (context);
1443 * g_source_get_can_recurse:
1444 * @source: a #GSource
1446 * Checks whether a source is allowed to be called recursively.
1447 * see g_source_set_can_recurse().
1449 * Return value: whether recursion is allowed.
1452 g_source_get_can_recurse (GSource *source)
1454 g_return_val_if_fail (source != NULL, FALSE);
1456 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1461 * @source: a #GSource
1463 * Increases the reference count on a source by one.
1465 * Return value: @source
1468 g_source_ref (GSource *source)
1470 GMainContext *context;
1472 g_return_val_if_fail (source != NULL, NULL);
1474 context = source->context;
1477 LOCK_CONTEXT (context);
1479 source->ref_count++;
1482 UNLOCK_CONTEXT (context);
1487 /* g_source_unref() but possible to call within context lock
1490 g_source_unref_internal (GSource *source,
1491 GMainContext *context,
1494 gpointer old_cb_data = NULL;
1495 GSourceCallbackFuncs *old_cb_funcs = NULL;
1497 g_return_if_fail (source != NULL);
1499 if (!have_lock && context)
1500 LOCK_CONTEXT (context);
1502 source->ref_count--;
1503 if (source->ref_count == 0)
1505 old_cb_data = source->callback_data;
1506 old_cb_funcs = source->callback_funcs;
1508 source->callback_data = NULL;
1509 source->callback_funcs = NULL;
1511 if (context && !SOURCE_DESTROYED (source))
1513 g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1514 source->ref_count++;
1517 g_source_list_remove (source, context);
1519 if (source->source_funcs->finalize)
1520 source->source_funcs->finalize (source);
1522 g_slist_free (source->poll_fds);
1523 source->poll_fds = NULL;
1527 if (!have_lock && context)
1528 UNLOCK_CONTEXT (context);
1533 UNLOCK_CONTEXT (context);
1535 old_cb_funcs->unref (old_cb_data);
1538 LOCK_CONTEXT (context);
1544 * @source: a #GSource
1546 * Decreases the reference count of a source by one. If the
1547 * resulting reference count is zero the source and associated
1548 * memory will be destroyed.
1551 g_source_unref (GSource *source)
1553 g_return_if_fail (source != NULL);
1555 g_source_unref_internal (source, source->context, FALSE);
1559 * g_main_context_find_source_by_id:
1560 * @context: a #GMainContext (if %NULL, the default context will be used)
1561 * @source_id: the source ID, as returned by g_source_get_id().
1563 * Finds a #GSource given a pair of context and ID.
1565 * Return value: the #GSource if found, otherwise, %NULL
1568 g_main_context_find_source_by_id (GMainContext *context,
1573 g_return_val_if_fail (source_id > 0, NULL);
1575 if (context == NULL)
1576 context = g_main_context_default ();
1578 LOCK_CONTEXT (context);
1580 source = context->source_list;
1583 if (!SOURCE_DESTROYED (source) &&
1584 source->source_id == source_id)
1586 source = source->next;
1589 UNLOCK_CONTEXT (context);
1595 * g_main_context_find_source_by_funcs_user_data:
1596 * @context: a #GMainContext (if %NULL, the default context will be used).
1597 * @funcs: the @source_funcs passed to g_source_new().
1598 * @user_data: the user data from the callback.
1600 * Finds a source with the given source functions and user data. If
1601 * multiple sources exist with the same source function and user data,
1602 * the first one found will be returned.
1604 * Return value: the source, if one was found, otherwise %NULL
1607 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1608 GSourceFuncs *funcs,
1613 g_return_val_if_fail (funcs != NULL, NULL);
1615 if (context == NULL)
1616 context = g_main_context_default ();
1618 LOCK_CONTEXT (context);
1620 source = context->source_list;
1623 if (!SOURCE_DESTROYED (source) &&
1624 source->source_funcs == funcs &&
1625 source->callback_funcs)
1627 GSourceFunc callback;
1628 gpointer callback_data;
1630 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1632 if (callback_data == user_data)
1635 source = source->next;
1638 UNLOCK_CONTEXT (context);
1644 * g_main_context_find_source_by_user_data:
1645 * @context: a #GMainContext
1646 * @user_data: the user_data for the callback.
1648 * Finds a source with the given user data for the callback. If
1649 * multiple sources exist with the same user data, the first
1650 * one found will be returned.
1652 * Return value: the source, if one was found, otherwise %NULL
1655 g_main_context_find_source_by_user_data (GMainContext *context,
1660 if (context == NULL)
1661 context = g_main_context_default ();
1663 LOCK_CONTEXT (context);
1665 source = context->source_list;
1668 if (!SOURCE_DESTROYED (source) &&
1669 source->callback_funcs)
1671 GSourceFunc callback;
1672 gpointer callback_data = NULL;
1674 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1676 if (callback_data == user_data)
1679 source = source->next;
1682 UNLOCK_CONTEXT (context);
1689 * @tag: the ID of the source to remove.
1691 * Removes the source with the given id from the default main context.
1693 * a #GSource is given by g_source_get_id(), or will be returned by the
1694 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1695 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1696 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1698 * See also g_source_destroy().
1700 * Return value: %TRUE if the source was found and removed.
1703 g_source_remove (guint tag)
1707 g_return_val_if_fail (tag > 0, FALSE);
1709 source = g_main_context_find_source_by_id (NULL, tag);
1711 g_source_destroy (source);
1713 return source != NULL;
1717 * g_source_remove_by_user_data:
1718 * @user_data: the user_data for the callback.
1720 * Removes a source from the default main loop context given the user
1721 * data for the callback. If multiple sources exist with the same user
1722 * data, only one will be destroyed.
1724 * Return value: %TRUE if a source was found and removed.
1727 g_source_remove_by_user_data (gpointer user_data)
1731 source = g_main_context_find_source_by_user_data (NULL, user_data);
1734 g_source_destroy (source);
1742 * g_source_remove_by_funcs_user_data:
1743 * @funcs: The @source_funcs passed to g_source_new()
1744 * @user_data: the user data for the callback
1746 * Removes a source from the default main loop context given the
1747 * source functions and user data. If multiple sources exist with the
1748 * same source functions and user data, only one will be destroyed.
1750 * Return value: %TRUE if a source was found and removed.
1753 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1758 g_return_val_if_fail (funcs != NULL, FALSE);
1760 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1763 g_source_destroy (source);
1771 * g_get_current_time:
1772 * @result: #GTimeVal structure in which to store current time.
1774 * Equivalent to the UNIX gettimeofday() function, but portable.
1777 g_get_current_time (GTimeVal *result)
1782 g_return_if_fail (result != NULL);
1784 /*this is required on alpha, there the timeval structs are int's
1785 not longs and a cast only would fail horribly*/
1786 gettimeofday (&r, NULL);
1787 result->tv_sec = r.tv_sec;
1788 result->tv_usec = r.tv_usec;
1793 g_return_if_fail (result != NULL);
1795 GetSystemTimeAsFileTime (&ft);
1796 memmove (&time64, &ft, sizeof (FILETIME));
1798 /* Convert from 100s of nanoseconds since 1601-01-01
1799 * to Unix epoch. Yes, this is Y2038 unsafe.
1801 time64 -= G_GINT64_CONSTANT (116444736000000000);
1804 result->tv_sec = time64 / 1000000;
1805 result->tv_usec = time64 % 1000000;
1810 g_main_dispatch_free (gpointer dispatch)
1812 g_slice_free (GMainDispatch, dispatch);
1815 /* Running the main loop */
1817 static GMainDispatch *
1820 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
1821 GMainDispatch *dispatch = g_static_private_get (&depth_private);
1824 dispatch = g_slice_new0 (GMainDispatch);
1825 g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
1834 * Returns the depth of the stack of calls to
1835 * g_main_context_dispatch() on any #GMainContext in the current thread.
1836 * That is, when called from the toplevel, it gives 0. When
1837 * called from within a callback from g_main_context_iteration()
1838 * (or g_main_loop_run(), etc.) it returns 1. When called from within
1839 * a callback to a recursive call to g_main_context_iterate(),
1840 * it returns 2. And so forth.
1842 * This function is useful in a situation like the following:
1843 * Imagine an extremely simple "garbage collected" system.
1846 * static GList *free_list;
1849 * allocate_memory (gsize size)
1851 * gpointer result = g_malloc (size);
1852 * free_list = g_list_prepend (free_list, result);
1857 * free_allocated_memory (void)
1860 * for (l = free_list; l; l = l->next);
1862 * g_list_free (free_list);
1870 * g_main_context_iteration (NULL, TRUE);
1871 * free_allocated_memory();
1875 * This works from an application, however, if you want to do the same
1876 * thing from a library, it gets more difficult, since you no longer
1877 * control the main loop. You might think you can simply use an idle
1878 * function to make the call to free_allocated_memory(), but that
1879 * doesn't work, since the idle function could be called from a
1880 * recursive callback. This can be fixed by using g_main_depth()
1884 * allocate_memory (gsize size)
1886 * FreeListBlock *block = g_new (FreeListBlock, 1);
1887 * block->mem = g_malloc (size);
1888 * block->depth = g_main_depth ();
1889 * free_list = g_list_prepend (free_list, block);
1890 * return block->mem;
1894 * free_allocated_memory (void)
1898 * int depth = g_main_depth ();
1899 * for (l = free_list; l; );
1901 * GList *next = l->next;
1902 * FreeListBlock *block = l->data;
1903 * if (block->depth > depth)
1905 * g_free (block->mem);
1907 * free_list = g_list_delete_link (free_list, l);
1915 * There is a temptation to use g_main_depth() to solve
1916 * problems with reentrancy. For instance, while waiting for data
1917 * to be received from the network in response to a menu item,
1918 * the menu item might be selected again. It might seem that
1919 * one could make the menu item's callback return immediately
1920 * and do nothing if g_main_depth() returns a value greater than 1.
1921 * However, this should be avoided since the user then sees selecting
1922 * the menu item do nothing. Furthermore, you'll find yourself adding
1923 * these checks all over your code, since there are doubtless many,
1924 * many things that the user could do. Instead, you can use the
1925 * following techniques:
1930 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
1931 * the user from interacting with elements while the main
1932 * loop is recursing.
1937 * Avoid main loop recursion in situations where you can't handle
1938 * arbitrary callbacks. Instead, structure your code so that you
1939 * simply return to the main loop and then get called again when
1940 * there is more work to do.
1945 * Return value: The main loop recursion level in the current thread
1950 GMainDispatch *dispatch = get_dispatch ();
1951 return dispatch->depth;
1955 * g_main_current_source:
1957 * Returns the currently firing source for this thread.
1959 * Return value: The currently firing source or %NULL.
1964 g_main_current_source (void)
1966 GMainDispatch *dispatch = get_dispatch ();
1967 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
1971 * g_source_is_destroyed:
1972 * @source: a #GSource
1974 * Returns whether @source has been destroyed.
1976 * This is important when you operate upon your objects
1977 * from within idle handlers, but may have freed the object
1978 * before the dispatch of your idle handler.
1982 * idle_callback (gpointer data)
1984 * SomeWidget *self = data;
1986 * GDK_THREADS_ENTER (<!-- -->);
1987 * /<!-- -->* do stuff with self *<!-- -->/
1988 * self->idle_id = 0;
1989 * GDK_THREADS_LEAVE (<!-- -->);
1995 * some_widget_do_stuff_later (SomeWidget *self)
1997 * self->idle_id = g_idle_add (idle_callback, self);
2001 * some_widget_finalize (GObject *object)
2003 * SomeWidget *self = SOME_WIDGET (object);
2005 * if (self->idle_id)
2006 * g_source_remove (self->idle_id);
2008 * G_OBJECT_CLASS (parent_class)->finalize (object);
2012 * This will fail in a multi-threaded application if the
2013 * widget is destroyed before the idle handler fires due
2014 * to the use after free in the callback. A solution, to
2015 * this particular problem, is to check to if the source
2016 * has already been destroy within the callback.
2020 * idle_callback (gpointer data)
2022 * SomeWidget *self = data;
2024 * GDK_THREADS_ENTER ();
2025 * if (!g_source_is_destroyed (g_main_current_source ()))
2027 * /<!-- -->* do stuff with self *<!-- -->/
2029 * GDK_THREADS_LEAVE ();
2035 * Return value: %TRUE if the source has been destroyed
2040 g_source_is_destroyed (GSource *source)
2042 return SOURCE_DESTROYED (source);
2046 /* Temporarily remove all this source's file descriptors from the
2047 * poll(), so that if data comes available for one of the file descriptors
2048 * we don't continually spin in the poll()
2050 /* HOLDS: source->context's lock */
2052 block_source (GSource *source)
2056 g_return_if_fail (!SOURCE_BLOCKED (source));
2058 tmp_list = source->poll_fds;
2061 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2062 tmp_list = tmp_list->next;
2066 /* HOLDS: source->context's lock */
2068 unblock_source (GSource *source)
2072 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
2073 g_return_if_fail (!SOURCE_DESTROYED (source));
2075 tmp_list = source->poll_fds;
2078 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2079 tmp_list = tmp_list->next;
2083 /* HOLDS: context's lock */
2085 g_main_dispatch (GMainContext *context)
2087 GMainDispatch *current = get_dispatch ();
2090 for (i = 0; i < context->pending_dispatches->len; i++)
2092 GSource *source = context->pending_dispatches->pdata[i];
2094 context->pending_dispatches->pdata[i] = NULL;
2097 source->flags &= ~G_SOURCE_READY;
2099 if (!SOURCE_DESTROYED (source))
2101 gboolean was_in_call;
2102 gpointer user_data = NULL;
2103 GSourceFunc callback = NULL;
2104 GSourceCallbackFuncs *cb_funcs;
2106 gboolean need_destroy;
2108 gboolean (*dispatch) (GSource *,
2111 GSList current_source_link;
2113 dispatch = source->source_funcs->dispatch;
2114 cb_funcs = source->callback_funcs;
2115 cb_data = source->callback_data;
2118 cb_funcs->ref (cb_data);
2120 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2121 block_source (source);
2123 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2124 source->flags |= G_HOOK_FLAG_IN_CALL;
2127 cb_funcs->get (cb_data, source, &callback, &user_data);
2129 UNLOCK_CONTEXT (context);
2132 /* The on-stack allocation of the GSList is unconventional, but
2133 * we know that the lifetime of the link is bounded to this
2134 * function as the link is kept in a thread specific list and
2135 * not manipulated outside of this function and its descendants.
2136 * Avoiding the overhead of a g_slist_alloc() is useful as many
2137 * applications do little more than dispatch events.
2139 * This is a performance hack - do not revert to g_slist_prepend()!
2141 current_source_link.data = source;
2142 current_source_link.next = current->dispatching_sources;
2143 current->dispatching_sources = ¤t_source_link;
2144 need_destroy = ! dispatch (source,
2147 g_assert (current->dispatching_sources == ¤t_source_link);
2148 current->dispatching_sources = current_source_link.next;
2152 cb_funcs->unref (cb_data);
2154 LOCK_CONTEXT (context);
2157 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2159 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2160 !SOURCE_DESTROYED (source))
2161 unblock_source (source);
2163 /* Note: this depends on the fact that we can't switch
2164 * sources from one main context to another
2166 if (need_destroy && !SOURCE_DESTROYED (source))
2168 g_assert (source->context == context);
2169 g_source_destroy_internal (source, context, TRUE);
2173 SOURCE_UNREF (source, context);
2176 g_ptr_array_set_size (context->pending_dispatches, 0);
2179 /* Holds context's lock */
2180 static inline GSource *
2181 next_valid_source (GMainContext *context,
2184 GSource *new_source = source ? source->next : context->source_list;
2188 if (!SOURCE_DESTROYED (new_source))
2190 new_source->ref_count++;
2194 new_source = new_source->next;
2198 SOURCE_UNREF (source, context);
2204 * g_main_context_acquire:
2205 * @context: a #GMainContext
2207 * Tries to become the owner of the specified context.
2208 * If some other thread is the owner of the context,
2209 * returns %FALSE immediately. Ownership is properly
2210 * recursive: the owner can require ownership again
2211 * and will release ownership when g_main_context_release()
2212 * is called as many times as g_main_context_acquire().
2214 * You must be the owner of a context before you
2215 * can call g_main_context_prepare(), g_main_context_query(),
2216 * g_main_context_check(), g_main_context_dispatch().
2218 * Return value: %TRUE if the operation succeeded, and
2219 * this thread is now the owner of @context.
2222 g_main_context_acquire (GMainContext *context)
2224 #ifdef G_THREADS_ENABLED
2225 gboolean result = FALSE;
2226 GThread *self = G_THREAD_SELF;
2228 if (context == NULL)
2229 context = g_main_context_default ();
2231 LOCK_CONTEXT (context);
2233 if (!context->owner)
2235 context->owner = self;
2236 g_assert (context->owner_count == 0);
2239 if (context->owner == self)
2241 context->owner_count++;
2245 UNLOCK_CONTEXT (context);
2248 #else /* !G_THREADS_ENABLED */
2250 #endif /* G_THREADS_ENABLED */
2254 * g_main_context_release:
2255 * @context: a #GMainContext
2257 * Releases ownership of a context previously acquired by this thread
2258 * with g_main_context_acquire(). If the context was acquired multiple
2259 * times, the ownership will be released only when g_main_context_release()
2260 * is called as many times as it was acquired.
2263 g_main_context_release (GMainContext *context)
2265 #ifdef G_THREADS_ENABLED
2266 if (context == NULL)
2267 context = g_main_context_default ();
2269 LOCK_CONTEXT (context);
2271 context->owner_count--;
2272 if (context->owner_count == 0)
2274 context->owner = NULL;
2276 if (context->waiters)
2278 GMainWaiter *waiter = context->waiters->data;
2279 gboolean loop_internal_waiter =
2280 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
2281 context->waiters = g_slist_delete_link (context->waiters,
2283 if (!loop_internal_waiter)
2284 g_mutex_lock (waiter->mutex);
2286 g_cond_signal (waiter->cond);
2288 if (!loop_internal_waiter)
2289 g_mutex_unlock (waiter->mutex);
2293 UNLOCK_CONTEXT (context);
2294 #endif /* G_THREADS_ENABLED */
2298 * g_main_context_wait:
2299 * @context: a #GMainContext
2300 * @cond: a condition variable
2301 * @mutex: a mutex, currently held
2303 * Tries to become the owner of the specified context,
2304 * as with g_main_context_acquire(). But if another thread
2305 * is the owner, atomically drop @mutex and wait on @cond until
2306 * that owner releases ownership or until @cond is signaled, then
2307 * try again (once) to become the owner.
2309 * Return value: %TRUE if the operation succeeded, and
2310 * this thread is now the owner of @context.
2313 g_main_context_wait (GMainContext *context,
2317 #ifdef G_THREADS_ENABLED
2318 gboolean result = FALSE;
2319 GThread *self = G_THREAD_SELF;
2320 gboolean loop_internal_waiter;
2322 if (context == NULL)
2323 context = g_main_context_default ();
2325 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2327 if (!loop_internal_waiter)
2328 LOCK_CONTEXT (context);
2330 if (context->owner && context->owner != self)
2335 waiter.mutex = mutex;
2337 context->waiters = g_slist_append (context->waiters, &waiter);
2339 if (!loop_internal_waiter)
2340 UNLOCK_CONTEXT (context);
2341 g_cond_wait (cond, mutex);
2342 if (!loop_internal_waiter)
2343 LOCK_CONTEXT (context);
2345 context->waiters = g_slist_remove (context->waiters, &waiter);
2348 if (!context->owner)
2350 context->owner = self;
2351 g_assert (context->owner_count == 0);
2354 if (context->owner == self)
2356 context->owner_count++;
2360 if (!loop_internal_waiter)
2361 UNLOCK_CONTEXT (context);
2364 #else /* !G_THREADS_ENABLED */
2366 #endif /* G_THREADS_ENABLED */
2370 * g_main_context_prepare:
2371 * @context: a #GMainContext
2372 * @priority: location to store priority of highest priority
2373 * source already ready.
2375 * Prepares to poll sources within a main loop. The resulting information
2376 * for polling is determined by calling g_main_context_query ().
2378 * Return value: %TRUE if some source is ready to be dispatched
2382 g_main_context_prepare (GMainContext *context,
2387 gint current_priority = G_MAXINT;
2390 if (context == NULL)
2391 context = g_main_context_default ();
2393 LOCK_CONTEXT (context);
2395 context->time_is_current = FALSE;
2397 if (context->in_check_or_prepare)
2399 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2400 "prepare() member.");
2401 UNLOCK_CONTEXT (context);
2405 #ifdef G_THREADS_ENABLED
2406 if (context->poll_waiting)
2408 g_warning("g_main_context_prepare(): main loop already active in another thread");
2409 UNLOCK_CONTEXT (context);
2413 context->poll_waiting = TRUE;
2414 #endif /* G_THREADS_ENABLED */
2417 /* If recursing, finish up current dispatch, before starting over */
2418 if (context->pending_dispatches)
2421 g_main_dispatch (context, ¤t_time);
2423 UNLOCK_CONTEXT (context);
2428 /* If recursing, clear list of pending dispatches */
2430 for (i = 0; i < context->pending_dispatches->len; i++)
2432 if (context->pending_dispatches->pdata[i])
2433 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2435 g_ptr_array_set_size (context->pending_dispatches, 0);
2437 /* Prepare all sources */
2439 context->timeout = -1;
2441 source = next_valid_source (context, NULL);
2444 gint source_timeout = -1;
2446 if ((n_ready > 0) && (source->priority > current_priority))
2448 SOURCE_UNREF (source, context);
2451 if (SOURCE_BLOCKED (source))
2454 if (!(source->flags & G_SOURCE_READY))
2457 gboolean (*prepare) (GSource *source,
2460 prepare = source->source_funcs->prepare;
2461 context->in_check_or_prepare++;
2462 UNLOCK_CONTEXT (context);
2464 result = (*prepare) (source, &source_timeout);
2466 LOCK_CONTEXT (context);
2467 context->in_check_or_prepare--;
2470 source->flags |= G_SOURCE_READY;
2473 if (source->flags & G_SOURCE_READY)
2476 current_priority = source->priority;
2477 context->timeout = 0;
2480 if (source_timeout >= 0)
2482 if (context->timeout < 0)
2483 context->timeout = source_timeout;
2485 context->timeout = MIN (context->timeout, source_timeout);
2489 source = next_valid_source (context, source);
2492 UNLOCK_CONTEXT (context);
2495 *priority = current_priority;
2497 return (n_ready > 0);
2501 * g_main_context_query:
2502 * @context: a #GMainContext
2503 * @max_priority: maximum priority source to check
2504 * @timeout_: location to store timeout to be used in polling
2505 * @fds: location to store #GPollFD records that need to be polled.
2506 * @n_fds: length of @fds.
2508 * Determines information necessary to poll this main loop.
2510 * Return value: the number of records actually stored in @fds,
2511 * or, if more than @n_fds records need to be stored, the number
2512 * of records that need to be stored.
2515 g_main_context_query (GMainContext *context,
2524 LOCK_CONTEXT (context);
2526 pollrec = context->poll_records;
2528 while (pollrec && max_priority >= pollrec->priority)
2530 /* We need to include entries with fd->events == 0 in the array because
2531 * otherwise if the application changes fd->events behind our back and
2532 * makes it non-zero, we'll be out of sync when we check the fds[] array.
2533 * (Changing fd->events after adding an FD wasn't an anticipated use of
2534 * this API, but it occurs in practice.) */
2537 fds[n_poll].fd = pollrec->fd->fd;
2538 /* In direct contradiction to the Unix98 spec, IRIX runs into
2539 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2540 * flags in the events field of the pollfd while it should
2541 * just ignoring them. So we mask them out here.
2543 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2544 fds[n_poll].revents = 0;
2547 pollrec = pollrec->next;
2551 #ifdef G_THREADS_ENABLED
2552 context->poll_changed = FALSE;
2557 *timeout = context->timeout;
2559 context->time_is_current = FALSE;
2562 UNLOCK_CONTEXT (context);
2568 * g_main_context_check:
2569 * @context: a #GMainContext
2570 * @max_priority: the maximum numerical priority of sources to check
2571 * @fds: array of #GPollFD's that was passed to the last call to
2572 * g_main_context_query()
2573 * @n_fds: return value of g_main_context_query()
2575 * Passes the results of polling back to the main loop.
2577 * Return value: %TRUE if some sources are ready to be dispatched.
2580 g_main_context_check (GMainContext *context,
2590 LOCK_CONTEXT (context);
2592 if (context->in_check_or_prepare)
2594 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2595 "prepare() member.");
2596 UNLOCK_CONTEXT (context);
2600 #ifdef G_THREADS_ENABLED
2601 if (!context->poll_waiting)
2605 read (context->wake_up_pipe[0], &a, 1);
2609 context->poll_waiting = FALSE;
2611 /* If the set of poll file descriptors changed, bail out
2612 * and let the main loop rerun
2614 if (context->poll_changed)
2616 UNLOCK_CONTEXT (context);
2619 #endif /* G_THREADS_ENABLED */
2621 pollrec = context->poll_records;
2625 if (pollrec->fd->events)
2626 pollrec->fd->revents = fds[i].revents;
2628 pollrec = pollrec->next;
2632 source = next_valid_source (context, NULL);
2635 if ((n_ready > 0) && (source->priority > max_priority))
2637 SOURCE_UNREF (source, context);
2640 if (SOURCE_BLOCKED (source))
2643 if (!(source->flags & G_SOURCE_READY))
2646 gboolean (*check) (GSource *source);
2648 check = source->source_funcs->check;
2650 context->in_check_or_prepare++;
2651 UNLOCK_CONTEXT (context);
2653 result = (*check) (source);
2655 LOCK_CONTEXT (context);
2656 context->in_check_or_prepare--;
2659 source->flags |= G_SOURCE_READY;
2662 if (source->flags & G_SOURCE_READY)
2664 source->ref_count++;
2665 g_ptr_array_add (context->pending_dispatches, source);
2669 /* never dispatch sources with less priority than the first
2670 * one we choose to dispatch
2672 max_priority = source->priority;
2676 source = next_valid_source (context, source);
2679 UNLOCK_CONTEXT (context);
2685 * g_main_context_dispatch:
2686 * @context: a #GMainContext
2688 * Dispatches all pending sources.
2691 g_main_context_dispatch (GMainContext *context)
2693 LOCK_CONTEXT (context);
2695 if (context->pending_dispatches->len > 0)
2697 g_main_dispatch (context);
2700 UNLOCK_CONTEXT (context);
2703 /* HOLDS context lock */
2705 g_main_context_iterate (GMainContext *context,
2712 gboolean some_ready;
2713 gint nfds, allocated_nfds;
2714 GPollFD *fds = NULL;
2716 UNLOCK_CONTEXT (context);
2718 #ifdef G_THREADS_ENABLED
2719 if (!g_main_context_acquire (context))
2721 gboolean got_ownership;
2723 g_return_val_if_fail (g_thread_supported (), FALSE);
2728 LOCK_CONTEXT (context);
2731 context->cond = g_cond_new ();
2733 got_ownership = g_main_context_wait (context,
2735 g_static_mutex_get_mutex (&context->mutex));
2739 UNLOCK_CONTEXT (context);
2744 LOCK_CONTEXT (context);
2745 #endif /* G_THREADS_ENABLED */
2747 if (!context->cached_poll_array)
2749 context->cached_poll_array_size = context->n_poll_records;
2750 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2753 allocated_nfds = context->cached_poll_array_size;
2754 fds = context->cached_poll_array;
2756 UNLOCK_CONTEXT (context);
2758 g_main_context_prepare (context, &max_priority);
2760 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
2761 allocated_nfds)) > allocated_nfds)
2763 LOCK_CONTEXT (context);
2765 context->cached_poll_array_size = allocated_nfds = nfds;
2766 context->cached_poll_array = fds = g_new (GPollFD, nfds);
2767 UNLOCK_CONTEXT (context);
2773 g_main_context_poll (context, timeout, max_priority, fds, nfds);
2775 some_ready = g_main_context_check (context, max_priority, fds, nfds);
2778 g_main_context_dispatch (context);
2780 #ifdef G_THREADS_ENABLED
2781 g_main_context_release (context);
2782 #endif /* G_THREADS_ENABLED */
2784 LOCK_CONTEXT (context);
2790 * g_main_context_pending:
2791 * @context: a #GMainContext (if %NULL, the default context will be used)
2793 * Checks if any sources have pending events for the given context.
2795 * Return value: %TRUE if events are pending.
2798 g_main_context_pending (GMainContext *context)
2803 context = g_main_context_default();
2805 LOCK_CONTEXT (context);
2806 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
2807 UNLOCK_CONTEXT (context);
2813 * g_main_context_iteration:
2814 * @context: a #GMainContext (if %NULL, the default context will be used)
2815 * @may_block: whether the call may block.
2817 * Runs a single iteration for the given main loop. This involves
2818 * checking to see if any event sources are ready to be processed,
2819 * then if no events sources are ready and @may_block is %TRUE, waiting
2820 * for a source to become ready, then dispatching the highest priority
2821 * events sources that are ready. Otherwise, if @may_block is %FALSE
2822 * sources are not waited to become ready, only those highest priority
2823 * events sources will be dispatched (if any), that are ready at this
2824 * given moment without further waiting.
2826 * Note that even when @may_block is %TRUE, it is still possible for
2827 * g_main_context_iteration() to return %FALSE, since the the wait may
2828 * be interrupted for other reasons than an event source becoming ready.
2830 * Return value: %TRUE if events were dispatched.
2833 g_main_context_iteration (GMainContext *context, gboolean may_block)
2838 context = g_main_context_default();
2840 LOCK_CONTEXT (context);
2841 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
2842 UNLOCK_CONTEXT (context);
2849 * @context: a #GMainContext (if %NULL, the default context will be used).
2850 * @is_running: set to %TRUE to indicate that the loop is running. This
2851 * is not very important since calling g_main_loop_run() will set this to
2854 * Creates a new #GMainLoop structure.
2856 * Return value: a new #GMainLoop.
2859 g_main_loop_new (GMainContext *context,
2860 gboolean is_running)
2865 context = g_main_context_default();
2867 g_main_context_ref (context);
2869 loop = g_new0 (GMainLoop, 1);
2870 loop->context = context;
2871 loop->is_running = is_running != FALSE;
2872 loop->ref_count = 1;
2879 * @loop: a #GMainLoop
2881 * Increases the reference count on a #GMainLoop object by one.
2883 * Return value: @loop
2886 g_main_loop_ref (GMainLoop *loop)
2888 g_return_val_if_fail (loop != NULL, NULL);
2889 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2891 g_atomic_int_inc (&loop->ref_count);
2897 * g_main_loop_unref:
2898 * @loop: a #GMainLoop
2900 * Decreases the reference count on a #GMainLoop object by one. If
2901 * the result is zero, free the loop and free all associated memory.
2904 g_main_loop_unref (GMainLoop *loop)
2906 g_return_if_fail (loop != NULL);
2907 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2909 if (!g_atomic_int_dec_and_test (&loop->ref_count))
2912 g_main_context_unref (loop->context);
2918 * @loop: a #GMainLoop
2920 * Runs a main loop until g_main_loop_quit() is called on the loop.
2921 * If this is called for the thread of the loop's #GMainContext,
2922 * it will process events from the loop, otherwise it will
2926 g_main_loop_run (GMainLoop *loop)
2928 GThread *self = G_THREAD_SELF;
2930 g_return_if_fail (loop != NULL);
2931 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2933 #ifdef G_THREADS_ENABLED
2934 if (!g_main_context_acquire (loop->context))
2936 gboolean got_ownership = FALSE;
2938 /* Another thread owns this context */
2939 if (!g_thread_supported ())
2941 g_warning ("g_main_loop_run() was called from second thread but "
2942 "g_thread_init() was never called.");
2946 LOCK_CONTEXT (loop->context);
2948 g_atomic_int_inc (&loop->ref_count);
2950 if (!loop->is_running)
2951 loop->is_running = TRUE;
2953 if (!loop->context->cond)
2954 loop->context->cond = g_cond_new ();
2956 while (loop->is_running && !got_ownership)
2957 got_ownership = g_main_context_wait (loop->context,
2958 loop->context->cond,
2959 g_static_mutex_get_mutex (&loop->context->mutex));
2961 if (!loop->is_running)
2963 UNLOCK_CONTEXT (loop->context);
2965 g_main_context_release (loop->context);
2966 g_main_loop_unref (loop);
2970 g_assert (got_ownership);
2973 LOCK_CONTEXT (loop->context);
2974 #endif /* G_THREADS_ENABLED */
2976 if (loop->context->in_check_or_prepare)
2978 g_warning ("g_main_loop_run(): called recursively from within a source's "
2979 "check() or prepare() member, iteration not possible.");
2983 g_atomic_int_inc (&loop->ref_count);
2984 loop->is_running = TRUE;
2985 while (loop->is_running)
2986 g_main_context_iterate (loop->context, TRUE, TRUE, self);
2988 UNLOCK_CONTEXT (loop->context);
2990 #ifdef G_THREADS_ENABLED
2991 g_main_context_release (loop->context);
2992 #endif /* G_THREADS_ENABLED */
2994 g_main_loop_unref (loop);
2999 * @loop: a #GMainLoop
3001 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3002 * for the loop will return.
3004 * Note that sources that have already been dispatched when
3005 * g_main_loop_quit() is called will still be executed.
3008 g_main_loop_quit (GMainLoop *loop)
3010 g_return_if_fail (loop != NULL);
3011 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3013 LOCK_CONTEXT (loop->context);
3014 loop->is_running = FALSE;
3015 g_main_context_wakeup_unlocked (loop->context);
3017 #ifdef G_THREADS_ENABLED
3018 if (loop->context->cond)
3019 g_cond_broadcast (loop->context->cond);
3020 #endif /* G_THREADS_ENABLED */
3022 UNLOCK_CONTEXT (loop->context);
3026 * g_main_loop_is_running:
3027 * @loop: a #GMainLoop.
3029 * Checks to see if the main loop is currently being run via g_main_loop_run().
3031 * Return value: %TRUE if the mainloop is currently being run.
3034 g_main_loop_is_running (GMainLoop *loop)
3036 g_return_val_if_fail (loop != NULL, FALSE);
3037 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3039 return loop->is_running;
3043 * g_main_loop_get_context:
3044 * @loop: a #GMainLoop.
3046 * Returns the #GMainContext of @loop.
3048 * Return value: the #GMainContext of @loop
3051 g_main_loop_get_context (GMainLoop *loop)
3053 g_return_val_if_fail (loop != NULL, NULL);
3054 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3056 return loop->context;
3059 /* HOLDS: context's lock */
3061 g_main_context_poll (GMainContext *context,
3067 #ifdef G_MAIN_POLL_DEBUG
3073 GPollFunc poll_func;
3075 if (n_fds || timeout != 0)
3077 #ifdef G_MAIN_POLL_DEBUG
3078 if (g_main_poll_debug)
3080 g_print ("polling context=%p n=%d timeout=%d\n",
3081 context, n_fds, timeout);
3082 poll_timer = g_timer_new ();
3086 LOCK_CONTEXT (context);
3088 poll_func = context->poll_func;
3090 UNLOCK_CONTEXT (context);
3091 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3094 g_warning ("poll(2) failed due to: %s.",
3095 g_strerror (errno));
3097 /* If g_poll () returns -1, it has already called g_warning() */
3101 #ifdef G_MAIN_POLL_DEBUG
3102 if (g_main_poll_debug)
3104 LOCK_CONTEXT (context);
3106 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3109 g_timer_elapsed (poll_timer, NULL));
3110 g_timer_destroy (poll_timer);
3111 pollrec = context->poll_records;
3113 while (pollrec != NULL)
3118 if (fds[i].fd == pollrec->fd->fd &&
3119 pollrec->fd->events &&
3122 g_print (" [" GPOLLFD_FORMAT " :", fds[i].fd);
3123 if (fds[i].revents & G_IO_IN)
3125 if (fds[i].revents & G_IO_OUT)
3127 if (fds[i].revents & G_IO_PRI)
3129 if (fds[i].revents & G_IO_ERR)
3131 if (fds[i].revents & G_IO_HUP)
3133 if (fds[i].revents & G_IO_NVAL)
3139 pollrec = pollrec->next;
3143 UNLOCK_CONTEXT (context);
3146 } /* if (n_fds || timeout != 0) */
3150 * g_main_context_add_poll:
3151 * @context: a #GMainContext (or %NULL for the default context)
3152 * @fd: a #GPollFD structure holding information about a file
3153 * descriptor to watch.
3154 * @priority: the priority for this file descriptor which should be
3155 * the same as the priority used for g_source_attach() to ensure that the
3156 * file descriptor is polled whenever the results may be needed.
3158 * Adds a file descriptor to the set of file descriptors polled for
3159 * this context. This will very seldomly be used directly. Instead
3160 * a typical event source will use g_source_add_poll() instead.
3163 g_main_context_add_poll (GMainContext *context,
3168 context = g_main_context_default ();
3170 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3171 g_return_if_fail (fd);
3173 LOCK_CONTEXT (context);
3174 g_main_context_add_poll_unlocked (context, priority, fd);
3175 UNLOCK_CONTEXT (context);
3178 /* HOLDS: main_loop_lock */
3180 g_main_context_add_poll_unlocked (GMainContext *context,
3184 GPollRec *lastrec, *pollrec;
3185 GPollRec *newrec = g_slice_new (GPollRec);
3187 /* This file descriptor may be checked before we ever poll */
3190 newrec->priority = priority;
3193 pollrec = context->poll_records;
3194 while (pollrec && priority >= pollrec->priority)
3197 pollrec = pollrec->next;
3201 lastrec->next = newrec;
3203 context->poll_records = newrec;
3205 newrec->next = pollrec;
3207 context->n_poll_records++;
3209 #ifdef G_THREADS_ENABLED
3210 context->poll_changed = TRUE;
3212 /* Now wake up the main loop if it is waiting in the poll() */
3213 g_main_context_wakeup_unlocked (context);
3218 * g_main_context_remove_poll:
3219 * @context:a #GMainContext
3220 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3222 * Removes file descriptor from the set of file descriptors to be
3223 * polled for a particular context.
3226 g_main_context_remove_poll (GMainContext *context,
3230 context = g_main_context_default ();
3232 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3233 g_return_if_fail (fd);
3235 LOCK_CONTEXT (context);
3236 g_main_context_remove_poll_unlocked (context, fd);
3237 UNLOCK_CONTEXT (context);
3241 g_main_context_remove_poll_unlocked (GMainContext *context,
3244 GPollRec *pollrec, *lastrec;
3247 pollrec = context->poll_records;
3251 if (pollrec->fd == fd)
3253 if (lastrec != NULL)
3254 lastrec->next = pollrec->next;
3256 context->poll_records = pollrec->next;
3258 g_slice_free (GPollRec, pollrec);
3260 context->n_poll_records--;
3264 pollrec = pollrec->next;
3267 #ifdef G_THREADS_ENABLED
3268 context->poll_changed = TRUE;
3270 /* Now wake up the main loop if it is waiting in the poll() */
3271 g_main_context_wakeup_unlocked (context);
3276 * g_source_get_current_time:
3277 * @source: a #GSource
3278 * @timeval: #GTimeVal structure in which to store current time.
3280 * Gets the "current time" to be used when checking
3281 * this source. The advantage of calling this function over
3282 * calling g_get_current_time() directly is that when
3283 * checking multiple sources, GLib can cache a single value
3284 * instead of having to repeatedly get the system time.
3287 g_source_get_current_time (GSource *source,
3290 GMainContext *context;
3292 g_return_if_fail (source->context != NULL);
3294 context = source->context;
3296 LOCK_CONTEXT (context);
3298 if (!context->time_is_current)
3300 g_get_current_time (&context->current_time);
3301 context->time_is_current = TRUE;
3304 *timeval = context->current_time;
3306 UNLOCK_CONTEXT (context);
3310 * g_main_context_set_poll_func:
3311 * @context: a #GMainContext
3312 * @func: the function to call to poll all file descriptors
3314 * Sets the function to use to handle polling of file descriptors. It
3315 * will be used instead of the poll() system call
3316 * (or GLib's replacement function, which is used where
3317 * poll() isn't available).
3319 * This function could possibly be used to integrate the GLib event
3320 * loop with an external event loop.
3323 g_main_context_set_poll_func (GMainContext *context,
3327 context = g_main_context_default ();
3329 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3331 LOCK_CONTEXT (context);
3334 context->poll_func = func;
3338 context->poll_func = (GPollFunc) poll;
3340 context->poll_func = (GPollFunc) g_poll;
3344 UNLOCK_CONTEXT (context);
3348 * g_main_context_get_poll_func:
3349 * @context: a #GMainContext
3351 * Gets the poll function set by g_main_context_set_poll_func().
3353 * Return value: the poll function
3356 g_main_context_get_poll_func (GMainContext *context)
3361 context = g_main_context_default ();
3363 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3365 LOCK_CONTEXT (context);
3366 result = context->poll_func;
3367 UNLOCK_CONTEXT (context);
3372 /* HOLDS: context's lock */
3373 /* Wake the main loop up from a poll() */
3375 g_main_context_wakeup_unlocked (GMainContext *context)
3377 #ifdef G_THREADS_ENABLED
3378 if (g_thread_supported() && context->poll_waiting)
3380 context->poll_waiting = FALSE;
3382 write (context->wake_up_pipe[1], "A", 1);
3384 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
3391 * g_main_context_wakeup:
3392 * @context: a #GMainContext
3394 * If @context is currently waiting in a poll(), interrupt
3395 * the poll(), and continue the iteration process.
3398 g_main_context_wakeup (GMainContext *context)
3401 context = g_main_context_default ();
3403 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3405 LOCK_CONTEXT (context);
3406 g_main_context_wakeup_unlocked (context);
3407 UNLOCK_CONTEXT (context);
3411 * g_main_context_is_owner:
3412 * @context: a #GMainContext
3414 * Determines whether this thread holds the (recursive)
3415 * ownership of this #GMaincontext. This is useful to
3416 * know before waiting on another thread that may be
3417 * blocking to get ownership of @context.
3419 * Returns: %TRUE if current thread is owner of @context.
3424 g_main_context_is_owner (GMainContext *context)
3429 context = g_main_context_default ();
3431 #ifdef G_THREADS_ENABLED
3432 LOCK_CONTEXT (context);
3433 is_owner = context->owner == G_THREAD_SELF;
3434 UNLOCK_CONTEXT (context);
3445 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3446 GTimeVal *current_time)
3448 guint seconds = timeout_source->interval / 1000;
3449 guint msecs = timeout_source->interval - seconds * 1000;
3451 timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
3452 timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
3453 if (timeout_source->expiration.tv_usec >= 1000000)
3455 timeout_source->expiration.tv_usec -= 1000000;
3456 timeout_source->expiration.tv_sec++;
3458 if (timer_perturb==-1)
3461 * we want a per machine/session unique 'random' value; try the dbus
3462 * address first, that has a UUID in it. If there is no dbus, use the
3463 * hostname for hashing.
3465 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3466 if (!session_bus_address)
3467 session_bus_address = g_getenv ("HOSTNAME");
3468 if (session_bus_address)
3469 timer_perturb = ABS ((gint) g_str_hash (session_bus_address));
3473 if (timeout_source->granularity)
3476 gint gran; /* in usecs */
3479 gran = timeout_source->granularity * 1000;
3480 perturb = timer_perturb % gran;
3482 * We want to give each machine a per machine pertubation;
3483 * shift time back first, and forward later after the rounding
3486 timeout_source->expiration.tv_usec -= perturb;
3487 if (timeout_source->expiration.tv_usec < 0)
3489 timeout_source->expiration.tv_usec += 1000000;
3490 timeout_source->expiration.tv_sec--;
3493 remainder = timeout_source->expiration.tv_usec % gran;
3494 if (remainder >= gran/4) /* round up */
3495 timeout_source->expiration.tv_usec += gran;
3496 timeout_source->expiration.tv_usec -= remainder;
3498 timeout_source->expiration.tv_usec += perturb;
3500 /* the rounding may have overflown tv_usec */
3501 while (timeout_source->expiration.tv_usec > 1000000)
3503 timeout_source->expiration.tv_usec -= 1000000;
3504 timeout_source->expiration.tv_sec++;
3510 g_timeout_prepare (GSource *source,
3515 GTimeVal current_time;
3517 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3519 g_source_get_current_time (source, ¤t_time);
3521 sec = timeout_source->expiration.tv_sec - current_time.tv_sec;
3522 msec = (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000;
3524 /* We do the following in a rather convoluted fashion to deal with
3525 * the fact that we don't have an integral type big enough to hold
3526 * the difference of two timevals in millseconds.
3528 if (sec < 0 || (sec == 0 && msec < 0))
3532 glong interval_sec = timeout_source->interval / 1000;
3533 glong interval_msec = timeout_source->interval % 1000;
3541 if (sec > interval_sec ||
3542 (sec == interval_sec && msec > interval_msec))
3544 /* The system time has been set backwards, so we
3545 * reset the expiration time to now + timeout_source->interval;
3546 * this at least avoids hanging for long periods of time.
3548 g_timeout_set_expiration (timeout_source, ¤t_time);
3549 msec = MIN (G_MAXINT, timeout_source->interval);
3553 msec = MIN (G_MAXINT, (guint)msec + 1000 * (guint)sec);
3557 *timeout = (gint)msec;
3563 g_timeout_check (GSource *source)
3565 GTimeVal current_time;
3566 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3568 g_source_get_current_time (source, ¤t_time);
3570 return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
3571 ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
3572 (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
3576 g_timeout_dispatch (GSource *source,
3577 GSourceFunc callback,
3580 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3584 g_warning ("Timeout source dispatched without callback\n"
3585 "You must call g_source_set_callback().");
3589 if (callback (user_data))
3591 GTimeVal current_time;
3593 g_source_get_current_time (source, ¤t_time);
3594 g_timeout_set_expiration (timeout_source, ¤t_time);
3603 * g_timeout_source_new:
3604 * @interval: the timeout interval in milliseconds.
3606 * Creates a new timeout source.
3608 * The source will not initially be associated with any #GMainContext
3609 * and must be added to one with g_source_attach() before it will be
3612 * Return value: the newly-created timeout source
3615 g_timeout_source_new (guint interval)
3617 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3618 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3619 GTimeVal current_time;
3621 timeout_source->interval = interval;
3623 g_get_current_time (¤t_time);
3624 g_timeout_set_expiration (timeout_source, ¤t_time);
3630 * g_timeout_source_new_seconds:
3631 * @interval: the timeout interval in seconds
3633 * Creates a new timeout source.
3635 * The source will not initially be associated with any #GMainContext
3636 * and must be added to one with g_source_attach() before it will be
3639 * The scheduling granularity/accuracy of this timeout source will be
3642 * Return value: the newly-created timeout source
3647 g_timeout_source_new_seconds (guint interval)
3649 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3650 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3651 GTimeVal current_time;
3653 timeout_source->interval = 1000*interval;
3654 timeout_source->granularity = 1000;
3656 g_get_current_time (¤t_time);
3657 g_timeout_set_expiration (timeout_source, ¤t_time);
3664 * g_timeout_add_full:
3665 * @priority: the priority of the timeout source. Typically this will be in
3666 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3667 * @interval: the time between calls to the function, in milliseconds
3668 * (1/1000ths of a second)
3669 * @function: function to call
3670 * @data: data to pass to @function
3671 * @notify: function to call when the timeout is removed, or %NULL
3673 * Sets a function to be called at regular intervals, with the given
3674 * priority. The function is called repeatedly until it returns
3675 * %FALSE, at which point the timeout is automatically destroyed and
3676 * the function will not be called again. The @notify function is
3677 * called when the timeout is destroyed. The first call to the
3678 * function will be at the end of the first @interval.
3680 * Note that timeout functions may be delayed, due to the processing of other
3681 * event sources. Thus they should not be relied on for precise timing.
3682 * After each call to the timeout function, the time of the next
3683 * timeout is recalculated based on the current time and the given interval
3684 * (it does not try to 'catch up' time lost in delays).
3686 * Return value: the ID (greater than 0) of the event source.
3689 g_timeout_add_full (gint priority,
3691 GSourceFunc function,
3693 GDestroyNotify notify)
3698 g_return_val_if_fail (function != NULL, 0);
3700 source = g_timeout_source_new (interval);
3702 if (priority != G_PRIORITY_DEFAULT)
3703 g_source_set_priority (source, priority);
3705 g_source_set_callback (source, function, data, notify);
3706 id = g_source_attach (source, NULL);
3707 g_source_unref (source);
3714 * @interval: the time between calls to the function, in milliseconds
3715 * (1/1000ths of a second)
3716 * @function: function to call
3717 * @data: data to pass to @function
3719 * Sets a function to be called at regular intervals, with the default
3720 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
3721 * until it returns %FALSE, at which point the timeout is automatically
3722 * destroyed and the function will not be called again. The first call
3723 * to the function will be at the end of the first @interval.
3725 * Note that timeout functions may be delayed, due to the processing of other
3726 * event sources. Thus they should not be relied on for precise timing.
3727 * After each call to the timeout function, the time of the next
3728 * timeout is recalculated based on the current time and the given interval
3729 * (it does not try to 'catch up' time lost in delays).
3731 * If you want to have a timer in the "seconds" range and do not care
3732 * about the exact time of the first call of the timer, use the
3733 * g_timeout_add_seconds() function; this function allows for more
3734 * optimizations and more efficient system power usage.
3736 * Return value: the ID (greater than 0) of the event source.
3739 g_timeout_add (guint32 interval,
3740 GSourceFunc function,
3743 return g_timeout_add_full (G_PRIORITY_DEFAULT,
3744 interval, function, data, NULL);
3748 * g_timeout_add_seconds_full:
3749 * @priority: the priority of the timeout source. Typically this will be in
3750 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3751 * @interval: the time between calls to the function, in seconds
3752 * @function: function to call
3753 * @data: data to pass to @function
3754 * @notify: function to call when the timeout is removed, or %NULL
3756 * Sets a function to be called at regular intervals, with @priority.
3757 * The function is called repeatedly until it returns %FALSE, at which
3758 * point the timeout is automatically destroyed and the function will
3759 * not be called again.
3761 * Unlike g_timeout_add(), this function operates at whole second granularity.
3762 * The initial starting point of the timer is determined by the implementation
3763 * and the implementation is expected to group multiple timers together so that
3764 * they fire all at the same time.
3765 * To allow this grouping, the @interval to the first timer is rounded
3766 * and can deviate up to one second from the specified interval.
3767 * Subsequent timer iterations will generally run at the specified interval.
3769 * Note that timeout functions may be delayed, due to the processing of other
3770 * event sources. Thus they should not be relied on for precise timing.
3771 * After each call to the timeout function, the time of the next
3772 * timeout is recalculated based on the current time and the given @interval
3774 * If you want timing more precise than whole seconds, use g_timeout_add()
3777 * The grouping of timers to fire at the same time results in a more power
3778 * and CPU efficient behavior so if your timer is in multiples of seconds
3779 * and you don't require the first timer exactly one second from now, the
3780 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
3782 * Return value: the ID (greater than 0) of the event source.
3787 g_timeout_add_seconds_full (gint priority,
3789 GSourceFunc function,
3791 GDestroyNotify notify)
3796 g_return_val_if_fail (function != NULL, 0);
3798 source = g_timeout_source_new_seconds (interval);
3800 if (priority != G_PRIORITY_DEFAULT)
3801 g_source_set_priority (source, priority);
3803 g_source_set_callback (source, function, data, notify);
3804 id = g_source_attach (source, NULL);
3805 g_source_unref (source);
3811 * g_timeout_add_seconds:
3812 * @interval: the time between calls to the function, in seconds
3813 * @function: function to call
3814 * @data: data to pass to @function
3816 * Sets a function to be called at regular intervals with the default
3817 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
3818 * it returns %FALSE, at which point the timeout is automatically destroyed
3819 * and the function will not be called again.
3821 * See g_timeout_add_seconds_full() for the differences between
3822 * g_timeout_add() and g_timeout_add_seconds().
3824 * Return value: the ID (greater than 0) of the event source.
3829 g_timeout_add_seconds (guint interval,
3830 GSourceFunc function,
3833 g_return_val_if_fail (function != NULL, 0);
3835 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
3838 /* Child watch functions */
3843 g_child_watch_prepare (GSource *source,
3852 g_child_watch_check (GSource *source)
3854 GChildWatchSource *child_watch_source;
3855 gboolean child_exited;
3857 child_watch_source = (GChildWatchSource *) source;
3859 child_exited = child_watch_source->poll.revents & G_IO_IN;
3866 * Note: We do _not_ check for the special value of STILL_ACTIVE
3867 * since we know that the process has exited and doing so runs into
3868 * problems if the child process "happens to return STILL_ACTIVE(259)"
3869 * as Microsoft's Platform SDK puts it.
3871 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
3873 gchar *emsg = g_win32_error_message (GetLastError ());
3874 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
3877 child_watch_source->child_status = -1;
3880 child_watch_source->child_status = child_status;
3883 return child_exited;
3886 #else /* G_OS_WIN32 */
3889 check_for_child_exited (GSource *source)
3891 GChildWatchSource *child_watch_source;
3894 /* protect against another SIGCHLD in the middle of this call */
3895 count = child_watch_count;
3897 child_watch_source = (GChildWatchSource *) source;
3899 if (child_watch_source->child_exited)
3902 if (child_watch_source->count < count)
3906 if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
3908 child_watch_source->child_status = child_status;
3909 child_watch_source->child_exited = TRUE;
3911 child_watch_source->count = count;
3914 return child_watch_source->child_exited;
3918 g_child_watch_prepare (GSource *source,
3923 return check_for_child_exited (source);
3928 g_child_watch_check (GSource *source)
3930 return check_for_child_exited (source);
3933 #endif /* G_OS_WIN32 */
3936 g_child_watch_dispatch (GSource *source,
3937 GSourceFunc callback,
3940 GChildWatchSource *child_watch_source;
3941 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
3943 child_watch_source = (GChildWatchSource *) source;
3947 g_warning ("Child watch source dispatched without callback\n"
3948 "You must call g_source_set_callback().");
3952 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
3954 /* We never keep a child watch source around as the child is gone */
3961 g_child_watch_signal_handler (int signum)
3963 child_watch_count ++;
3965 if (child_watch_init_state == CHILD_WATCH_INITIALIZED_THREADED)
3967 write (child_watch_wake_up_pipe[1], "B", 1);
3971 /* We count on the signal interrupting the poll in the same thread.
3977 g_child_watch_source_init_single (void)
3979 struct sigaction action;
3981 g_assert (! g_thread_supported());
3982 g_assert (child_watch_init_state == CHILD_WATCH_UNINITIALIZED);
3984 child_watch_init_state = CHILD_WATCH_INITIALIZED_SINGLE;
3986 action.sa_handler = g_child_watch_signal_handler;
3987 sigemptyset (&action.sa_mask);
3988 action.sa_flags = SA_NOCLDSTOP;
3989 sigaction (SIGCHLD, &action, NULL);
3993 child_watch_helper_thread (gpointer data)
4000 read (child_watch_wake_up_pipe[0], b, 20);
4002 /* We were woken up. Wake up all other contexts in all other threads */
4003 G_LOCK (main_context_list);
4004 for (list = main_context_list; list; list = list->next)
4006 GMainContext *context;
4008 context = list->data;
4009 if (g_atomic_int_get (&context->ref_count) > 0)
4010 /* Due to racing conditions we can find ref_count == 0, in
4011 * that case, however, the context is still not destroyed
4012 * and no poll can be active, otherwise the ref_count
4014 g_main_context_wakeup (context);
4016 G_UNLOCK (main_context_list);
4023 g_child_watch_source_init_multi_threaded (void)
4025 GError *error = NULL;
4026 struct sigaction action;
4028 g_assert (g_thread_supported());
4030 if (pipe (child_watch_wake_up_pipe) < 0)
4031 g_error ("Cannot create wake up pipe: %s\n", g_strerror (errno));
4032 fcntl (child_watch_wake_up_pipe[1], F_SETFL, O_NONBLOCK | fcntl (child_watch_wake_up_pipe[1], F_GETFL));
4034 /* We create a helper thread that polls on the wakeup pipe indefinitely */
4035 /* FIXME: Think this through for races */
4036 if (g_thread_create (child_watch_helper_thread, NULL, FALSE, &error) == NULL)
4037 g_error ("Cannot create a thread to monitor child exit status: %s\n", error->message);
4038 child_watch_init_state = CHILD_WATCH_INITIALIZED_THREADED;
4040 action.sa_handler = g_child_watch_signal_handler;
4041 sigemptyset (&action.sa_mask);
4042 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4043 sigaction (SIGCHLD, &action, NULL);
4047 g_child_watch_source_init_promote_single_to_threaded (void)
4049 g_child_watch_source_init_multi_threaded ();
4053 g_child_watch_source_init (void)
4055 if (g_thread_supported())
4057 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
4058 g_child_watch_source_init_multi_threaded ();
4059 else if (child_watch_init_state == CHILD_WATCH_INITIALIZED_SINGLE)
4060 g_child_watch_source_init_promote_single_to_threaded ();
4064 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
4065 g_child_watch_source_init_single ();
4069 #endif /* !G_OS_WIN32 */
4072 * g_child_watch_source_new:
4073 * @pid: process to watch. On POSIX the pid of a child process. On
4074 * Windows a handle for a process (which doesn't have to be a child).
4076 * Creates a new child_watch source.
4078 * The source will not initially be associated with any #GMainContext
4079 * and must be added to one with g_source_attach() before it will be
4082 * Note that child watch sources can only be used in conjunction with
4083 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4086 * Note that on platforms where #GPid must be explicitly closed
4087 * (see g_spawn_close_pid()) @pid must not be closed while the
4088 * source is still active. Typically, you will want to call
4089 * g_spawn_close_pid() in the callback function for the source.
4091 * Note further that using g_child_watch_source_new() is not
4092 * compatible with calling <literal>waitpid(-1)</literal> in
4093 * the application. Calling waitpid() for individual pids will
4096 * Return value: the newly-created child watch source
4101 g_child_watch_source_new (GPid pid)
4103 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4104 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4107 child_watch_source->poll.fd = (gintptr) pid;
4108 child_watch_source->poll.events = G_IO_IN;
4110 g_source_add_poll (source, &child_watch_source->poll);
4111 #else /* G_OS_WIN32 */
4112 g_child_watch_source_init ();
4113 #endif /* G_OS_WIN32 */
4115 child_watch_source->pid = pid;
4121 * g_child_watch_add_full:
4122 * @priority: the priority of the idle source. Typically this will be in the
4123 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4124 * @pid: process to watch. On POSIX the pid of a child process. On
4125 * Windows a handle for a process (which doesn't have to be a child).
4126 * @function: function to call
4127 * @data: data to pass to @function
4128 * @notify: function to call when the idle is removed, or %NULL
4130 * Sets a function to be called when the child indicated by @pid
4131 * exits, at the priority @priority.
4133 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4134 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4135 * the spawn function for the child watching to work.
4137 * Note that on platforms where #GPid must be explicitly closed
4138 * (see g_spawn_close_pid()) @pid must not be closed while the
4139 * source is still active. Typically, you will want to call
4140 * g_spawn_close_pid() in the callback function for the source.
4142 * GLib supports only a single callback per process id.
4144 * Return value: the ID (greater than 0) of the event source.
4149 g_child_watch_add_full (gint priority,
4151 GChildWatchFunc function,
4153 GDestroyNotify notify)
4158 g_return_val_if_fail (function != NULL, 0);
4160 source = g_child_watch_source_new (pid);
4162 if (priority != G_PRIORITY_DEFAULT)
4163 g_source_set_priority (source, priority);
4165 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4166 id = g_source_attach (source, NULL);
4167 g_source_unref (source);
4173 * g_child_watch_add:
4174 * @pid: process id to watch. On POSIX the pid of a child process. On
4175 * Windows a handle for a process (which doesn't have to be a child).
4176 * @function: function to call
4177 * @data: data to pass to @function
4179 * Sets a function to be called when the child indicated by @pid
4180 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4182 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4183 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4184 * the spawn function for the child watching to work.
4186 * Note that on platforms where #GPid must be explicitly closed
4187 * (see g_spawn_close_pid()) @pid must not be closed while the
4188 * source is still active. Typically, you will want to call
4189 * g_spawn_close_pid() in the callback function for the source.
4191 * GLib supports only a single callback per process id.
4193 * Return value: the ID (greater than 0) of the event source.
4198 g_child_watch_add (GPid pid,
4199 GChildWatchFunc function,
4202 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4206 /* Idle functions */
4209 g_idle_prepare (GSource *source,
4218 g_idle_check (GSource *source)
4224 g_idle_dispatch (GSource *source,
4225 GSourceFunc callback,
4230 g_warning ("Idle source dispatched without callback\n"
4231 "You must call g_source_set_callback().");
4235 return callback (user_data);
4239 * g_idle_source_new:
4241 * Creates a new idle source.
4243 * The source will not initially be associated with any #GMainContext
4244 * and must be added to one with g_source_attach() before it will be
4245 * executed. Note that the default priority for idle sources is
4246 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4247 * have a default priority of %G_PRIORITY_DEFAULT.
4249 * Return value: the newly-created idle source
4252 g_idle_source_new (void)
4256 source = g_source_new (&g_idle_funcs, sizeof (GSource));
4257 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4264 * @priority: the priority of the idle source. Typically this will be in the
4265 * range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4266 * @function: function to call
4267 * @data: data to pass to @function
4268 * @notify: function to call when the idle is removed, or %NULL
4270 * Adds a function to be called whenever there are no higher priority
4271 * events pending. If the function returns %FALSE it is automatically
4272 * removed from the list of event sources and will not be called again.
4274 * Return value: the ID (greater than 0) of the event source.
4277 g_idle_add_full (gint priority,
4278 GSourceFunc function,
4280 GDestroyNotify notify)
4285 g_return_val_if_fail (function != NULL, 0);
4287 source = g_idle_source_new ();
4289 if (priority != G_PRIORITY_DEFAULT_IDLE)
4290 g_source_set_priority (source, priority);
4292 g_source_set_callback (source, function, data, notify);
4293 id = g_source_attach (source, NULL);
4294 g_source_unref (source);
4301 * @function: function to call
4302 * @data: data to pass to @function.
4304 * Adds a function to be called whenever there are no higher priority
4305 * events pending to the default main loop. The function is given the
4306 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4307 * returns %FALSE it is automatically removed from the list of event
4308 * sources and will not be called again.
4310 * Return value: the ID (greater than 0) of the event source.
4313 g_idle_add (GSourceFunc function,
4316 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4320 * g_idle_remove_by_data:
4321 * @data: the data for the idle source's callback.
4323 * Removes the idle function with the given data.
4325 * Return value: %TRUE if an idle source was found and removed.
4328 g_idle_remove_by_data (gpointer data)
4330 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4333 #define __G_MAIN_C__
4334 #include "galiasdef.c"