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 get poll() debugging info */
37 /* #define G_MAIN_POLL_DEBUG */
40 #include "gthreadinit.h"
42 #include <sys/types.h>
44 #ifdef HAVE_SYS_TIME_H
46 #endif /* HAVE_SYS_TIME_H */
47 #ifdef GLIB_HAVE_SYS_POLL_H
48 # include <sys/poll.h>
49 # undef events /* AIX 4.1.5 & 4.3.2 define this for SVR3,4 compatibility */
50 # undef revents /* AIX 4.1.5 & 4.3.2 define this for SVR3,4 compatibility */
52 /* The poll() emulation on OS/X doesn't handle fds=NULL, nfds=0,
53 * so we prefer our own poll emulation.
59 #endif /* GLIB_HAVE_SYS_POLL_H */
62 #endif /* HAVE_UNISTD_H */
68 #endif /* G_OS_WIN32 */
71 #include <net/socket.h>
72 #endif /* G_OS_BEOS */
80 typedef struct _GTimeoutSource GTimeoutSource;
81 typedef struct _GChildWatchSource GChildWatchSource;
82 typedef struct _GPollRec GPollRec;
83 typedef struct _GSourceCallback GSourceCallback;
87 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
88 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
91 #ifdef G_THREADS_ENABLED
92 typedef struct _GMainWaiter GMainWaiter;
103 #ifdef G_THREADS_ENABLED
104 /* The following lock is used for both the list of sources
105 * and the list of poll records
116 GPtrArray *pending_dispatches;
117 gint timeout; /* Timeout for current iteration */
120 GSource *source_list;
121 gint in_check_or_prepare;
123 GPollRec *poll_records;
124 GPollRec *poll_free_list;
125 GMemChunk *poll_chunk;
126 guint n_poll_records;
127 GPollFD *cached_poll_array;
128 guint cached_poll_array_size;
130 #ifdef G_THREADS_ENABLED
132 /* this pipe is used to wake up the main loop when a source is added.
134 gint wake_up_pipe[2];
135 #else /* G_OS_WIN32 */
136 HANDLE wake_up_semaphore;
137 #endif /* G_OS_WIN32 */
140 gboolean poll_waiting;
142 /* Flag indicating whether the set of fd's changed during a poll */
143 gboolean poll_changed;
144 #endif /* G_THREADS_ENABLED */
148 GTimeVal current_time;
149 gboolean time_is_current;
152 struct _GSourceCallback
157 GDestroyNotify notify;
162 GMainContext *context;
167 struct _GTimeoutSource
174 struct _GChildWatchSource
181 #else /* G_OS_WIN32 */
183 gboolean child_exited;
184 #endif /* G_OS_WIN32 */
194 #ifdef G_THREADS_ENABLED
195 #define LOCK_CONTEXT(context) g_static_mutex_lock (&context->mutex)
196 #define UNLOCK_CONTEXT(context) g_static_mutex_unlock (&context->mutex)
197 #define G_THREAD_SELF g_thread_self ()
199 #define LOCK_CONTEXT(context) (void)0
200 #define UNLOCK_CONTEXT(context) (void)0
201 #define G_THREAD_SELF NULL
204 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
206 #define SOURCE_UNREF(source, context) \
208 if ((source)->ref_count > 1) \
209 (source)->ref_count--; \
211 g_source_unref_internal ((source), (context), TRUE); \
215 /* Forward declarations */
217 static void g_source_unref_internal (GSource *source,
218 GMainContext *context,
220 static void g_source_destroy_internal (GSource *source,
221 GMainContext *context,
223 static void g_main_context_poll (GMainContext *context,
228 static void g_main_context_add_poll_unlocked (GMainContext *context,
231 static void g_main_context_remove_poll_unlocked (GMainContext *context,
233 static void g_main_context_wakeup_unlocked (GMainContext *context);
235 static gboolean g_timeout_prepare (GSource *source,
237 static gboolean g_timeout_check (GSource *source);
238 static gboolean g_timeout_dispatch (GSource *source,
239 GSourceFunc callback,
241 static gboolean g_child_watch_prepare (GSource *source,
243 static gboolean g_child_watch_check (GSource *source);
244 static gboolean g_child_watch_dispatch (GSource *source,
245 GSourceFunc callback,
247 static gboolean g_idle_prepare (GSource *source,
249 static gboolean g_idle_check (GSource *source);
250 static gboolean g_idle_dispatch (GSource *source,
251 GSourceFunc callback,
254 G_LOCK_DEFINE_STATIC (main_loop);
255 static GMainContext *default_main_context;
256 static GSList *main_contexts_without_pipe = NULL;
259 /* Child status monitoring code */
261 CHILD_WATCH_UNINITIALIZED,
262 CHILD_WATCH_INITIALIZED_SINGLE,
263 CHILD_WATCH_INITIALIZED_THREADED
265 static gint child_watch_init_state = CHILD_WATCH_UNINITIALIZED;
266 static gint child_watch_count = 0;
267 static gint child_watch_wake_up_pipe[2] = {0, 0};
268 #endif /* !G_OS_WIN32 */
269 G_LOCK_DEFINE_STATIC (main_context_list);
270 static GSList *main_context_list = NULL;
272 #if defined(G_PLATFORM_WIN32) && defined(__GNUC__)
273 __declspec(dllexport)
275 GSourceFuncs g_timeout_funcs =
283 GSourceFuncs g_child_watch_funcs =
285 g_child_watch_prepare,
287 g_child_watch_dispatch,
291 #if defined(G_PLATFORM_WIN32) && defined(__GNUC__)
292 __declspec(dllexport)
294 GSourceFuncs g_idle_funcs =
303 /* SunOS has poll, but doesn't provide a prototype. */
304 # if defined (sun) && !defined (__SVR4)
305 extern gint poll (GPollFD *ufds, guint nfsd, gint timeout);
307 #else /* !HAVE_POLL */
312 g_poll (GPollFD *fds,
316 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
317 gboolean poll_msgs = FALSE;
324 for (f = fds; f < &fds[nfds]; ++f)
327 if (f->fd == G_WIN32_MSG_HANDLE)
329 else if (nhandles == MAXIMUM_WAIT_OBJECTS)
331 g_warning (G_STRLOC ": Too many handles to wait for!\n");
336 #ifdef G_MAIN_POLL_DEBUG
337 g_print ("g_poll: waiting for %#x\n", f->fd);
339 handles[nhandles++] = (HANDLE) f->fd;
348 /* Waiting for messages, and maybe events
349 * -> First PeekMessage
351 #ifdef G_MAIN_POLL_DEBUG
352 g_print ("PeekMessage\n");
354 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
355 ready = WAIT_OBJECT_0 + nhandles;
360 /* Waiting just for messages */
361 if (timeout == INFINITE)
366 #ifdef G_MAIN_POLL_DEBUG
367 g_print ("WaitMessage\n");
371 gchar *emsg = g_win32_error_message (GetLastError ());
372 g_warning (G_STRLOC ": WaitMessage() failed: %s", emsg);
375 ready = WAIT_OBJECT_0 + nhandles;
377 else if (timeout == 0)
379 /* Waiting just for messages, zero timeout.
380 * If we got here, there was no message
382 ready = WAIT_TIMEOUT;
386 /* Waiting just for messages, some timeout
387 * -> Set a timer, wait for message,
388 * kill timer, use PeekMessage
390 timer = SetTimer (NULL, 0, timeout, NULL);
393 gchar *emsg = g_win32_error_message (GetLastError ());
394 g_warning (G_STRLOC ": SetTimer() failed: %s", emsg);
396 ready = WAIT_TIMEOUT;
400 #ifdef G_MAIN_POLL_DEBUG
401 g_print ("WaitMessage\n");
404 KillTimer (NULL, timer);
405 #ifdef G_MAIN_POLL_DEBUG
406 g_print ("PeekMessage\n");
408 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE)
409 && msg.message != WM_TIMER)
410 ready = WAIT_OBJECT_0;
412 ready = WAIT_TIMEOUT;
418 /* Wait for either message or event
419 * -> Use MsgWaitForMultipleObjects
421 #ifdef G_MAIN_POLL_DEBUG
422 g_print ("MsgWaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
424 ready = MsgWaitForMultipleObjects (nhandles, handles, FALSE,
425 timeout, QS_ALLINPUT);
427 if (ready == WAIT_FAILED)
429 gchar *emsg = g_win32_error_message (GetLastError ());
430 g_warning (G_STRLOC ": MsgWaitForMultipleObjects() failed: %s", emsg);
436 else if (nhandles == 0)
438 /* Wait for nothing (huh?) */
443 /* Wait for just events
444 * -> Use WaitForMultipleObjects
446 #ifdef G_MAIN_POLL_DEBUG
447 g_print ("WaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
449 ready = WaitForMultipleObjects (nhandles, handles, FALSE, timeout);
450 if (ready == WAIT_FAILED)
452 gchar *emsg = g_win32_error_message (GetLastError ());
453 g_warning (G_STRLOC ": WaitForMultipleObjects() failed: %s", emsg);
458 #ifdef G_MAIN_POLL_DEBUG
459 g_print ("wait returns %ld%s\n",
461 (ready == WAIT_FAILED ? " (WAIT_FAILED)" :
462 (ready == WAIT_TIMEOUT ? " (WAIT_TIMEOUT)" :
463 (poll_msgs && ready == WAIT_OBJECT_0 + nhandles ? " (msg)" : ""))));
465 for (f = fds; f < &fds[nfds]; ++f)
468 if (ready == WAIT_FAILED)
470 else if (ready == WAIT_TIMEOUT)
472 else if (poll_msgs && ready == WAIT_OBJECT_0 + nhandles)
474 for (f = fds; f < &fds[nfds]; ++f)
477 if (f->events & G_IO_IN)
478 if (f->fd == G_WIN32_MSG_HANDLE)
479 f->revents |= G_IO_IN;
482 #if 1 /* TEST_WITHOUT_THIS */
483 else if (ready >= WAIT_OBJECT_0 && ready < WAIT_OBJECT_0 + nhandles)
484 for (f = fds; f < &fds[nfds]; ++f)
486 if ((f->events & (G_IO_IN | G_IO_OUT))
487 && f->fd == (gint) handles[ready - WAIT_OBJECT_0])
489 if (f->events & G_IO_IN)
490 f->revents |= G_IO_IN;
492 f->revents |= G_IO_OUT;
493 #ifdef G_MAIN_POLL_DEBUG
494 g_print ("g_poll: got event %#x\n", f->fd);
497 ResetEvent ((HANDLE) f->fd);
506 #else /* !G_OS_WIN32 */
508 /* The following implementation of poll() comes from the GNU C Library.
509 * Copyright (C) 1994, 1996, 1997 Free Software Foundation, Inc.
512 #include <string.h> /* for bzero on BSD systems */
514 #ifdef HAVE_SYS_SELECT_H
515 #include <sys/select.h>
516 #endif /* HAVE_SYS_SELECT_H */
520 #endif /* G_OS_BEOS */
523 # define SELECT_MASK fd_set
524 #else /* !NO_FD_SET */
526 typedef long fd_mask;
529 # define SELECT_MASK void
531 # define SELECT_MASK int
532 # endif /* !_IBMR2 */
533 #endif /* !NO_FD_SET */
536 g_poll (GPollFD *fds,
541 SELECT_MASK rset, wset, xset;
550 for (f = fds; f < &fds[nfds]; ++f)
553 if (f->events & G_IO_IN)
554 FD_SET (f->fd, &rset);
555 if (f->events & G_IO_OUT)
556 FD_SET (f->fd, &wset);
557 if (f->events & G_IO_PRI)
558 FD_SET (f->fd, &xset);
559 if (f->fd > maxfd && (f->events & (G_IO_IN|G_IO_OUT|G_IO_PRI)))
563 tv.tv_sec = timeout / 1000;
564 tv.tv_usec = (timeout % 1000) * 1000;
566 ready = select (maxfd + 1, &rset, &wset, &xset,
567 timeout == -1 ? NULL : &tv);
569 for (f = fds; f < &fds[nfds]; ++f)
574 if (FD_ISSET (f->fd, &rset))
575 f->revents |= G_IO_IN;
576 if (FD_ISSET (f->fd, &wset))
577 f->revents |= G_IO_OUT;
578 if (FD_ISSET (f->fd, &xset))
579 f->revents |= G_IO_PRI;
586 #endif /* !G_OS_WIN32 */
588 #endif /* !HAVE_POLL */
591 * g_main_context_ref:
592 * @context: a #GMainContext
594 * Increases the reference count on a #GMainContext object by one.
597 g_main_context_ref (GMainContext *context)
599 g_return_if_fail (context != NULL);
600 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
602 g_atomic_int_inc (&context->ref_count);
605 /* If DISABLE_MEM_POOLS is defined, then freeing the
606 * mem chunk won't free the records, so we have to
607 * do it manually. The conditionalization here is
608 * an optimization; g_mem_chunk_free() is a no-op
609 * when DISABLE_MEM_POOLS is set.
611 #ifdef DISABLE_MEM_POOLS
613 poll_rec_list_free (GMainContext *context,
618 GPollRec *tmp_rec = list;
620 g_chunk_free (tmp_rec, context->poll_chunk);
623 #endif /* DISABLE_MEM_POOLS */
626 * g_main_context_unref:
627 * @context: a #GMainContext
629 * Decreases the reference count on a #GMainContext object by one. If
630 * the result is zero, free the context and free all associated memory.
633 g_main_context_unref (GMainContext *context)
636 g_return_if_fail (context != NULL);
637 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
639 if (!g_atomic_int_dec_and_test (&context->ref_count))
642 G_LOCK (main_context_list);
643 main_context_list = g_slist_remove (main_context_list, context);
644 G_UNLOCK (main_context_list);
646 source = context->source_list;
649 GSource *next = source->next;
650 g_source_destroy_internal (source, context, TRUE);
654 #ifdef G_THREADS_ENABLED
655 g_static_mutex_free (&context->mutex);
658 g_ptr_array_free (context->pending_dispatches, TRUE);
659 g_free (context->cached_poll_array);
661 #ifdef DISABLE_MEM_POLLS
662 poll_rec_list_free (context, context->poll_records);
663 poll_rec_list_free (context, context->poll_free_list);
664 #endif /* DISABLE_MEM_POOLS */
666 if (context->poll_chunk)
667 g_mem_chunk_destroy (context->poll_chunk);
669 #ifdef G_THREADS_ENABLED
670 if (g_thread_supported())
673 close (context->wake_up_pipe[0]);
674 close (context->wake_up_pipe[1]);
676 CloseHandle (context->wake_up_semaphore);
680 main_contexts_without_pipe = g_slist_remove (main_contexts_without_pipe,
687 #ifdef G_THREADS_ENABLED
689 g_main_context_init_pipe (GMainContext *context)
692 if (context->wake_up_pipe[0] != -1)
694 if (pipe (context->wake_up_pipe) < 0)
695 g_error ("Cannot create pipe main loop wake-up: %s\n",
698 context->wake_up_rec.fd = context->wake_up_pipe[0];
699 context->wake_up_rec.events = G_IO_IN;
701 if (context->wake_up_semaphore != NULL)
703 context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
704 if (context->wake_up_semaphore == NULL)
705 g_error ("Cannot create wake-up semaphore: %s",
706 g_win32_error_message (GetLastError ()));
707 context->wake_up_rec.fd = (gint) context->wake_up_semaphore;
708 context->wake_up_rec.events = G_IO_IN;
709 # ifdef G_MAIN_POLL_DEBUG
710 g_print ("wake-up semaphore: %#x\n", (guint) context->wake_up_semaphore);
713 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
717 _g_main_thread_init ()
719 GSList *curr = main_contexts_without_pipe;
722 g_main_context_init_pipe ((GMainContext *)curr->data);
725 g_slist_free (main_contexts_without_pipe);
726 main_contexts_without_pipe = NULL;
728 #endif /* G_THREADS_ENABLED */
731 * g_main_context_new:
733 * Creates a new #GMainContext strcuture
735 * Return value: the new #GMainContext
738 g_main_context_new ()
740 GMainContext *context = g_new0 (GMainContext, 1);
742 #ifdef G_THREADS_ENABLED
743 g_static_mutex_init (&context->mutex);
745 context->owner = NULL;
746 context->waiters = NULL;
749 context->wake_up_pipe[0] = -1;
750 context->wake_up_pipe[1] = -1;
752 context->wake_up_semaphore = NULL;
756 context->ref_count = 1;
758 context->next_id = 1;
760 context->source_list = NULL;
763 context->poll_func = (GPollFunc)poll;
765 context->poll_func = g_poll;
768 context->cached_poll_array = NULL;
769 context->cached_poll_array_size = 0;
771 context->pending_dispatches = g_ptr_array_new ();
773 context->time_is_current = FALSE;
775 #ifdef G_THREADS_ENABLED
776 if (g_thread_supported ())
777 g_main_context_init_pipe (context);
779 main_contexts_without_pipe = g_slist_prepend (main_contexts_without_pipe,
783 G_LOCK (main_context_list);
784 main_context_list = g_slist_append (main_context_list, context);
785 G_UNLOCK (main_context_list);
791 * g_main_context_default:
793 * Returns the default main context. This is the main context used
794 * for main loop functions when a main loop is not explicitly
797 * Return value: the default main context.
800 g_main_context_default (void)
806 if (!default_main_context)
807 default_main_context = g_main_context_new ();
809 G_UNLOCK (main_loop);
811 return default_main_context;
814 /* Hooks for adding to the main loop */
818 * @source_funcs: structure containing functions that implement
819 * the sources behavior.
820 * @struct_size: size of the #GSource structure to create.
822 * Creates a new #GSource structure. The size is specified to
823 * allow creating structures derived from #GSource that contain
824 * additional data. The size passed in must be at least
825 * <literal>sizeof (GSource)</literal>.
827 * The source will not initially be associated with any #GMainContext
828 * and must be added to one with g_source_attach() before it will be
831 * Return value: the newly-created #GSource.
834 g_source_new (GSourceFuncs *source_funcs,
839 g_return_val_if_fail (source_funcs != NULL, NULL);
840 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
842 source = (GSource*) g_malloc0 (struct_size);
844 source->source_funcs = source_funcs;
845 source->ref_count = 1;
847 source->priority = G_PRIORITY_DEFAULT;
849 source->flags = G_HOOK_FLAG_ACTIVE;
851 /* NULL/0 initialization for all other fields */
856 /* Holds context's lock
859 g_source_list_add (GSource *source,
860 GMainContext *context)
862 GSource *tmp_source, *last_source;
865 tmp_source = context->source_list;
866 while (tmp_source && tmp_source->priority <= source->priority)
868 last_source = tmp_source;
869 tmp_source = tmp_source->next;
872 source->next = tmp_source;
874 tmp_source->prev = source;
876 source->prev = last_source;
878 last_source->next = source;
880 context->source_list = source;
883 /* Holds context's lock
886 g_source_list_remove (GSource *source,
887 GMainContext *context)
890 source->prev->next = source->next;
892 context->source_list = source->next;
895 source->next->prev = source->prev;
903 * @source: a #GSource
904 * @context: a #GMainContext (if %NULL, the default context will be used)
906 * Adds a #GSource to a @context so that it will be executed within
909 * Return value: the ID for the source within the #GMainContext
912 g_source_attach (GSource *source,
913 GMainContext *context)
918 g_return_val_if_fail (source->context == NULL, 0);
919 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
922 context = g_main_context_default ();
924 LOCK_CONTEXT (context);
926 source->context = context;
927 result = source->source_id = context->next_id++;
930 g_source_list_add (source, context);
932 tmp_list = source->poll_fds;
935 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
936 tmp_list = tmp_list->next;
939 #ifdef G_THREADS_ENABLED
940 /* Now wake up the main loop if it is waiting in the poll() */
941 g_main_context_wakeup_unlocked (context);
944 UNLOCK_CONTEXT (context);
950 g_source_destroy_internal (GSource *source,
951 GMainContext *context,
955 LOCK_CONTEXT (context);
957 if (!SOURCE_DESTROYED (source))
960 gpointer old_cb_data;
961 GSourceCallbackFuncs *old_cb_funcs;
963 source->flags &= ~G_HOOK_FLAG_ACTIVE;
965 old_cb_data = source->callback_data;
966 old_cb_funcs = source->callback_funcs;
968 source->callback_data = NULL;
969 source->callback_funcs = NULL;
973 UNLOCK_CONTEXT (context);
974 old_cb_funcs->unref (old_cb_data);
975 LOCK_CONTEXT (context);
978 tmp_list = source->poll_fds;
981 g_main_context_remove_poll_unlocked (context, tmp_list->data);
982 tmp_list = tmp_list->next;
985 g_source_unref_internal (source, context, TRUE);
989 UNLOCK_CONTEXT (context);
994 * @source: a #GSource
996 * Removes a source from its #GMainContext, if any, and mark it as
997 * destroyed. The source cannot be subsequently added to another
1001 g_source_destroy (GSource *source)
1003 GMainContext *context;
1005 g_return_if_fail (source != NULL);
1007 context = source->context;
1010 g_source_destroy_internal (source, context, FALSE);
1012 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1017 * @source: a #GSource
1019 * Returns the numeric ID for a particular source. The ID of a source
1020 * is unique within a particular main loop context. The reverse
1021 * mapping from ID to source is done by g_main_context_find_source_by_id().
1023 * Return value: the ID for the source
1026 g_source_get_id (GSource *source)
1030 g_return_val_if_fail (source != NULL, 0);
1031 g_return_val_if_fail (source->context != NULL, 0);
1033 LOCK_CONTEXT (source->context);
1034 result = source->source_id;
1035 UNLOCK_CONTEXT (source->context);
1041 * g_source_get_context:
1042 * @source: a #GSource
1044 * Gets the #GMainContext with which the source is associated.
1045 * Calling this function on a destroyed source is an error.
1047 * Return value: the #GMainContext with which the source is associated,
1048 * or %NULL if the context has not yet been added
1052 g_source_get_context (GSource *source)
1054 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1056 return source->context;
1060 * g_source_add_poll:
1061 * @source:a #GSource
1062 * @fd: a #GPollFD structure holding information about a file
1063 * descriptor to watch.
1065 * Adds a file descriptor to the set of file descriptors polled for
1066 * this source. This is usually combined with g_source_new() to add an
1067 * event source. The event source's check function will typically test
1068 * the @revents field in the #GPollFD struct and return %TRUE if events need
1072 g_source_add_poll (GSource *source,
1075 GMainContext *context;
1077 g_return_if_fail (source != NULL);
1078 g_return_if_fail (fd != NULL);
1079 g_return_if_fail (!SOURCE_DESTROYED (source));
1081 context = source->context;
1084 LOCK_CONTEXT (context);
1086 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1090 g_main_context_add_poll_unlocked (context, source->priority, fd);
1091 UNLOCK_CONTEXT (context);
1096 * g_source_remove_poll:
1097 * @source:a #GSource
1098 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1100 * Removes a file descriptor from the set of file descriptors polled for
1104 g_source_remove_poll (GSource *source,
1107 GMainContext *context;
1109 g_return_if_fail (source != NULL);
1110 g_return_if_fail (fd != NULL);
1111 g_return_if_fail (!SOURCE_DESTROYED (source));
1113 context = source->context;
1116 LOCK_CONTEXT (context);
1118 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1122 g_main_context_remove_poll_unlocked (context, fd);
1123 UNLOCK_CONTEXT (context);
1128 * g_source_set_callback_indirect:
1129 * @source: the source
1130 * @callback_data: pointer to callback data "object"
1131 * @callback_funcs: functions for reference counting @callback_data
1132 * and getting the callback and data
1134 * Sets the callback function storing the data as a refcounted callback
1135 * "object". This is used internally. Note that calling
1136 * g_source_set_callback_indirect() assumes
1137 * an initial reference count on @callback_data, and thus
1138 * @callback_funcs->unref will eventually be called once more
1139 * than @callback_funcs->ref.
1142 g_source_set_callback_indirect (GSource *source,
1143 gpointer callback_data,
1144 GSourceCallbackFuncs *callback_funcs)
1146 GMainContext *context;
1147 gpointer old_cb_data;
1148 GSourceCallbackFuncs *old_cb_funcs;
1150 g_return_if_fail (source != NULL);
1151 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1153 context = source->context;
1156 LOCK_CONTEXT (context);
1158 old_cb_data = source->callback_data;
1159 old_cb_funcs = source->callback_funcs;
1161 source->callback_data = callback_data;
1162 source->callback_funcs = callback_funcs;
1165 UNLOCK_CONTEXT (context);
1168 old_cb_funcs->unref (old_cb_data);
1172 g_source_callback_ref (gpointer cb_data)
1174 GSourceCallback *callback = cb_data;
1176 callback->ref_count++;
1181 g_source_callback_unref (gpointer cb_data)
1183 GSourceCallback *callback = cb_data;
1185 callback->ref_count--;
1186 if (callback->ref_count == 0)
1188 if (callback->notify)
1189 callback->notify (callback->data);
1195 g_source_callback_get (gpointer cb_data,
1200 GSourceCallback *callback = cb_data;
1202 *func = callback->func;
1203 *data = callback->data;
1206 static GSourceCallbackFuncs g_source_callback_funcs = {
1207 g_source_callback_ref,
1208 g_source_callback_unref,
1209 g_source_callback_get,
1213 * g_source_set_callback:
1214 * @source: the source
1215 * @func: a callback function
1216 * @data: the data to pass to callback function
1217 * @notify: a function to call when @data is no longer in use, or %NULL.
1219 * Sets the callback function for a source. The callback for a source is
1220 * called from the source's dispatch function.
1222 * The exact type of @func depends on the type of source; ie. you
1223 * should not count on @func being called with @data as its first
1226 * Typically, you won't use this function. Instead use functions specific
1227 * to the type of source you are using.
1230 g_source_set_callback (GSource *source,
1233 GDestroyNotify notify)
1235 GSourceCallback *new_callback;
1237 g_return_if_fail (source != NULL);
1239 new_callback = g_new (GSourceCallback, 1);
1241 new_callback->ref_count = 1;
1242 new_callback->func = func;
1243 new_callback->data = data;
1244 new_callback->notify = notify;
1246 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1250 * g_source_set_priority:
1251 * @source: a #GSource
1252 * @priority: the new priority.
1254 * Sets the priority of a source. While the main loop is being
1255 * run, a source will be dispatched if it is ready to be dispatched and no sources
1256 * at a higher (numerically smaller) priority are ready to be dispatched.
1259 g_source_set_priority (GSource *source,
1263 GMainContext *context;
1265 g_return_if_fail (source != NULL);
1267 context = source->context;
1270 LOCK_CONTEXT (context);
1272 source->priority = priority;
1276 source->next = NULL;
1277 source->prev = NULL;
1279 tmp_list = source->poll_fds;
1282 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1283 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1285 tmp_list = tmp_list->next;
1288 UNLOCK_CONTEXT (source->context);
1293 * g_source_get_priority:
1294 * @source: a #GSource
1296 * Gets the priority of a source.
1298 * Return value: the priority of the source
1301 g_source_get_priority (GSource *source)
1303 g_return_val_if_fail (source != NULL, 0);
1305 return source->priority;
1309 * g_source_set_can_recurse:
1310 * @source: a #GSource
1311 * @can_recurse: whether recursion is allowed for this source
1313 * Sets whether a source can be called recursively. If @can_recurse is
1314 * %TRUE, then while the source is being dispatched then this source
1315 * will be processed normally. Otherwise, all processing of this
1316 * source is blocked until the dispatch function returns.
1319 g_source_set_can_recurse (GSource *source,
1320 gboolean can_recurse)
1322 GMainContext *context;
1324 g_return_if_fail (source != NULL);
1326 context = source->context;
1329 LOCK_CONTEXT (context);
1332 source->flags |= G_SOURCE_CAN_RECURSE;
1334 source->flags &= ~G_SOURCE_CAN_RECURSE;
1337 UNLOCK_CONTEXT (context);
1341 * g_source_get_can_recurse:
1342 * @source: a #GSource
1344 * Checks whether a source is allowed to be called recursively.
1345 * see g_source_set_can_recurse().
1347 * Return value: whether recursion is allowed.
1350 g_source_get_can_recurse (GSource *source)
1352 g_return_val_if_fail (source != NULL, FALSE);
1354 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1359 * @source: a #GSource
1361 * Increases the reference count on a source by one.
1363 * Return value: @source
1366 g_source_ref (GSource *source)
1368 GMainContext *context;
1370 g_return_val_if_fail (source != NULL, NULL);
1372 context = source->context;
1375 LOCK_CONTEXT (context);
1377 source->ref_count++;
1380 UNLOCK_CONTEXT (context);
1385 /* g_source_unref() but possible to call within context lock
1388 g_source_unref_internal (GSource *source,
1389 GMainContext *context,
1392 gpointer old_cb_data = NULL;
1393 GSourceCallbackFuncs *old_cb_funcs = NULL;
1395 g_return_if_fail (source != NULL);
1397 if (!have_lock && context)
1398 LOCK_CONTEXT (context);
1400 source->ref_count--;
1401 if (source->ref_count == 0)
1403 old_cb_data = source->callback_data;
1404 old_cb_funcs = source->callback_funcs;
1406 source->callback_data = NULL;
1407 source->callback_funcs = NULL;
1409 if (context && !SOURCE_DESTROYED (source))
1411 g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1412 source->ref_count++;
1415 g_source_list_remove (source, context);
1417 if (source->source_funcs->finalize)
1418 source->source_funcs->finalize (source);
1420 g_slist_free (source->poll_fds);
1421 source->poll_fds = NULL;
1425 if (!have_lock && context)
1426 UNLOCK_CONTEXT (context);
1431 UNLOCK_CONTEXT (context);
1433 old_cb_funcs->unref (old_cb_data);
1436 LOCK_CONTEXT (context);
1442 * @source: a #GSource
1444 * Decreases the reference count of a source by one. If the
1445 * resulting reference count is zero the source and associated
1446 * memory will be destroyed.
1449 g_source_unref (GSource *source)
1451 g_return_if_fail (source != NULL);
1453 g_source_unref_internal (source, source->context, FALSE);
1457 * g_main_context_find_source_by_id:
1458 * @context: a #GMainContext (if %NULL, the default context will be used)
1459 * @source_id: the source ID, as returned by g_source_get_id()
1461 * Finds a #GSource given a pair of context and ID
1463 * Return value: the #GSource if found, otherwise, %NULL
1466 g_main_context_find_source_by_id (GMainContext *context,
1471 g_return_val_if_fail (source_id > 0, NULL);
1473 if (context == NULL)
1474 context = g_main_context_default ();
1476 LOCK_CONTEXT (context);
1478 source = context->source_list;
1481 if (!SOURCE_DESTROYED (source) &&
1482 source->source_id == source_id)
1484 source = source->next;
1487 UNLOCK_CONTEXT (context);
1493 * g_main_context_find_source_by_funcs_user_data:
1494 * @context: a #GMainContext (if %NULL, the default context will be used).
1495 * @funcs: the @source_funcs passed to g_source_new().
1496 * @user_data: the user data from the callback.
1498 * Finds a source with the given source functions and user data. If
1499 * multiple sources exist with the same source function and user data,
1500 * the first one found will be returned.
1502 * Return value: the source, if one was found, otherwise %NULL
1505 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1506 GSourceFuncs *funcs,
1511 g_return_val_if_fail (funcs != NULL, NULL);
1513 if (context == NULL)
1514 context = g_main_context_default ();
1516 LOCK_CONTEXT (context);
1518 source = context->source_list;
1521 if (!SOURCE_DESTROYED (source) &&
1522 source->source_funcs == funcs &&
1523 source->callback_funcs)
1525 GSourceFunc callback;
1526 gpointer callback_data;
1528 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1530 if (callback_data == user_data)
1533 source = source->next;
1536 UNLOCK_CONTEXT (context);
1542 * g_main_context_find_source_by_user_data:
1543 * @context: a #GMainContext
1544 * @user_data: the user_data for the callback.
1546 * Finds a source with the given user data for the callback. If
1547 * multiple sources exist with the same user data, the first
1548 * one found will be returned.
1550 * Return value: the source, if one was found, otherwise %NULL
1553 g_main_context_find_source_by_user_data (GMainContext *context,
1558 if (context == NULL)
1559 context = g_main_context_default ();
1561 LOCK_CONTEXT (context);
1563 source = context->source_list;
1566 if (!SOURCE_DESTROYED (source) &&
1567 source->callback_funcs)
1569 GSourceFunc callback;
1570 gpointer callback_data = NULL;
1572 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1574 if (callback_data == user_data)
1577 source = source->next;
1580 UNLOCK_CONTEXT (context);
1587 * @tag: the id of the source to remove.
1589 * Removes the source with the given id from the default main context. The id of
1590 * a #GSource is given by g_source_get_id(), or will be returned by the
1591 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1592 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1593 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1595 * See also g_source_destroy().
1597 * Return value: %TRUE if the source was found and removed.
1600 g_source_remove (guint tag)
1604 g_return_val_if_fail (tag > 0, FALSE);
1606 source = g_main_context_find_source_by_id (NULL, tag);
1608 g_source_destroy (source);
1610 return source != NULL;
1614 * g_source_remove_by_user_data:
1615 * @user_data: the user_data for the callback.
1617 * Removes a source from the default main loop context given the user
1618 * data for the callback. If multiple sources exist with the same user
1619 * data, only one will be destroyed.
1621 * Return value: %TRUE if a source was found and removed.
1624 g_source_remove_by_user_data (gpointer user_data)
1628 source = g_main_context_find_source_by_user_data (NULL, user_data);
1631 g_source_destroy (source);
1639 * g_source_remove_by_funcs_user_data:
1640 * @funcs: The @source_funcs passed to g_source_new()
1641 * @user_data: the user data for the callback
1643 * Removes a source from the default main loop context given the
1644 * source functions and user data. If multiple sources exist with the
1645 * same source functions and user data, only one will be destroyed.
1647 * Return value: %TRUE if a source was found and removed.
1650 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1655 g_return_val_if_fail (funcs != NULL, FALSE);
1657 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1660 g_source_destroy (source);
1668 * g_get_current_time:
1669 * @result: #GTimeVal structure in which to store current time.
1671 * Equivalent to the UNIX gettimeofday() function, but portable.
1674 g_get_current_time (GTimeVal *result)
1679 g_return_if_fail (result != NULL);
1681 /*this is required on alpha, there the timeval structs are int's
1682 not longs and a cast only would fail horribly*/
1683 gettimeofday (&r, NULL);
1684 result->tv_sec = r.tv_sec;
1685 result->tv_usec = r.tv_usec;
1687 /* Avoid calling time() except for the first time.
1688 * GetTickCount() should be pretty fast and low-level?
1689 * I could also use ftime() but it seems unnecessarily overheady.
1691 static DWORD start_tick = 0;
1692 static time_t start_time;
1695 g_return_if_fail (result != NULL);
1697 if (start_tick == 0)
1699 start_tick = GetTickCount ();
1703 tick = GetTickCount ();
1705 result->tv_sec = (tick - start_tick) / 1000 + start_time;
1706 result->tv_usec = ((tick - start_tick) % 1000) * 1000;
1710 /* Running the main loop */
1713 get_depth_pointer (void)
1715 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
1716 gint *depth_pointer = g_static_private_get (&depth_private);
1719 depth_pointer = g_new (gint, 1);
1721 g_static_private_set (&depth_private, depth_pointer, g_free);
1724 return depth_pointer;
1730 * Return value: The main loop recursion level in the current thread
1732 * Returns the depth of the stack of calls to
1733 * g_main_context_dispatch() on any #GMainContext in the current thread.
1734 * That is, when called from the toplevel, it gives 0. When
1735 * called from within a callback from g_main_context_iteration()
1736 * (or g_main_loop_run(), etc.) it returns 1. When called from within
1737 * a callback to a recursive call to g_main_context_iterate(),
1738 * it returns 2. And so forth.
1740 * This function is useful in a situation like the following:
1741 * Imagine an extremely simple "garbage collected" system.
1744 * static GList *free_list;
1747 * allocate_memory (gsize size)
1749 * gpointer result = g_malloc (size);
1750 * free_list = g_list_prepend (free_list, result);
1755 * free_allocated_memory (void)
1758 * for (l = free_list; l; l = l->next);
1760 * g_list_free (free_list);
1768 * g_main_context_iteration (NULL, TRUE);
1769 * free_allocated_memory();
1773 * This works from an application, however, if you want to do the same
1774 * thing from a library, it gets more difficult, since you no longer
1775 * control the main loop. You might think you can simply use an idle
1776 * function to make the call to free_allocated_memory(), but that
1777 * doesn't work, since the idle function could be called from a
1778 * recursive callback. This can be fixed by using g_main_depth()
1782 * allocate_memory (gsize size)
1784 * FreeListBlock *block = g_new (FreeListBlock, 1);\
1785 * block->mem = g_malloc (size);
1786 * block->depth = g_main_depth ();
1787 * free_list = g_list_prepend (free_list, block);
1788 * return block->mem;
1792 * free_allocated_memory (void)
1796 * int depth = g_main_depth ();
1797 * for (l = free_list; l; );
1799 * GList *next = l->next;
1800 * FreeListBlock *block = l->data;
1801 * if (block->depth > depth)
1803 * g_free (block->mem);
1805 * free_list = g_list_delete_link (free_list, l);
1813 * There is a temptation to use g_main_depth() to solve
1814 * problems with reentrancy. For instance, while waiting for data
1815 * to be received from the network in response to a menu item,
1816 * the menu item might be selected again. It might seem that
1817 * one could make the menu item's callback return immediately
1818 * and do nothing if g_main_depth() returns a value greater than 1.
1819 * However, this should be avoided since the user then sees selecting
1820 * the menu item do nothing. Furthermore, you'll find yourself adding
1821 * these checks all over your code, since there are doubtless many,
1822 * many things that the user could do. Instead, you can use the
1823 * following techniques:
1828 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
1829 * the user from interacting with elements while the main
1830 * loop is recursing.
1835 * Avoid main loop recursion in situations where you can't handle
1836 * arbitrary callbacks. Instead, structure your code so that you
1837 * simply return to the main loop and then get called again when
1838 * there is more work to do.
1846 gint *depth = get_depth_pointer ();
1850 /* HOLDS: context's lock */
1852 g_main_dispatch (GMainContext *context)
1854 gint *depth = get_depth_pointer ();
1857 for (i = 0; i < context->pending_dispatches->len; i++)
1859 GSource *source = context->pending_dispatches->pdata[i];
1861 context->pending_dispatches->pdata[i] = NULL;
1864 source->flags &= ~G_SOURCE_READY;
1866 if (!SOURCE_DESTROYED (source))
1868 gboolean was_in_call;
1869 gpointer user_data = NULL;
1870 GSourceFunc callback = NULL;
1871 GSourceCallbackFuncs *cb_funcs;
1873 gboolean need_destroy;
1875 gboolean (*dispatch) (GSource *,
1879 dispatch = source->source_funcs->dispatch;
1880 cb_funcs = source->callback_funcs;
1881 cb_data = source->callback_data;
1884 cb_funcs->ref (cb_data);
1886 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
1887 source->flags |= G_HOOK_FLAG_IN_CALL;
1890 cb_funcs->get (cb_data, source, &callback, &user_data);
1892 UNLOCK_CONTEXT (context);
1895 need_destroy = ! dispatch (source,
1900 LOCK_CONTEXT (context);
1903 cb_funcs->unref (cb_data);
1906 source->flags &= ~G_HOOK_FLAG_IN_CALL;
1908 /* Note: this depends on the fact that we can't switch
1909 * sources from one main context to another
1911 if (need_destroy && !SOURCE_DESTROYED (source))
1913 g_assert (source->context == context);
1914 g_source_destroy_internal (source, context, TRUE);
1918 SOURCE_UNREF (source, context);
1921 g_ptr_array_set_size (context->pending_dispatches, 0);
1924 /* Holds context's lock */
1925 static inline GSource *
1926 next_valid_source (GMainContext *context,
1929 GSource *new_source = source ? source->next : context->source_list;
1933 if (!SOURCE_DESTROYED (new_source))
1935 new_source->ref_count++;
1939 new_source = new_source->next;
1943 SOURCE_UNREF (source, context);
1949 * g_main_context_acquire:
1950 * @context: a #GMainContext
1952 * Tries to become the owner of the specified context.
1953 * If some other context is the owner of the context,
1954 * returns %FALSE immediately. Ownership is properly
1955 * recursive: the owner can require ownership again
1956 * and will release ownership when g_main_context_release()
1957 * is called as many times as g_main_context_acquire().
1959 * You must be the owner of a context before you
1960 * can call g_main_context_prepare(), g_main_context_query(),
1961 * g_main_context_check(), g_main_context_dispatch().
1963 * Return value: %TRUE if the operation succeeded, and
1964 * this thread is now the owner of @context.
1967 g_main_context_acquire (GMainContext *context)
1969 #ifdef G_THREADS_ENABLED
1970 gboolean result = FALSE;
1971 GThread *self = G_THREAD_SELF;
1973 if (context == NULL)
1974 context = g_main_context_default ();
1976 LOCK_CONTEXT (context);
1978 if (!context->owner)
1980 context->owner = self;
1981 g_assert (context->owner_count == 0);
1984 if (context->owner == self)
1986 context->owner_count++;
1990 UNLOCK_CONTEXT (context);
1993 #else /* !G_THREADS_ENABLED */
1995 #endif /* G_THREADS_ENABLED */
1999 * g_main_context_release:
2000 * @context: a #GMainContext
2002 * Releases ownership of a context previously acquired by this thread
2003 * with g_main_context_acquire(). If the context was acquired multiple
2004 * times, the only release ownership when g_main_context_release()
2005 * is called as many times as it was acquired.
2008 g_main_context_release (GMainContext *context)
2010 #ifdef G_THREADS_ENABLED
2011 if (context == NULL)
2012 context = g_main_context_default ();
2014 LOCK_CONTEXT (context);
2016 context->owner_count--;
2017 if (context->owner_count == 0)
2019 context->owner = NULL;
2021 if (context->waiters)
2023 GMainWaiter *waiter = context->waiters->data;
2024 gboolean loop_internal_waiter =
2025 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
2026 context->waiters = g_slist_delete_link (context->waiters,
2028 if (!loop_internal_waiter)
2029 g_mutex_lock (waiter->mutex);
2031 g_cond_signal (waiter->cond);
2033 if (!loop_internal_waiter)
2034 g_mutex_unlock (waiter->mutex);
2038 UNLOCK_CONTEXT (context);
2039 #endif /* G_THREADS_ENABLED */
2043 * g_main_context_wait:
2044 * @context: a #GMainContext
2045 * @cond: a condition variable
2046 * @mutex: a mutex, currently held
2048 * Tries to become the owner of the specified context,
2049 * as with g_main_context_acquire(). But if another thread
2050 * is the owner, atomically drop @mutex and wait on @cond until
2051 * that owner releases ownership or until @cond is signaled, then
2052 * try again (once) to become the owner.
2054 * Return value: %TRUE if the operation succeeded, and
2055 * this thread is now the owner of @context.
2058 g_main_context_wait (GMainContext *context,
2062 #ifdef G_THREADS_ENABLED
2063 gboolean result = FALSE;
2064 GThread *self = G_THREAD_SELF;
2065 gboolean loop_internal_waiter;
2067 if (context == NULL)
2068 context = g_main_context_default ();
2070 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2072 if (!loop_internal_waiter)
2073 LOCK_CONTEXT (context);
2075 if (context->owner && context->owner != self)
2080 waiter.mutex = mutex;
2082 context->waiters = g_slist_append (context->waiters, &waiter);
2084 if (!loop_internal_waiter)
2085 UNLOCK_CONTEXT (context);
2086 g_cond_wait (cond, mutex);
2087 if (!loop_internal_waiter)
2088 LOCK_CONTEXT (context);
2090 context->waiters = g_slist_remove (context->waiters, &waiter);
2093 if (!context->owner)
2095 context->owner = self;
2096 g_assert (context->owner_count == 0);
2099 if (context->owner == self)
2101 context->owner_count++;
2105 if (!loop_internal_waiter)
2106 UNLOCK_CONTEXT (context);
2109 #else /* !G_THREADS_ENABLED */
2111 #endif /* G_THREADS_ENABLED */
2115 * g_main_context_prepare:
2116 * @context: a #GMainContext
2117 * @priority: location to store priority of highest priority
2118 * source already ready.
2120 * Prepares to poll sources within a main loop. The resulting information
2121 * for polling is determined by calling g_main_context_query ().
2123 * Return value: %TRUE if some source is ready to be dispatched
2127 g_main_context_prepare (GMainContext *context,
2132 gint current_priority = G_MAXINT;
2135 if (context == NULL)
2136 context = g_main_context_default ();
2138 LOCK_CONTEXT (context);
2140 context->time_is_current = FALSE;
2142 if (context->in_check_or_prepare)
2144 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2145 "prepare() member.");
2146 UNLOCK_CONTEXT (context);
2150 #ifdef G_THREADS_ENABLED
2151 if (context->poll_waiting)
2153 g_warning("g_main_context_prepare(): main loop already active in another thread");
2154 UNLOCK_CONTEXT (context);
2158 context->poll_waiting = TRUE;
2159 #endif /* G_THREADS_ENABLED */
2162 /* If recursing, finish up current dispatch, before starting over */
2163 if (context->pending_dispatches)
2166 g_main_dispatch (context, ¤t_time);
2168 UNLOCK_CONTEXT (context);
2173 /* If recursing, clear list of pending dispatches */
2175 for (i = 0; i < context->pending_dispatches->len; i++)
2177 if (context->pending_dispatches->pdata[i])
2178 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2180 g_ptr_array_set_size (context->pending_dispatches, 0);
2182 /* Prepare all sources */
2184 context->timeout = -1;
2186 source = next_valid_source (context, NULL);
2189 gint source_timeout = -1;
2191 if ((n_ready > 0) && (source->priority > current_priority))
2193 SOURCE_UNREF (source, context);
2196 if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
2199 if (!(source->flags & G_SOURCE_READY))
2202 gboolean (*prepare) (GSource *source,
2205 prepare = source->source_funcs->prepare;
2206 context->in_check_or_prepare++;
2207 UNLOCK_CONTEXT (context);
2209 result = (*prepare) (source, &source_timeout);
2211 LOCK_CONTEXT (context);
2212 context->in_check_or_prepare--;
2215 source->flags |= G_SOURCE_READY;
2218 if (source->flags & G_SOURCE_READY)
2221 current_priority = source->priority;
2222 context->timeout = 0;
2225 if (source_timeout >= 0)
2227 if (context->timeout < 0)
2228 context->timeout = source_timeout;
2230 context->timeout = MIN (context->timeout, source_timeout);
2234 source = next_valid_source (context, source);
2237 UNLOCK_CONTEXT (context);
2240 *priority = current_priority;
2242 return (n_ready > 0);
2246 * g_main_context_query:
2247 * @context: a #GMainContext
2248 * @max_priority: maximum priority source to check
2249 * @timeout_: location to store timeout to be used in polling
2250 * @fds: location to store #GPollFD records that need to be polled.
2251 * @n_fds: length of @fds.
2253 * Determines information necessary to poll this main loop.
2255 * Return value: the number of records actually stored in @fds,
2256 * or, if more than @n_fds records need to be stored, the number
2257 * of records that need to be stored.
2260 g_main_context_query (GMainContext *context,
2269 LOCK_CONTEXT (context);
2271 pollrec = context->poll_records;
2273 while (pollrec && max_priority >= pollrec->priority)
2275 if (pollrec->fd->events)
2279 fds[n_poll].fd = pollrec->fd->fd;
2280 /* In direct contradiction to the Unix98 spec, IRIX runs into
2281 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2282 * flags in the events field of the pollfd while it should
2283 * just ignoring them. So we mask them out here.
2285 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2286 fds[n_poll].revents = 0;
2291 pollrec = pollrec->next;
2294 #ifdef G_THREADS_ENABLED
2295 context->poll_changed = FALSE;
2300 *timeout = context->timeout;
2302 context->time_is_current = FALSE;
2305 UNLOCK_CONTEXT (context);
2311 * g_main_context_check:
2312 * @context: a #GMainContext
2313 * @max_priority: the maximum numerical priority of sources to check
2314 * @fds: array of #GPollFD's that was passed to the last call to
2315 * g_main_context_query()
2316 * @n_fds: return value of g_main_context_query()
2318 * Passes the results of polling back to the main loop.
2320 * Return value: %TRUE if some sources are ready to be dispatched.
2323 g_main_context_check (GMainContext *context,
2333 LOCK_CONTEXT (context);
2335 if (context->in_check_or_prepare)
2337 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2338 "prepare() member.");
2339 UNLOCK_CONTEXT (context);
2343 #ifdef G_THREADS_ENABLED
2344 if (!context->poll_waiting)
2348 read (context->wake_up_pipe[0], &a, 1);
2352 context->poll_waiting = FALSE;
2354 /* If the set of poll file descriptors changed, bail out
2355 * and let the main loop rerun
2357 if (context->poll_changed)
2359 UNLOCK_CONTEXT (context);
2362 #endif /* G_THREADS_ENABLED */
2364 pollrec = context->poll_records;
2368 if (pollrec->fd->events)
2370 pollrec->fd->revents = fds[i].revents;
2373 pollrec = pollrec->next;
2376 source = next_valid_source (context, NULL);
2379 if ((n_ready > 0) && (source->priority > max_priority))
2381 SOURCE_UNREF (source, context);
2384 if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
2387 if (!(source->flags & G_SOURCE_READY))
2390 gboolean (*check) (GSource *source);
2392 check = source->source_funcs->check;
2394 context->in_check_or_prepare++;
2395 UNLOCK_CONTEXT (context);
2397 result = (*check) (source);
2399 LOCK_CONTEXT (context);
2400 context->in_check_or_prepare--;
2403 source->flags |= G_SOURCE_READY;
2406 if (source->flags & G_SOURCE_READY)
2408 source->ref_count++;
2409 g_ptr_array_add (context->pending_dispatches, source);
2413 /* never dispatch sources with less priority than the first
2414 * one we choose to dispatch
2416 max_priority = source->priority;
2420 source = next_valid_source (context, source);
2423 UNLOCK_CONTEXT (context);
2429 * g_main_context_dispatch:
2430 * @context: a #GMainContext
2432 * Dispatches all pending sources.
2435 g_main_context_dispatch (GMainContext *context)
2437 LOCK_CONTEXT (context);
2439 if (context->pending_dispatches->len > 0)
2441 g_main_dispatch (context);
2444 UNLOCK_CONTEXT (context);
2447 /* HOLDS context lock */
2449 g_main_context_iterate (GMainContext *context,
2456 gboolean some_ready;
2457 gint nfds, allocated_nfds;
2458 GPollFD *fds = NULL;
2460 UNLOCK_CONTEXT (context);
2462 #ifdef G_THREADS_ENABLED
2463 if (!g_main_context_acquire (context))
2465 gboolean got_ownership;
2467 g_return_val_if_fail (g_thread_supported (), FALSE);
2472 LOCK_CONTEXT (context);
2475 context->cond = g_cond_new ();
2477 got_ownership = g_main_context_wait (context,
2479 g_static_mutex_get_mutex (&context->mutex));
2483 UNLOCK_CONTEXT (context);
2488 LOCK_CONTEXT (context);
2489 #endif /* G_THREADS_ENABLED */
2491 if (!context->cached_poll_array)
2493 context->cached_poll_array_size = context->n_poll_records;
2494 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2497 allocated_nfds = context->cached_poll_array_size;
2498 fds = context->cached_poll_array;
2500 UNLOCK_CONTEXT (context);
2502 g_main_context_prepare (context, &max_priority);
2504 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
2505 allocated_nfds)) > allocated_nfds)
2507 LOCK_CONTEXT (context);
2509 context->cached_poll_array_size = allocated_nfds = nfds;
2510 context->cached_poll_array = fds = g_new (GPollFD, nfds);
2511 UNLOCK_CONTEXT (context);
2517 g_main_context_poll (context, timeout, max_priority, fds, nfds);
2519 some_ready = g_main_context_check (context, max_priority, fds, nfds);
2522 g_main_context_dispatch (context);
2524 #ifdef G_THREADS_ENABLED
2525 g_main_context_release (context);
2526 #endif /* G_THREADS_ENABLED */
2528 LOCK_CONTEXT (context);
2534 * g_main_context_pending:
2535 * @context: a #GMainContext (if %NULL, the default context will be used)
2537 * Checks if any sources have pending events for the given context.
2539 * Return value: %TRUE if events are pending.
2542 g_main_context_pending (GMainContext *context)
2547 context = g_main_context_default();
2549 LOCK_CONTEXT (context);
2550 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
2551 UNLOCK_CONTEXT (context);
2557 * g_main_context_iteration:
2558 * @context: a #GMainContext (if %NULL, the default context will be used)
2559 * @may_block: whether the call may block.
2561 * Runs a single iteration for the given main loop. This involves
2562 * checking to see if any event sources are ready to be processed,
2563 * then if no events sources are ready and @may_block is %TRUE, waiting
2564 * for a source to become ready, then dispatching the highest priority
2565 * events sources that are ready. Note that even when @may_block is %TRUE,
2566 * it is still possible for g_main_context_iteration() to return
2567 * %FALSE, since the the wait may be interrupted for other
2568 * reasons than an event source becoming ready.
2570 * Return value: %TRUE if events were dispatched.
2573 g_main_context_iteration (GMainContext *context, gboolean may_block)
2578 context = g_main_context_default();
2580 LOCK_CONTEXT (context);
2581 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
2582 UNLOCK_CONTEXT (context);
2589 * @context: a #GMainContext (if %NULL, the default context will be used).
2590 * @is_running: set to %TRUE to indicate that the loop is running. This
2591 * is not very important since calling g_main_loop_run() will set this to
2594 * Creates a new #GMainLoop structure.
2596 * Return value: a new #GMainLoop.
2599 g_main_loop_new (GMainContext *context,
2600 gboolean is_running)
2605 context = g_main_context_default();
2607 g_main_context_ref (context);
2609 loop = g_new0 (GMainLoop, 1);
2610 loop->context = context;
2611 loop->is_running = is_running != FALSE;
2612 loop->ref_count = 1;
2619 * @loop: a #GMainLoop
2621 * Increases the reference count on a #GMainLoop object by one.
2623 * Return value: @loop
2626 g_main_loop_ref (GMainLoop *loop)
2628 g_return_val_if_fail (loop != NULL, NULL);
2629 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2631 g_atomic_int_inc (&loop->ref_count);
2637 * g_main_loop_unref:
2638 * @loop: a #GMainLoop
2640 * Decreases the reference count on a #GMainLoop object by one. If
2641 * the result is zero, free the loop and free all associated memory.
2644 g_main_loop_unref (GMainLoop *loop)
2646 g_return_if_fail (loop != NULL);
2647 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2649 if (!g_atomic_int_dec_and_test (&loop->ref_count))
2652 g_main_context_unref (loop->context);
2658 * @loop: a #GMainLoop
2660 * Runs a main loop until g_main_loop_quit() is called on the loop.
2661 * If this is called for the thread of the loop's #GMainContext,
2662 * it will process events from the loop, otherwise it will
2666 g_main_loop_run (GMainLoop *loop)
2668 GThread *self = G_THREAD_SELF;
2670 g_return_if_fail (loop != NULL);
2671 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2673 #ifdef G_THREADS_ENABLED
2674 if (!g_main_context_acquire (loop->context))
2676 gboolean got_ownership = FALSE;
2678 /* Another thread owns this context */
2679 if (!g_thread_supported ())
2681 g_warning ("g_main_loop_run() was called from second thread but "
2682 "g_thread_init() was never called.");
2686 LOCK_CONTEXT (loop->context);
2688 g_atomic_int_inc (&loop->ref_count);
2690 if (!loop->is_running)
2691 loop->is_running = TRUE;
2693 if (!loop->context->cond)
2694 loop->context->cond = g_cond_new ();
2696 while (loop->is_running && !got_ownership)
2697 got_ownership = g_main_context_wait (loop->context,
2698 loop->context->cond,
2699 g_static_mutex_get_mutex (&loop->context->mutex));
2701 if (!loop->is_running)
2703 UNLOCK_CONTEXT (loop->context);
2705 g_main_context_release (loop->context);
2706 g_main_loop_unref (loop);
2710 g_assert (got_ownership);
2713 LOCK_CONTEXT (loop->context);
2714 #endif /* G_THREADS_ENABLED */
2716 if (loop->context->in_check_or_prepare)
2718 g_warning ("g_main_loop_run(): called recursively from within a source's "
2719 "check() or prepare() member, iteration not possible.");
2723 g_atomic_int_inc (&loop->ref_count);
2724 loop->is_running = TRUE;
2725 while (loop->is_running)
2726 g_main_context_iterate (loop->context, TRUE, TRUE, self);
2728 UNLOCK_CONTEXT (loop->context);
2730 #ifdef G_THREADS_ENABLED
2731 g_main_context_release (loop->context);
2732 #endif /* G_THREADS_ENABLED */
2734 g_main_loop_unref (loop);
2739 * @loop: a #GMainLoop
2741 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
2742 * for the loop will return.
2745 g_main_loop_quit (GMainLoop *loop)
2747 g_return_if_fail (loop != NULL);
2748 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2750 LOCK_CONTEXT (loop->context);
2751 loop->is_running = FALSE;
2752 g_main_context_wakeup_unlocked (loop->context);
2754 #ifdef G_THREADS_ENABLED
2755 if (loop->context->cond)
2756 g_cond_broadcast (loop->context->cond);
2757 #endif /* G_THREADS_ENABLED */
2759 UNLOCK_CONTEXT (loop->context);
2763 * g_main_loop_is_running:
2764 * @loop: a #GMainLoop.
2766 * Checks to see if the main loop is currently being run via g_main_loop_run().
2768 * Return value: %TRUE if the mainloop is currently being run.
2771 g_main_loop_is_running (GMainLoop *loop)
2773 g_return_val_if_fail (loop != NULL, FALSE);
2774 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
2776 return loop->is_running;
2780 * g_main_loop_get_context:
2781 * @loop: a #GMainLoop.
2783 * Returns the #GMainContext of @loop.
2785 * Return value: the #GMainContext of @loop
2788 g_main_loop_get_context (GMainLoop *loop)
2790 g_return_val_if_fail (loop != NULL, NULL);
2791 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2793 return loop->context;
2796 /* HOLDS: context's lock */
2798 g_main_context_poll (GMainContext *context,
2804 #ifdef G_MAIN_POLL_DEBUG
2810 GPollFunc poll_func;
2812 if (n_fds || timeout != 0)
2814 #ifdef G_MAIN_POLL_DEBUG
2815 g_print ("g_main_poll(%d) timeout: %d\n", n_fds, timeout);
2816 poll_timer = g_timer_new ();
2819 LOCK_CONTEXT (context);
2821 poll_func = context->poll_func;
2823 UNLOCK_CONTEXT (context);
2824 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
2827 g_warning ("poll(2) failed due to: %s.",
2828 g_strerror (errno));
2830 /* If g_poll () returns -1, it has already called g_warning() */
2834 #ifdef G_MAIN_POLL_DEBUG
2835 LOCK_CONTEXT (context);
2837 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
2840 g_timer_elapsed (poll_timer, NULL));
2841 g_timer_destroy (poll_timer);
2842 pollrec = context->poll_records;
2846 if (pollrec->fd->events)
2850 g_print (" [%d:", fds[i].fd);
2851 if (fds[i].revents & G_IO_IN)
2853 if (fds[i].revents & G_IO_OUT)
2855 if (fds[i].revents & G_IO_PRI)
2857 if (fds[i].revents & G_IO_ERR)
2859 if (fds[i].revents & G_IO_HUP)
2861 if (fds[i].revents & G_IO_NVAL)
2867 pollrec = pollrec->next;
2871 UNLOCK_CONTEXT (context);
2873 } /* if (n_fds || timeout != 0) */
2877 * g_main_context_add_poll:
2878 * @context: a #GMainContext (or %NULL for the default context)
2879 * @fd: a #GPollFD structure holding information about a file
2880 * descriptor to watch.
2881 * @priority: the priority for this file descriptor which should be
2882 * the same as the priority used for g_source_attach() to ensure that the
2883 * file descriptor is polled whenever the results may be needed.
2885 * Adds a file descriptor to the set of file descriptors polled for
2886 * this context. This will very seldomly be used directly. Instead
2887 * a typical event source will use g_source_add_poll() instead.
2890 g_main_context_add_poll (GMainContext *context,
2895 context = g_main_context_default ();
2897 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
2898 g_return_if_fail (fd);
2900 LOCK_CONTEXT (context);
2901 g_main_context_add_poll_unlocked (context, priority, fd);
2902 UNLOCK_CONTEXT (context);
2905 /* HOLDS: main_loop_lock */
2907 g_main_context_add_poll_unlocked (GMainContext *context,
2911 GPollRec *lastrec, *pollrec, *newrec;
2913 if (!context->poll_chunk)
2914 context->poll_chunk = g_mem_chunk_create (GPollRec, 32, G_ALLOC_ONLY);
2916 if (context->poll_free_list)
2918 newrec = context->poll_free_list;
2919 context->poll_free_list = newrec->next;
2922 newrec = g_chunk_new (GPollRec, context->poll_chunk);
2924 /* This file descriptor may be checked before we ever poll */
2927 newrec->priority = priority;
2930 pollrec = context->poll_records;
2931 while (pollrec && priority >= pollrec->priority)
2934 pollrec = pollrec->next;
2938 lastrec->next = newrec;
2940 context->poll_records = newrec;
2942 newrec->next = pollrec;
2944 context->n_poll_records++;
2946 #ifdef G_THREADS_ENABLED
2947 context->poll_changed = TRUE;
2949 /* Now wake up the main loop if it is waiting in the poll() */
2950 g_main_context_wakeup_unlocked (context);
2955 * g_main_context_remove_poll:
2956 * @context:a #GMainContext
2957 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
2959 * Removes file descriptor from the set of file descriptors to be
2960 * polled for a particular context.
2963 g_main_context_remove_poll (GMainContext *context,
2967 context = g_main_context_default ();
2969 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
2970 g_return_if_fail (fd);
2972 LOCK_CONTEXT (context);
2973 g_main_context_remove_poll_unlocked (context, fd);
2974 UNLOCK_CONTEXT (context);
2978 g_main_context_remove_poll_unlocked (GMainContext *context,
2981 GPollRec *pollrec, *lastrec;
2984 pollrec = context->poll_records;
2988 if (pollrec->fd == fd)
2990 if (lastrec != NULL)
2991 lastrec->next = pollrec->next;
2993 context->poll_records = pollrec->next;
2995 #ifdef ENABLE_GC_FRIENDLY
2997 #endif /* ENABLE_GC_FRIENDLY */
2999 pollrec->next = context->poll_free_list;
3000 context->poll_free_list = pollrec;
3002 context->n_poll_records--;
3006 pollrec = pollrec->next;
3009 #ifdef G_THREADS_ENABLED
3010 context->poll_changed = TRUE;
3012 /* Now wake up the main loop if it is waiting in the poll() */
3013 g_main_context_wakeup_unlocked (context);
3018 * g_source_get_current_time:
3019 * @source: a #GSource
3020 * @timeval: #GTimeVal structure in which to store current time.
3022 * Gets the "current time" to be used when checking
3023 * this source. The advantage of calling this function over
3024 * calling g_get_current_time() directly is that when
3025 * checking multiple sources, GLib can cache a single value
3026 * instead of having to repeatedly get the system time.
3029 g_source_get_current_time (GSource *source,
3032 GMainContext *context;
3034 g_return_if_fail (source->context != NULL);
3036 context = source->context;
3038 LOCK_CONTEXT (context);
3040 if (!context->time_is_current)
3042 g_get_current_time (&context->current_time);
3043 context->time_is_current = TRUE;
3046 *timeval = context->current_time;
3048 UNLOCK_CONTEXT (context);
3052 * g_main_context_set_poll_func:
3053 * @context: a #GMainContext
3054 * @func: the function to call to poll all file descriptors
3056 * Sets the function to use to handle polling of file descriptors. It
3057 * will be used instead of the poll() system call
3058 * (or GLib's replacement function, which is used where
3059 * poll() isn't available).
3061 * This function could possibly be used to integrate the GLib event
3062 * loop with an external event loop.
3065 g_main_context_set_poll_func (GMainContext *context,
3069 context = g_main_context_default ();
3071 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3073 LOCK_CONTEXT (context);
3076 context->poll_func = func;
3080 context->poll_func = (GPollFunc) poll;
3082 context->poll_func = (GPollFunc) g_poll;
3086 UNLOCK_CONTEXT (context);
3090 * g_main_context_get_poll_func:
3091 * @context: a #GMainContext
3093 * Gets the poll function set by g_main_context_set_poll_func().
3095 * Return value: the poll function
3098 g_main_context_get_poll_func (GMainContext *context)
3103 context = g_main_context_default ();
3105 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3107 LOCK_CONTEXT (context);
3108 result = context->poll_func;
3109 UNLOCK_CONTEXT (context);
3114 /* HOLDS: context's lock */
3115 /* Wake the main loop up from a poll() */
3117 g_main_context_wakeup_unlocked (GMainContext *context)
3119 #ifdef G_THREADS_ENABLED
3120 if (g_thread_supported() && context->poll_waiting)
3122 context->poll_waiting = FALSE;
3124 write (context->wake_up_pipe[1], "A", 1);
3126 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
3133 * g_main_context_wakeup:
3134 * @context: a #GMainContext
3136 * If @context is currently waiting in a poll(), interrupt
3137 * the poll(), and continue the iteration process.
3140 g_main_context_wakeup (GMainContext *context)
3143 context = g_main_context_default ();
3145 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3147 LOCK_CONTEXT (context);
3148 g_main_context_wakeup_unlocked (context);
3149 UNLOCK_CONTEXT (context);
3155 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3156 GTimeVal *current_time)
3158 guint seconds = timeout_source->interval / 1000;
3159 guint msecs = timeout_source->interval - seconds * 1000;
3161 timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
3162 timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
3163 if (timeout_source->expiration.tv_usec >= 1000000)
3165 timeout_source->expiration.tv_usec -= 1000000;
3166 timeout_source->expiration.tv_sec++;
3171 g_timeout_prepare (GSource *source,
3176 GTimeVal current_time;
3178 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3180 g_source_get_current_time (source, ¤t_time);
3182 sec = timeout_source->expiration.tv_sec - current_time.tv_sec;
3183 msec = (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000;
3185 /* We do the following in a rather convoluted fashion to deal with
3186 * the fact that we don't have an integral type big enough to hold
3187 * the difference of two timevals in millseconds.
3189 if (sec < 0 || (sec == 0 && msec < 0))
3193 glong interval_sec = timeout_source->interval / 1000;
3194 glong interval_msec = timeout_source->interval % 1000;
3202 if (sec > interval_sec ||
3203 (sec == interval_sec && msec > interval_msec))
3205 /* The system time has been set backwards, so we
3206 * reset the expiration time to now + timeout_source->interval;
3207 * this at least avoids hanging for long periods of time.
3209 g_timeout_set_expiration (timeout_source, ¤t_time);
3210 msec = MIN (G_MAXINT, timeout_source->interval);
3214 msec = MIN (G_MAXINT, (guint)msec + 1000 * (guint)sec);
3218 *timeout = (gint)msec;
3224 g_timeout_check (GSource *source)
3226 GTimeVal current_time;
3227 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3229 g_source_get_current_time (source, ¤t_time);
3231 return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
3232 ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
3233 (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
3237 g_timeout_dispatch (GSource *source,
3238 GSourceFunc callback,
3241 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3245 g_warning ("Timeout source dispatched without callback\n"
3246 "You must call g_source_set_callback().");
3250 if (callback (user_data))
3252 GTimeVal current_time;
3254 g_source_get_current_time (source, ¤t_time);
3255 g_timeout_set_expiration (timeout_source, ¤t_time);
3264 * g_timeout_source_new:
3265 * @interval: the timeout interval in milliseconds.
3267 * Creates a new timeout source.
3269 * The source will not initially be associated with any #GMainContext
3270 * and must be added to one with g_source_attach() before it will be
3273 * Return value: the newly-created timeout source
3276 g_timeout_source_new (guint interval)
3278 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3279 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3280 GTimeVal current_time;
3282 timeout_source->interval = interval;
3284 g_get_current_time (¤t_time);
3285 g_timeout_set_expiration (timeout_source, ¤t_time);
3291 * g_timeout_add_full:
3292 * @priority: the priority of the idle source. Typically this will be in the
3293 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3294 * @interval: the time between calls to the function, in milliseconds
3295 * (1/1000ths of a second)
3296 * @function: function to call
3297 * @data: data to pass to @function
3298 * @notify: function to call when the idle is removed, or %NULL
3300 * Sets a function to be called at regular intervals, with the given
3301 * priority. The function is called repeatedly until it returns
3302 * %FALSE, at which point the timeout is automatically destroyed and
3303 * the function will not be called again. The @notify function is
3304 * called when the timeout is destroyed. The first call to the
3305 * function will be at the end of the first @interval.
3307 * Note that timeout functions may be delayed, due to the processing of other
3308 * event sources. Thus they should not be relied on for precise timing.
3309 * After each call to the timeout function, the time of the next
3310 * timeout is recalculated based on the current time and the given interval
3311 * (it does not try to 'catch up' time lost in delays).
3313 * Return value: the id of event source.
3316 g_timeout_add_full (gint priority,
3318 GSourceFunc function,
3320 GDestroyNotify notify)
3325 g_return_val_if_fail (function != NULL, 0);
3327 source = g_timeout_source_new (interval);
3329 if (priority != G_PRIORITY_DEFAULT)
3330 g_source_set_priority (source, priority);
3332 g_source_set_callback (source, function, data, notify);
3333 id = g_source_attach (source, NULL);
3334 g_source_unref (source);
3341 * @interval: the time between calls to the function, in milliseconds
3342 * (1/1000ths of a second)
3343 * @function: function to call
3344 * @data: data to pass to @function
3346 * Sets a function to be called at regular intervals, with the default
3347 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
3348 * until it returns %FALSE, at which point the timeout is automatically
3349 * destroyed and the function will not be called again. The first call
3350 * to the function will be at the end of the first @interval.
3352 * Note that timeout functions may be delayed, due to the processing of other
3353 * event sources. Thus they should not be relied on for precise timing.
3354 * After each call to the timeout function, the time of the next
3355 * timeout is recalculated based on the current time and the given interval
3356 * (it does not try to 'catch up' time lost in delays).
3358 * Return value: the id of event source.
3361 g_timeout_add (guint32 interval,
3362 GSourceFunc function,
3365 return g_timeout_add_full (G_PRIORITY_DEFAULT,
3366 interval, function, data, NULL);
3369 /* Child watch functions */
3374 g_child_watch_prepare (GSource *source,
3383 g_child_watch_check (GSource *source)
3385 GChildWatchSource *child_watch_source;
3386 gboolean child_exited;
3388 child_watch_source = (GChildWatchSource *) source;
3390 child_exited = child_watch_source->poll.revents & G_IO_IN;
3397 * Note: We do _not_ check for the special value of STILL_ACTIVE
3398 * since we know that the process has exited and doing so runs into
3399 * problems if the child process "happens to return STILL_ACTIVE(259)"
3400 * as Microsoft's Platform SDK puts it.
3402 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
3404 gchar *emsg = g_win32_error_message (GetLastError ());
3405 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
3408 child_watch_source->child_status = -1;
3411 child_watch_source->child_status = child_status;
3414 return child_exited;
3417 #else /* G_OS_WIN32 */
3420 check_for_child_exited (GSource *source)
3422 GChildWatchSource *child_watch_source;
3425 /* protect against another SIGCHLD in the middle of this call */
3426 count = child_watch_count;
3428 child_watch_source = (GChildWatchSource *) source;
3430 if (child_watch_source->child_exited)
3433 if (child_watch_source->count < count)
3437 if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
3439 child_watch_source->child_status = child_status;
3440 child_watch_source->child_exited = TRUE;
3442 child_watch_source->count = count;
3445 return child_watch_source->child_exited;
3449 g_child_watch_prepare (GSource *source,
3452 GChildWatchSource *child_watch_source;
3455 child_watch_source = (GChildWatchSource *) source;
3457 return check_for_child_exited (source);
3462 g_child_watch_check (GSource *source)
3464 GChildWatchSource *child_watch_source;
3466 child_watch_source = (GChildWatchSource *) source;
3468 return check_for_child_exited (source);
3471 #endif /* G_OS_WIN32 */
3474 g_child_watch_dispatch (GSource *source,
3475 GSourceFunc callback,
3478 GChildWatchSource *child_watch_source;
3479 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
3481 child_watch_source = (GChildWatchSource *) source;
3485 g_warning ("Child watch source dispatched without callback\n"
3486 "You must call g_source_set_callback().");
3490 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
3492 /* We never keep a child watch source around as the child is gone */
3499 g_child_watch_signal_handler (int signum)
3501 child_watch_count ++;
3503 if (child_watch_init_state == CHILD_WATCH_INITIALIZED_THREADED)
3505 write (child_watch_wake_up_pipe[1], "B", 1);
3509 /* We count on the signal interrupting the poll in the same thread.
3515 g_child_watch_source_init_single (void)
3517 g_assert (! g_thread_supported());
3518 g_assert (child_watch_init_state == CHILD_WATCH_UNINITIALIZED);
3520 child_watch_init_state = CHILD_WATCH_INITIALIZED_SINGLE;
3522 signal (SIGCHLD, g_child_watch_signal_handler);
3526 child_watch_helper_thread (gpointer data)
3529 GPollFunc poll_func;
3532 poll_func = (GPollFunc)poll;
3537 fds.fd = child_watch_wake_up_pipe[0];
3538 fds.events = G_IO_IN;
3545 read (child_watch_wake_up_pipe[0], b, 20);
3547 /* We were woken up. Wake up all other contexts in all other threads */
3548 G_LOCK (main_context_list);
3549 for (list = main_context_list; list; list = list->next)
3551 GMainContext *context;
3553 context = list->data;
3554 if (g_atomic_int_get (&context->ref_count) > 0)
3555 /* Due to racing conditions we can find ref_count == 0, in
3556 * that case, however, the context is still not destroyed
3557 * and no poll can be active, otherwise the ref_count
3559 g_main_context_wakeup (context);
3561 G_UNLOCK (main_context_list);
3567 g_child_watch_source_init_multi_threaded (void)
3569 GError *error = NULL;
3571 g_assert (g_thread_supported());
3573 if (pipe (child_watch_wake_up_pipe) < 0)
3574 g_error ("Cannot create wake up pipe: %s\n", g_strerror (errno));
3575 fcntl (child_watch_wake_up_pipe[1], F_SETFL, O_NONBLOCK | fcntl (child_watch_wake_up_pipe[1], F_GETFL));
3577 /* We create a helper thread that polls on the wakeup pipe indefinitely */
3578 /* FIXME: Think this through for races */
3579 if (g_thread_create (child_watch_helper_thread, NULL, FALSE, &error) == NULL)
3580 g_error ("Cannot create a thread to monitor child exit status: %s\n", error->message);
3581 child_watch_init_state = CHILD_WATCH_INITIALIZED_THREADED;
3582 signal (SIGCHLD, g_child_watch_signal_handler);
3586 g_child_watch_source_init_promote_single_to_threaded (void)
3588 g_child_watch_source_init_multi_threaded ();
3592 g_child_watch_source_init (void)
3594 if (g_thread_supported())
3596 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
3597 g_child_watch_source_init_multi_threaded ();
3598 else if (child_watch_init_state == CHILD_WATCH_INITIALIZED_SINGLE)
3599 g_child_watch_source_init_promote_single_to_threaded ();
3603 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
3604 g_child_watch_source_init_single ();
3608 #endif /* !G_OS_WIN32 */
3611 * g_child_watch_source_new:
3612 * @pid: process id of a child process to watch
3614 * Creates a new child_watch source.
3616 * The source will not initially be associated with any #GMainContext
3617 * and must be added to one with g_source_attach() before it will be
3620 * Note that on platforms where #GPid must be explicitely closed
3621 * (see g_spawn_close_pid()) @pid must not be closed while the
3622 * source is still active. Typically, you will want to call
3623 * g_spawn_close_pid() in the callback function for the source.
3625 * Return value: the newly-created child watch source
3630 g_child_watch_source_new (GPid pid)
3632 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
3633 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
3636 child_watch_source->poll.fd = (int)pid;
3637 child_watch_source->poll.events = G_IO_IN;
3639 g_source_add_poll (source, &child_watch_source->poll);
3640 #else /* G_OS_WIN32 */
3641 g_child_watch_source_init ();
3642 #endif /* G_OS_WIN32 */
3644 child_watch_source->pid = pid;
3650 * g_child_watch_add_full:
3651 * @priority: the priority of the idle source. Typically this will be in the
3652 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3653 * @pid: process id of a child process to watch
3654 * @function: function to call
3655 * @data: data to pass to @function
3656 * @notify: function to call when the idle is removed, or %NULL
3658 * Sets a function to be called when the child indicated by @pid exits, at a
3659 * default priority, #G_PRIORITY_DEFAULT.
3661 * Note that on platforms where #GPid must be explicitely closed
3662 * (see g_spawn_close_pid()) @pid must not be closed while the
3663 * source is still active. Typically, you will want to call
3664 * g_spawn_close_pid() in the callback function for the source.
3666 * Return value: the id of event source.
3671 g_child_watch_add_full (gint priority,
3673 GChildWatchFunc function,
3675 GDestroyNotify notify)
3680 g_return_val_if_fail (function != NULL, 0);
3682 source = g_child_watch_source_new (pid);
3684 if (priority != G_PRIORITY_DEFAULT)
3685 g_source_set_priority (source, priority);
3687 g_source_set_callback (source, (GSourceFunc) function, data, notify);
3688 id = g_source_attach (source, NULL);
3689 g_source_unref (source);
3695 * g_child_watch_add:
3696 * @pid: process id of a child process to watch
3697 * @function: function to call
3698 * @data: data to pass to @function
3700 * Sets a function to be called when the child indicated by @pid exits, at a
3701 * default priority, #G_PRIORITY_DEFAULT.
3703 * Note that on platforms where #GPid must be explicitely closed
3704 * (see g_spawn_close_pid()) @pid must not be closed while the
3705 * source is still active. Typically, you will want to call
3706 * g_spawn_close_pid() in the callback function for the source.
3708 * Return value: the id of event source.
3713 g_child_watch_add (GPid pid,
3714 GChildWatchFunc function,
3717 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
3721 /* Idle functions */
3724 g_idle_prepare (GSource *source,
3733 g_idle_check (GSource *source)
3739 g_idle_dispatch (GSource *source,
3740 GSourceFunc callback,
3745 g_warning ("Idle source dispatched without callback\n"
3746 "You must call g_source_set_callback().");
3750 return callback (user_data);
3754 * g_idle_source_new:
3756 * Creates a new idle source.
3758 * The source will not initially be associated with any #GMainContext
3759 * and must be added to one with g_source_attach() before it will be
3760 * executed. Note that the default priority for idle sources is
3761 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
3762 * have a default priority of %G_PRIORITY_DEFAULT.
3764 * Return value: the newly-created idle source
3767 g_idle_source_new (void)
3771 source = g_source_new (&g_idle_funcs, sizeof (GSource));
3772 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
3779 * @priority: the priority of the idle source. Typically this will be in the
3780 * range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3781 * @function: function to call
3782 * @data: data to pass to @function
3783 * @notify: function to call when the idle is removed, or %NULL
3785 * Adds a function to be called whenever there are no higher priority
3786 * events pending. If the function returns %FALSE it is automatically
3787 * removed from the list of event sources and will not be called again.
3789 * Return value: the id of the event source.
3792 g_idle_add_full (gint priority,
3793 GSourceFunc function,
3795 GDestroyNotify notify)
3800 g_return_val_if_fail (function != NULL, 0);
3802 source = g_idle_source_new ();
3804 if (priority != G_PRIORITY_DEFAULT_IDLE)
3805 g_source_set_priority (source, priority);
3807 g_source_set_callback (source, function, data, notify);
3808 id = g_source_attach (source, NULL);
3809 g_source_unref (source);
3816 * @function: function to call
3817 * @data: data to pass to @function.
3819 * Adds a function to be called whenever there are no higher priority
3820 * events pending to the default main loop. The function is given the
3821 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
3822 * returns %FALSE it is automatically removed from the list of event
3823 * sources and will not be called again.
3825 * Return value: the id of the event source.
3828 g_idle_add (GSourceFunc function,
3831 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
3835 * g_idle_remove_by_data:
3836 * @data: the data for the idle source's callback.
3838 * Removes the idle function with the given data.
3840 * Return value: %TRUE if an idle source was found and removed.
3843 g_idle_remove_by_data (gpointer data)
3845 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);