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 <sys/socket.h>
73 #endif /* G_OS_BEOS */
84 typedef struct _GTimeoutSource GTimeoutSource;
85 typedef struct _GChildWatchSource GChildWatchSource;
86 typedef struct _GPollRec GPollRec;
87 typedef struct _GSourceCallback GSourceCallback;
91 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
92 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
95 #ifdef G_THREADS_ENABLED
96 typedef struct _GMainWaiter GMainWaiter;
107 #ifdef G_THREADS_ENABLED
108 /* The following lock is used for both the list of sources
109 * and the list of poll records
120 GPtrArray *pending_dispatches;
121 gint timeout; /* Timeout for current iteration */
124 GSource *source_list;
125 gint in_check_or_prepare;
127 GPollRec *poll_records;
128 GPollRec *poll_free_list;
129 GMemChunk *poll_chunk;
130 guint n_poll_records;
131 GPollFD *cached_poll_array;
132 guint cached_poll_array_size;
134 #ifdef G_THREADS_ENABLED
136 /* this pipe is used to wake up the main loop when a source is added.
138 gint wake_up_pipe[2];
139 #else /* G_OS_WIN32 */
140 HANDLE wake_up_semaphore;
141 #endif /* G_OS_WIN32 */
144 gboolean poll_waiting;
146 /* Flag indicating whether the set of fd's changed during a poll */
147 gboolean poll_changed;
148 #endif /* G_THREADS_ENABLED */
152 GTimeVal current_time;
153 gboolean time_is_current;
156 struct _GSourceCallback
161 GDestroyNotify notify;
166 GMainContext *context;
171 struct _GTimeoutSource
178 struct _GChildWatchSource
185 #else /* G_OS_WIN32 */
187 gboolean child_exited;
188 #endif /* G_OS_WIN32 */
198 #ifdef G_THREADS_ENABLED
199 #define LOCK_CONTEXT(context) g_static_mutex_lock (&context->mutex)
200 #define UNLOCK_CONTEXT(context) g_static_mutex_unlock (&context->mutex)
201 #define G_THREAD_SELF g_thread_self ()
203 #define LOCK_CONTEXT(context) (void)0
204 #define UNLOCK_CONTEXT(context) (void)0
205 #define G_THREAD_SELF NULL
208 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
209 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
210 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
212 #define SOURCE_UNREF(source, context) \
214 if ((source)->ref_count > 1) \
215 (source)->ref_count--; \
217 g_source_unref_internal ((source), (context), TRUE); \
221 /* Forward declarations */
223 static void g_source_unref_internal (GSource *source,
224 GMainContext *context,
226 static void g_source_destroy_internal (GSource *source,
227 GMainContext *context,
229 static void g_main_context_poll (GMainContext *context,
234 static void g_main_context_add_poll_unlocked (GMainContext *context,
237 static void g_main_context_remove_poll_unlocked (GMainContext *context,
239 static void g_main_context_wakeup_unlocked (GMainContext *context);
241 static gboolean g_timeout_prepare (GSource *source,
243 static gboolean g_timeout_check (GSource *source);
244 static gboolean g_timeout_dispatch (GSource *source,
245 GSourceFunc callback,
247 static gboolean g_child_watch_prepare (GSource *source,
249 static gboolean g_child_watch_check (GSource *source);
250 static gboolean g_child_watch_dispatch (GSource *source,
251 GSourceFunc callback,
253 static gboolean g_idle_prepare (GSource *source,
255 static gboolean g_idle_check (GSource *source);
256 static gboolean g_idle_dispatch (GSource *source,
257 GSourceFunc callback,
260 G_LOCK_DEFINE_STATIC (main_loop);
261 static GMainContext *default_main_context;
262 static GSList *main_contexts_without_pipe = NULL;
265 /* Child status monitoring code */
267 CHILD_WATCH_UNINITIALIZED,
268 CHILD_WATCH_INITIALIZED_SINGLE,
269 CHILD_WATCH_INITIALIZED_THREADED
271 static gint child_watch_init_state = CHILD_WATCH_UNINITIALIZED;
272 static gint child_watch_count = 1;
273 static gint child_watch_wake_up_pipe[2] = {0, 0};
274 #endif /* !G_OS_WIN32 */
275 G_LOCK_DEFINE_STATIC (main_context_list);
276 static GSList *main_context_list = NULL;
278 GSourceFuncs g_timeout_funcs =
286 GSourceFuncs g_child_watch_funcs =
288 g_child_watch_prepare,
290 g_child_watch_dispatch,
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 else if (ready >= WAIT_OBJECT_0 && ready < WAIT_OBJECT_0 + nhandles)
483 for (f = fds; f < &fds[nfds]; ++f)
485 if (f->fd == (gint) handles[ready - WAIT_OBJECT_0])
487 f->revents = f->events;
488 #ifdef G_MAIN_POLL_DEBUG
489 g_print ("g_poll: got event %#x\n", f->fd);
497 #else /* !G_OS_WIN32 */
499 /* The following implementation of poll() comes from the GNU C Library.
500 * Copyright (C) 1994, 1996, 1997 Free Software Foundation, Inc.
503 #include <string.h> /* for bzero on BSD systems */
505 #ifdef HAVE_SYS_SELECT_H
506 #include <sys/select.h>
507 #endif /* HAVE_SYS_SELECT_H */
511 #endif /* G_OS_BEOS */
514 # define SELECT_MASK fd_set
515 #else /* !NO_FD_SET */
517 typedef long fd_mask;
520 # define SELECT_MASK void
522 # define SELECT_MASK int
523 # endif /* !_IBMR2 */
524 #endif /* !NO_FD_SET */
527 g_poll (GPollFD *fds,
532 SELECT_MASK rset, wset, xset;
541 for (f = fds; f < &fds[nfds]; ++f)
544 if (f->events & G_IO_IN)
545 FD_SET (f->fd, &rset);
546 if (f->events & G_IO_OUT)
547 FD_SET (f->fd, &wset);
548 if (f->events & G_IO_PRI)
549 FD_SET (f->fd, &xset);
550 if (f->fd > maxfd && (f->events & (G_IO_IN|G_IO_OUT|G_IO_PRI)))
554 tv.tv_sec = timeout / 1000;
555 tv.tv_usec = (timeout % 1000) * 1000;
557 ready = select (maxfd + 1, &rset, &wset, &xset,
558 timeout == -1 ? NULL : &tv);
560 for (f = fds; f < &fds[nfds]; ++f)
565 if (FD_ISSET (f->fd, &rset))
566 f->revents |= G_IO_IN;
567 if (FD_ISSET (f->fd, &wset))
568 f->revents |= G_IO_OUT;
569 if (FD_ISSET (f->fd, &xset))
570 f->revents |= G_IO_PRI;
577 #endif /* !G_OS_WIN32 */
579 #endif /* !HAVE_POLL */
582 * g_main_context_ref:
583 * @context: a #GMainContext
585 * Increases the reference count on a #GMainContext object by one.
587 * Returns: the @context that was passed in (since 2.6)
590 g_main_context_ref (GMainContext *context)
592 g_return_val_if_fail (context != NULL, NULL);
593 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
595 g_atomic_int_inc (&context->ref_count);
600 /* If DISABLE_MEM_POOLS is defined, then freeing the
601 * mem chunk won't free the records, so we have to
602 * do it manually. The conditionalization here is
603 * an optimization; g_mem_chunk_free() is a no-op
604 * when DISABLE_MEM_POOLS is set.
606 #ifdef DISABLE_MEM_POOLS
608 poll_rec_list_free (GMainContext *context,
613 GPollRec *tmp_rec = list;
615 g_chunk_free (tmp_rec, context->poll_chunk);
618 #endif /* DISABLE_MEM_POOLS */
621 * g_main_context_unref:
622 * @context: a #GMainContext
624 * Decreases the reference count on a #GMainContext object by one. If
625 * the result is zero, free the context and free all associated memory.
628 g_main_context_unref (GMainContext *context)
631 g_return_if_fail (context != NULL);
632 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
634 if (!g_atomic_int_dec_and_test (&context->ref_count))
637 G_LOCK (main_context_list);
638 main_context_list = g_slist_remove (main_context_list, context);
639 G_UNLOCK (main_context_list);
641 source = context->source_list;
644 GSource *next = source->next;
645 g_source_destroy_internal (source, context, TRUE);
649 #ifdef G_THREADS_ENABLED
650 g_static_mutex_free (&context->mutex);
653 g_ptr_array_free (context->pending_dispatches, TRUE);
654 g_free (context->cached_poll_array);
656 #ifdef DISABLE_MEM_POLLS
657 poll_rec_list_free (context, context->poll_records);
658 poll_rec_list_free (context, context->poll_free_list);
659 #endif /* DISABLE_MEM_POOLS */
661 if (context->poll_chunk)
662 g_mem_chunk_destroy (context->poll_chunk);
664 #ifdef G_THREADS_ENABLED
665 if (g_thread_supported())
668 close (context->wake_up_pipe[0]);
669 close (context->wake_up_pipe[1]);
671 CloseHandle (context->wake_up_semaphore);
675 main_contexts_without_pipe = g_slist_remove (main_contexts_without_pipe,
682 #ifdef G_THREADS_ENABLED
684 g_main_context_init_pipe (GMainContext *context)
687 if (context->wake_up_pipe[0] != -1)
689 if (pipe (context->wake_up_pipe) < 0)
690 g_error ("Cannot create pipe main loop wake-up: %s\n",
693 context->wake_up_rec.fd = context->wake_up_pipe[0];
694 context->wake_up_rec.events = G_IO_IN;
696 if (context->wake_up_semaphore != NULL)
698 context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
699 if (context->wake_up_semaphore == NULL)
700 g_error ("Cannot create wake-up semaphore: %s",
701 g_win32_error_message (GetLastError ()));
702 context->wake_up_rec.fd = (gint) context->wake_up_semaphore;
703 context->wake_up_rec.events = G_IO_IN;
704 # ifdef G_MAIN_POLL_DEBUG
705 g_print ("wake-up semaphore: %#x\n", (guint) context->wake_up_semaphore);
708 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
712 _g_main_thread_init (void)
714 GSList *curr = main_contexts_without_pipe;
717 g_main_context_init_pipe ((GMainContext *)curr->data);
720 g_slist_free (main_contexts_without_pipe);
721 main_contexts_without_pipe = NULL;
723 #endif /* G_THREADS_ENABLED */
726 * g_main_context_new:
728 * Creates a new #GMainContext strcuture
730 * Return value: the new #GMainContext
733 g_main_context_new (void)
735 GMainContext *context = g_new0 (GMainContext, 1);
737 #ifdef G_THREADS_ENABLED
738 g_static_mutex_init (&context->mutex);
740 context->owner = NULL;
741 context->waiters = NULL;
744 context->wake_up_pipe[0] = -1;
745 context->wake_up_pipe[1] = -1;
747 context->wake_up_semaphore = NULL;
751 context->ref_count = 1;
753 context->next_id = 1;
755 context->source_list = NULL;
758 context->poll_func = (GPollFunc)poll;
760 context->poll_func = g_poll;
763 context->cached_poll_array = NULL;
764 context->cached_poll_array_size = 0;
766 context->pending_dispatches = g_ptr_array_new ();
768 context->time_is_current = FALSE;
770 #ifdef G_THREADS_ENABLED
771 if (g_thread_supported ())
772 g_main_context_init_pipe (context);
774 main_contexts_without_pipe = g_slist_prepend (main_contexts_without_pipe,
778 G_LOCK (main_context_list);
779 main_context_list = g_slist_append (main_context_list, context);
780 G_UNLOCK (main_context_list);
786 * g_main_context_default:
788 * Returns the default main context. This is the main context used
789 * for main loop functions when a main loop is not explicitly
792 * Return value: the default main context.
795 g_main_context_default (void)
801 if (!default_main_context)
802 default_main_context = g_main_context_new ();
804 G_UNLOCK (main_loop);
806 return default_main_context;
809 /* Hooks for adding to the main loop */
813 * @source_funcs: structure containing functions that implement
814 * the sources behavior.
815 * @struct_size: size of the #GSource structure to create.
817 * Creates a new #GSource structure. The size is specified to
818 * allow creating structures derived from #GSource that contain
819 * additional data. The size passed in must be at least
820 * <literal>sizeof (GSource)</literal>.
822 * The source will not initially be associated with any #GMainContext
823 * and must be added to one with g_source_attach() before it will be
826 * Return value: the newly-created #GSource.
829 g_source_new (GSourceFuncs *source_funcs,
834 g_return_val_if_fail (source_funcs != NULL, NULL);
835 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
837 source = (GSource*) g_malloc0 (struct_size);
839 source->source_funcs = source_funcs;
840 source->ref_count = 1;
842 source->priority = G_PRIORITY_DEFAULT;
844 source->flags = G_HOOK_FLAG_ACTIVE;
846 /* NULL/0 initialization for all other fields */
851 /* Holds context's lock
854 g_source_list_add (GSource *source,
855 GMainContext *context)
857 GSource *tmp_source, *last_source;
860 tmp_source = context->source_list;
861 while (tmp_source && tmp_source->priority <= source->priority)
863 last_source = tmp_source;
864 tmp_source = tmp_source->next;
867 source->next = tmp_source;
869 tmp_source->prev = source;
871 source->prev = last_source;
873 last_source->next = source;
875 context->source_list = source;
878 /* Holds context's lock
881 g_source_list_remove (GSource *source,
882 GMainContext *context)
885 source->prev->next = source->next;
887 context->source_list = source->next;
890 source->next->prev = source->prev;
898 * @source: a #GSource
899 * @context: a #GMainContext (if %NULL, the default context will be used)
901 * Adds a #GSource to a @context so that it will be executed within
904 * Return value: the ID for the source within the #GMainContext
907 g_source_attach (GSource *source,
908 GMainContext *context)
913 g_return_val_if_fail (source->context == NULL, 0);
914 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
917 context = g_main_context_default ();
919 LOCK_CONTEXT (context);
921 source->context = context;
922 result = source->source_id = context->next_id++;
925 g_source_list_add (source, context);
927 tmp_list = source->poll_fds;
930 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
931 tmp_list = tmp_list->next;
934 #ifdef G_THREADS_ENABLED
935 /* Now wake up the main loop if it is waiting in the poll() */
936 g_main_context_wakeup_unlocked (context);
939 UNLOCK_CONTEXT (context);
945 g_source_destroy_internal (GSource *source,
946 GMainContext *context,
950 LOCK_CONTEXT (context);
952 if (!SOURCE_DESTROYED (source))
955 gpointer old_cb_data;
956 GSourceCallbackFuncs *old_cb_funcs;
958 source->flags &= ~G_HOOK_FLAG_ACTIVE;
960 old_cb_data = source->callback_data;
961 old_cb_funcs = source->callback_funcs;
963 source->callback_data = NULL;
964 source->callback_funcs = NULL;
968 UNLOCK_CONTEXT (context);
969 old_cb_funcs->unref (old_cb_data);
970 LOCK_CONTEXT (context);
973 if (!SOURCE_BLOCKED (source))
975 tmp_list = source->poll_fds;
978 g_main_context_remove_poll_unlocked (context, tmp_list->data);
979 tmp_list = tmp_list->next;
983 g_source_unref_internal (source, context, TRUE);
987 UNLOCK_CONTEXT (context);
992 * @source: a #GSource
994 * Removes a source from its #GMainContext, if any, and mark it as
995 * destroyed. The source cannot be subsequently added to another
999 g_source_destroy (GSource *source)
1001 GMainContext *context;
1003 g_return_if_fail (source != NULL);
1005 context = source->context;
1008 g_source_destroy_internal (source, context, FALSE);
1010 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1015 * @source: a #GSource
1017 * Returns the numeric ID for a particular source. The ID of a source
1018 * is unique within a particular main loop context. The reverse
1019 * mapping from ID to source is done by g_main_context_find_source_by_id().
1021 * Return value: the ID for the source
1024 g_source_get_id (GSource *source)
1028 g_return_val_if_fail (source != NULL, 0);
1029 g_return_val_if_fail (source->context != NULL, 0);
1031 LOCK_CONTEXT (source->context);
1032 result = source->source_id;
1033 UNLOCK_CONTEXT (source->context);
1039 * g_source_get_context:
1040 * @source: a #GSource
1042 * Gets the #GMainContext with which the source is associated.
1043 * Calling this function on a destroyed source is an error.
1045 * Return value: the #GMainContext with which the source is associated,
1046 * or %NULL if the context has not yet been added
1050 g_source_get_context (GSource *source)
1052 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1054 return source->context;
1058 * g_source_add_poll:
1059 * @source:a #GSource
1060 * @fd: a #GPollFD structure holding information about a file
1061 * descriptor to watch.
1063 * Adds a file descriptor to the set of file descriptors polled for
1064 * this source. This is usually combined with g_source_new() to add an
1065 * event source. The event source's check function will typically test
1066 * the @revents field in the #GPollFD struct and return %TRUE if events need
1070 g_source_add_poll (GSource *source,
1073 GMainContext *context;
1075 g_return_if_fail (source != NULL);
1076 g_return_if_fail (fd != NULL);
1077 g_return_if_fail (!SOURCE_DESTROYED (source));
1079 context = source->context;
1082 LOCK_CONTEXT (context);
1084 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1088 if (!SOURCE_BLOCKED (source))
1089 g_main_context_add_poll_unlocked (context, source->priority, fd);
1090 UNLOCK_CONTEXT (context);
1095 * g_source_remove_poll:
1096 * @source:a #GSource
1097 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1099 * Removes a file descriptor from the set of file descriptors polled for
1103 g_source_remove_poll (GSource *source,
1106 GMainContext *context;
1108 g_return_if_fail (source != NULL);
1109 g_return_if_fail (fd != NULL);
1110 g_return_if_fail (!SOURCE_DESTROYED (source));
1112 context = source->context;
1115 LOCK_CONTEXT (context);
1117 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1121 if (!SOURCE_BLOCKED (source))
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 /* Remove the source from the context's source and then
1277 * add it back so it is sorted in the correct plcae
1279 g_source_list_remove (source, source->context);
1280 g_source_list_add (source, source->context);
1282 if (!SOURCE_BLOCKED (source))
1284 tmp_list = source->poll_fds;
1287 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1288 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1290 tmp_list = tmp_list->next;
1294 UNLOCK_CONTEXT (source->context);
1299 * g_source_get_priority:
1300 * @source: a #GSource
1302 * Gets the priority of a source.
1304 * Return value: the priority of the source
1307 g_source_get_priority (GSource *source)
1309 g_return_val_if_fail (source != NULL, 0);
1311 return source->priority;
1315 * g_source_set_can_recurse:
1316 * @source: a #GSource
1317 * @can_recurse: whether recursion is allowed for this source
1319 * Sets whether a source can be called recursively. If @can_recurse is
1320 * %TRUE, then while the source is being dispatched then this source
1321 * will be processed normally. Otherwise, all processing of this
1322 * source is blocked until the dispatch function returns.
1325 g_source_set_can_recurse (GSource *source,
1326 gboolean can_recurse)
1328 GMainContext *context;
1330 g_return_if_fail (source != NULL);
1332 context = source->context;
1335 LOCK_CONTEXT (context);
1338 source->flags |= G_SOURCE_CAN_RECURSE;
1340 source->flags &= ~G_SOURCE_CAN_RECURSE;
1343 UNLOCK_CONTEXT (context);
1347 * g_source_get_can_recurse:
1348 * @source: a #GSource
1350 * Checks whether a source is allowed to be called recursively.
1351 * see g_source_set_can_recurse().
1353 * Return value: whether recursion is allowed.
1356 g_source_get_can_recurse (GSource *source)
1358 g_return_val_if_fail (source != NULL, FALSE);
1360 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1365 * @source: a #GSource
1367 * Increases the reference count on a source by one.
1369 * Return value: @source
1372 g_source_ref (GSource *source)
1374 GMainContext *context;
1376 g_return_val_if_fail (source != NULL, NULL);
1378 context = source->context;
1381 LOCK_CONTEXT (context);
1383 source->ref_count++;
1386 UNLOCK_CONTEXT (context);
1391 /* g_source_unref() but possible to call within context lock
1394 g_source_unref_internal (GSource *source,
1395 GMainContext *context,
1398 gpointer old_cb_data = NULL;
1399 GSourceCallbackFuncs *old_cb_funcs = NULL;
1401 g_return_if_fail (source != NULL);
1403 if (!have_lock && context)
1404 LOCK_CONTEXT (context);
1406 source->ref_count--;
1407 if (source->ref_count == 0)
1409 old_cb_data = source->callback_data;
1410 old_cb_funcs = source->callback_funcs;
1412 source->callback_data = NULL;
1413 source->callback_funcs = NULL;
1415 if (context && !SOURCE_DESTROYED (source))
1417 g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1418 source->ref_count++;
1421 g_source_list_remove (source, context);
1423 if (source->source_funcs->finalize)
1424 source->source_funcs->finalize (source);
1426 g_slist_free (source->poll_fds);
1427 source->poll_fds = NULL;
1431 if (!have_lock && context)
1432 UNLOCK_CONTEXT (context);
1437 UNLOCK_CONTEXT (context);
1439 old_cb_funcs->unref (old_cb_data);
1442 LOCK_CONTEXT (context);
1448 * @source: a #GSource
1450 * Decreases the reference count of a source by one. If the
1451 * resulting reference count is zero the source and associated
1452 * memory will be destroyed.
1455 g_source_unref (GSource *source)
1457 g_return_if_fail (source != NULL);
1459 g_source_unref_internal (source, source->context, FALSE);
1463 * g_main_context_find_source_by_id:
1464 * @context: a #GMainContext (if %NULL, the default context will be used)
1465 * @source_id: the source ID, as returned by g_source_get_id()
1467 * Finds a #GSource given a pair of context and ID
1469 * Return value: the #GSource if found, otherwise, %NULL
1472 g_main_context_find_source_by_id (GMainContext *context,
1477 g_return_val_if_fail (source_id > 0, NULL);
1479 if (context == NULL)
1480 context = g_main_context_default ();
1482 LOCK_CONTEXT (context);
1484 source = context->source_list;
1487 if (!SOURCE_DESTROYED (source) &&
1488 source->source_id == source_id)
1490 source = source->next;
1493 UNLOCK_CONTEXT (context);
1499 * g_main_context_find_source_by_funcs_user_data:
1500 * @context: a #GMainContext (if %NULL, the default context will be used).
1501 * @funcs: the @source_funcs passed to g_source_new().
1502 * @user_data: the user data from the callback.
1504 * Finds a source with the given source functions and user data. If
1505 * multiple sources exist with the same source function and user data,
1506 * the first one found will be returned.
1508 * Return value: the source, if one was found, otherwise %NULL
1511 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1512 GSourceFuncs *funcs,
1517 g_return_val_if_fail (funcs != NULL, NULL);
1519 if (context == NULL)
1520 context = g_main_context_default ();
1522 LOCK_CONTEXT (context);
1524 source = context->source_list;
1527 if (!SOURCE_DESTROYED (source) &&
1528 source->source_funcs == funcs &&
1529 source->callback_funcs)
1531 GSourceFunc callback;
1532 gpointer callback_data;
1534 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1536 if (callback_data == user_data)
1539 source = source->next;
1542 UNLOCK_CONTEXT (context);
1548 * g_main_context_find_source_by_user_data:
1549 * @context: a #GMainContext
1550 * @user_data: the user_data for the callback.
1552 * Finds a source with the given user data for the callback. If
1553 * multiple sources exist with the same user data, the first
1554 * one found will be returned.
1556 * Return value: the source, if one was found, otherwise %NULL
1559 g_main_context_find_source_by_user_data (GMainContext *context,
1564 if (context == NULL)
1565 context = g_main_context_default ();
1567 LOCK_CONTEXT (context);
1569 source = context->source_list;
1572 if (!SOURCE_DESTROYED (source) &&
1573 source->callback_funcs)
1575 GSourceFunc callback;
1576 gpointer callback_data = NULL;
1578 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1580 if (callback_data == user_data)
1583 source = source->next;
1586 UNLOCK_CONTEXT (context);
1593 * @tag: the id of the source to remove.
1595 * Removes the source with the given id from the default main context. The id of
1596 * a #GSource is given by g_source_get_id(), or will be returned by the
1597 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1598 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1599 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1601 * See also g_source_destroy().
1603 * Return value: %TRUE if the source was found and removed.
1606 g_source_remove (guint tag)
1610 g_return_val_if_fail (tag > 0, FALSE);
1612 source = g_main_context_find_source_by_id (NULL, tag);
1614 g_source_destroy (source);
1616 return source != NULL;
1620 * g_source_remove_by_user_data:
1621 * @user_data: the user_data for the callback.
1623 * Removes a source from the default main loop context given the user
1624 * data for the callback. If multiple sources exist with the same user
1625 * data, only one will be destroyed.
1627 * Return value: %TRUE if a source was found and removed.
1630 g_source_remove_by_user_data (gpointer user_data)
1634 source = g_main_context_find_source_by_user_data (NULL, user_data);
1637 g_source_destroy (source);
1645 * g_source_remove_by_funcs_user_data:
1646 * @funcs: The @source_funcs passed to g_source_new()
1647 * @user_data: the user data for the callback
1649 * Removes a source from the default main loop context given the
1650 * source functions and user data. If multiple sources exist with the
1651 * same source functions and user data, only one will be destroyed.
1653 * Return value: %TRUE if a source was found and removed.
1656 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1661 g_return_val_if_fail (funcs != NULL, FALSE);
1663 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1666 g_source_destroy (source);
1674 * g_get_current_time:
1675 * @result: #GTimeVal structure in which to store current time.
1677 * Equivalent to the UNIX gettimeofday() function, but portable.
1680 g_get_current_time (GTimeVal *result)
1685 g_return_if_fail (result != NULL);
1687 /*this is required on alpha, there the timeval structs are int's
1688 not longs and a cast only would fail horribly*/
1689 gettimeofday (&r, NULL);
1690 result->tv_sec = r.tv_sec;
1691 result->tv_usec = r.tv_usec;
1694 guint64 *time64 = (guint64 *) &ft;
1696 GetSystemTimeAsFileTime (&ft);
1698 /* Convert from 100s of nanoseconds since 1601-01-01
1699 * to Unix epoch. Yes, this is Y2038 unsafe.
1701 *time64 -= G_GINT64_CONSTANT (116444736000000000);
1704 result->tv_sec = *time64 / 1000000;
1705 result->tv_usec = *time64 % 1000000;
1709 /* Running the main loop */
1712 get_depth_pointer (void)
1714 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
1715 gint *depth_pointer = g_static_private_get (&depth_private);
1718 depth_pointer = g_new (gint, 1);
1720 g_static_private_set (&depth_private, depth_pointer, g_free);
1723 return depth_pointer;
1729 * Return value: The main loop recursion level in the current thread
1731 * Returns the depth of the stack of calls to
1732 * g_main_context_dispatch() on any #GMainContext in the current thread.
1733 * That is, when called from the toplevel, it gives 0. When
1734 * called from within a callback from g_main_context_iteration()
1735 * (or g_main_loop_run(), etc.) it returns 1. When called from within
1736 * a callback to a recursive call to g_main_context_iterate(),
1737 * it returns 2. And so forth.
1739 * This function is useful in a situation like the following:
1740 * Imagine an extremely simple "garbage collected" system.
1743 * static GList *free_list;
1746 * allocate_memory (gsize size)
1748 * gpointer result = g_malloc (size);
1749 * free_list = g_list_prepend (free_list, result);
1754 * free_allocated_memory (void)
1757 * for (l = free_list; l; l = l->next);
1759 * g_list_free (free_list);
1767 * g_main_context_iteration (NULL, TRUE);
1768 * free_allocated_memory();
1772 * This works from an application, however, if you want to do the same
1773 * thing from a library, it gets more difficult, since you no longer
1774 * control the main loop. You might think you can simply use an idle
1775 * function to make the call to free_allocated_memory(), but that
1776 * doesn't work, since the idle function could be called from a
1777 * recursive callback. This can be fixed by using g_main_depth()
1781 * allocate_memory (gsize size)
1783 * FreeListBlock *block = g_new (FreeListBlock, 1);\
1784 * block->mem = g_malloc (size);
1785 * block->depth = g_main_depth ();
1786 * free_list = g_list_prepend (free_list, block);
1787 * return block->mem;
1791 * free_allocated_memory (void)
1795 * int depth = g_main_depth ();
1796 * for (l = free_list; l; );
1798 * GList *next = l->next;
1799 * FreeListBlock *block = l->data;
1800 * if (block->depth > depth)
1802 * g_free (block->mem);
1804 * free_list = g_list_delete_link (free_list, l);
1812 * There is a temptation to use g_main_depth() to solve
1813 * problems with reentrancy. For instance, while waiting for data
1814 * to be received from the network in response to a menu item,
1815 * the menu item might be selected again. It might seem that
1816 * one could make the menu item's callback return immediately
1817 * and do nothing if g_main_depth() returns a value greater than 1.
1818 * However, this should be avoided since the user then sees selecting
1819 * the menu item do nothing. Furthermore, you'll find yourself adding
1820 * these checks all over your code, since there are doubtless many,
1821 * many things that the user could do. Instead, you can use the
1822 * following techniques:
1827 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
1828 * the user from interacting with elements while the main
1829 * loop is recursing.
1834 * Avoid main loop recursion in situations where you can't handle
1835 * arbitrary callbacks. Instead, structure your code so that you
1836 * simply return to the main loop and then get called again when
1837 * there is more work to do.
1845 gint *depth = get_depth_pointer ();
1849 /* Temporarily remove all this source's file descriptors from the
1850 * poll(), so that if data comes available for one of the file descriptors
1851 * we don't continually spin in the poll()
1853 /* HOLDS: source->context's lock */
1855 block_source (GSource *source)
1859 g_return_if_fail (!SOURCE_BLOCKED (source));
1861 tmp_list = source->poll_fds;
1864 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
1865 tmp_list = tmp_list->next;
1869 /* HOLDS: source->context's lock */
1871 unblock_source (GSource *source)
1875 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
1876 g_return_if_fail (!SOURCE_DESTROYED (source));
1878 tmp_list = source->poll_fds;
1881 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
1882 tmp_list = tmp_list->next;
1886 /* HOLDS: context's lock */
1888 g_main_dispatch (GMainContext *context)
1890 gint *depth = get_depth_pointer ();
1893 for (i = 0; i < context->pending_dispatches->len; i++)
1895 GSource *source = context->pending_dispatches->pdata[i];
1897 context->pending_dispatches->pdata[i] = NULL;
1900 source->flags &= ~G_SOURCE_READY;
1902 if (!SOURCE_DESTROYED (source))
1904 gboolean was_in_call;
1905 gpointer user_data = NULL;
1906 GSourceFunc callback = NULL;
1907 GSourceCallbackFuncs *cb_funcs;
1909 gboolean need_destroy;
1911 gboolean (*dispatch) (GSource *,
1915 dispatch = source->source_funcs->dispatch;
1916 cb_funcs = source->callback_funcs;
1917 cb_data = source->callback_data;
1920 cb_funcs->ref (cb_data);
1922 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
1923 block_source (source);
1925 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
1926 source->flags |= G_HOOK_FLAG_IN_CALL;
1929 cb_funcs->get (cb_data, source, &callback, &user_data);
1931 UNLOCK_CONTEXT (context);
1934 need_destroy = ! dispatch (source,
1939 LOCK_CONTEXT (context);
1942 cb_funcs->unref (cb_data);
1945 source->flags &= ~G_HOOK_FLAG_IN_CALL;
1947 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
1948 !SOURCE_DESTROYED (source))
1949 unblock_source (source);
1951 /* Note: this depends on the fact that we can't switch
1952 * sources from one main context to another
1954 if (need_destroy && !SOURCE_DESTROYED (source))
1956 g_assert (source->context == context);
1957 g_source_destroy_internal (source, context, TRUE);
1961 SOURCE_UNREF (source, context);
1964 g_ptr_array_set_size (context->pending_dispatches, 0);
1967 /* Holds context's lock */
1968 static inline GSource *
1969 next_valid_source (GMainContext *context,
1972 GSource *new_source = source ? source->next : context->source_list;
1976 if (!SOURCE_DESTROYED (new_source))
1978 new_source->ref_count++;
1982 new_source = new_source->next;
1986 SOURCE_UNREF (source, context);
1992 * g_main_context_acquire:
1993 * @context: a #GMainContext
1995 * Tries to become the owner of the specified context.
1996 * If some other context is the owner of the context,
1997 * returns %FALSE immediately. Ownership is properly
1998 * recursive: the owner can require ownership again
1999 * and will release ownership when g_main_context_release()
2000 * is called as many times as g_main_context_acquire().
2002 * You must be the owner of a context before you
2003 * can call g_main_context_prepare(), g_main_context_query(),
2004 * g_main_context_check(), g_main_context_dispatch().
2006 * Return value: %TRUE if the operation succeeded, and
2007 * this thread is now the owner of @context.
2010 g_main_context_acquire (GMainContext *context)
2012 #ifdef G_THREADS_ENABLED
2013 gboolean result = FALSE;
2014 GThread *self = G_THREAD_SELF;
2016 if (context == NULL)
2017 context = g_main_context_default ();
2019 LOCK_CONTEXT (context);
2021 if (!context->owner)
2023 context->owner = self;
2024 g_assert (context->owner_count == 0);
2027 if (context->owner == self)
2029 context->owner_count++;
2033 UNLOCK_CONTEXT (context);
2036 #else /* !G_THREADS_ENABLED */
2038 #endif /* G_THREADS_ENABLED */
2042 * g_main_context_release:
2043 * @context: a #GMainContext
2045 * Releases ownership of a context previously acquired by this thread
2046 * with g_main_context_acquire(). If the context was acquired multiple
2047 * times, the only release ownership when g_main_context_release()
2048 * is called as many times as it was acquired.
2051 g_main_context_release (GMainContext *context)
2053 #ifdef G_THREADS_ENABLED
2054 if (context == NULL)
2055 context = g_main_context_default ();
2057 LOCK_CONTEXT (context);
2059 context->owner_count--;
2060 if (context->owner_count == 0)
2062 context->owner = NULL;
2064 if (context->waiters)
2066 GMainWaiter *waiter = context->waiters->data;
2067 gboolean loop_internal_waiter =
2068 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
2069 context->waiters = g_slist_delete_link (context->waiters,
2071 if (!loop_internal_waiter)
2072 g_mutex_lock (waiter->mutex);
2074 g_cond_signal (waiter->cond);
2076 if (!loop_internal_waiter)
2077 g_mutex_unlock (waiter->mutex);
2081 UNLOCK_CONTEXT (context);
2082 #endif /* G_THREADS_ENABLED */
2086 * g_main_context_wait:
2087 * @context: a #GMainContext
2088 * @cond: a condition variable
2089 * @mutex: a mutex, currently held
2091 * Tries to become the owner of the specified context,
2092 * as with g_main_context_acquire(). But if another thread
2093 * is the owner, atomically drop @mutex and wait on @cond until
2094 * that owner releases ownership or until @cond is signaled, then
2095 * try again (once) to become the owner.
2097 * Return value: %TRUE if the operation succeeded, and
2098 * this thread is now the owner of @context.
2101 g_main_context_wait (GMainContext *context,
2105 #ifdef G_THREADS_ENABLED
2106 gboolean result = FALSE;
2107 GThread *self = G_THREAD_SELF;
2108 gboolean loop_internal_waiter;
2110 if (context == NULL)
2111 context = g_main_context_default ();
2113 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2115 if (!loop_internal_waiter)
2116 LOCK_CONTEXT (context);
2118 if (context->owner && context->owner != self)
2123 waiter.mutex = mutex;
2125 context->waiters = g_slist_append (context->waiters, &waiter);
2127 if (!loop_internal_waiter)
2128 UNLOCK_CONTEXT (context);
2129 g_cond_wait (cond, mutex);
2130 if (!loop_internal_waiter)
2131 LOCK_CONTEXT (context);
2133 context->waiters = g_slist_remove (context->waiters, &waiter);
2136 if (!context->owner)
2138 context->owner = self;
2139 g_assert (context->owner_count == 0);
2142 if (context->owner == self)
2144 context->owner_count++;
2148 if (!loop_internal_waiter)
2149 UNLOCK_CONTEXT (context);
2152 #else /* !G_THREADS_ENABLED */
2154 #endif /* G_THREADS_ENABLED */
2158 * g_main_context_prepare:
2159 * @context: a #GMainContext
2160 * @priority: location to store priority of highest priority
2161 * source already ready.
2163 * Prepares to poll sources within a main loop. The resulting information
2164 * for polling is determined by calling g_main_context_query ().
2166 * Return value: %TRUE if some source is ready to be dispatched
2170 g_main_context_prepare (GMainContext *context,
2175 gint current_priority = G_MAXINT;
2178 if (context == NULL)
2179 context = g_main_context_default ();
2181 LOCK_CONTEXT (context);
2183 context->time_is_current = FALSE;
2185 if (context->in_check_or_prepare)
2187 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2188 "prepare() member.");
2189 UNLOCK_CONTEXT (context);
2193 #ifdef G_THREADS_ENABLED
2194 if (context->poll_waiting)
2196 g_warning("g_main_context_prepare(): main loop already active in another thread");
2197 UNLOCK_CONTEXT (context);
2201 context->poll_waiting = TRUE;
2202 #endif /* G_THREADS_ENABLED */
2205 /* If recursing, finish up current dispatch, before starting over */
2206 if (context->pending_dispatches)
2209 g_main_dispatch (context, ¤t_time);
2211 UNLOCK_CONTEXT (context);
2216 /* If recursing, clear list of pending dispatches */
2218 for (i = 0; i < context->pending_dispatches->len; i++)
2220 if (context->pending_dispatches->pdata[i])
2221 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2223 g_ptr_array_set_size (context->pending_dispatches, 0);
2225 /* Prepare all sources */
2227 context->timeout = -1;
2229 source = next_valid_source (context, NULL);
2232 gint source_timeout = -1;
2234 if ((n_ready > 0) && (source->priority > current_priority))
2236 SOURCE_UNREF (source, context);
2239 if (SOURCE_BLOCKED (source))
2242 if (!(source->flags & G_SOURCE_READY))
2245 gboolean (*prepare) (GSource *source,
2248 prepare = source->source_funcs->prepare;
2249 context->in_check_or_prepare++;
2250 UNLOCK_CONTEXT (context);
2252 result = (*prepare) (source, &source_timeout);
2254 LOCK_CONTEXT (context);
2255 context->in_check_or_prepare--;
2258 source->flags |= G_SOURCE_READY;
2261 if (source->flags & G_SOURCE_READY)
2264 current_priority = source->priority;
2265 context->timeout = 0;
2268 if (source_timeout >= 0)
2270 if (context->timeout < 0)
2271 context->timeout = source_timeout;
2273 context->timeout = MIN (context->timeout, source_timeout);
2277 source = next_valid_source (context, source);
2280 UNLOCK_CONTEXT (context);
2283 *priority = current_priority;
2285 return (n_ready > 0);
2289 * g_main_context_query:
2290 * @context: a #GMainContext
2291 * @max_priority: maximum priority source to check
2292 * @timeout_: location to store timeout to be used in polling
2293 * @fds: location to store #GPollFD records that need to be polled.
2294 * @n_fds: length of @fds.
2296 * Determines information necessary to poll this main loop.
2298 * Return value: the number of records actually stored in @fds,
2299 * or, if more than @n_fds records need to be stored, the number
2300 * of records that need to be stored.
2303 g_main_context_query (GMainContext *context,
2312 LOCK_CONTEXT (context);
2314 pollrec = context->poll_records;
2316 while (pollrec && max_priority >= pollrec->priority)
2318 if (pollrec->fd->events)
2322 fds[n_poll].fd = pollrec->fd->fd;
2323 /* In direct contradiction to the Unix98 spec, IRIX runs into
2324 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2325 * flags in the events field of the pollfd while it should
2326 * just ignoring them. So we mask them out here.
2328 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2329 fds[n_poll].revents = 0;
2334 pollrec = pollrec->next;
2337 #ifdef G_THREADS_ENABLED
2338 context->poll_changed = FALSE;
2343 *timeout = context->timeout;
2345 context->time_is_current = FALSE;
2348 UNLOCK_CONTEXT (context);
2354 * g_main_context_check:
2355 * @context: a #GMainContext
2356 * @max_priority: the maximum numerical priority of sources to check
2357 * @fds: array of #GPollFD's that was passed to the last call to
2358 * g_main_context_query()
2359 * @n_fds: return value of g_main_context_query()
2361 * Passes the results of polling back to the main loop.
2363 * Return value: %TRUE if some sources are ready to be dispatched.
2366 g_main_context_check (GMainContext *context,
2376 LOCK_CONTEXT (context);
2378 if (context->in_check_or_prepare)
2380 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2381 "prepare() member.");
2382 UNLOCK_CONTEXT (context);
2386 #ifdef G_THREADS_ENABLED
2387 if (!context->poll_waiting)
2391 read (context->wake_up_pipe[0], &a, 1);
2395 context->poll_waiting = FALSE;
2397 /* If the set of poll file descriptors changed, bail out
2398 * and let the main loop rerun
2400 if (context->poll_changed)
2402 UNLOCK_CONTEXT (context);
2405 #endif /* G_THREADS_ENABLED */
2407 pollrec = context->poll_records;
2411 if (pollrec->fd->events)
2413 pollrec->fd->revents = fds[i].revents;
2416 pollrec = pollrec->next;
2419 source = next_valid_source (context, NULL);
2422 if ((n_ready > 0) && (source->priority > max_priority))
2424 SOURCE_UNREF (source, context);
2427 if (SOURCE_BLOCKED (source))
2430 if (!(source->flags & G_SOURCE_READY))
2433 gboolean (*check) (GSource *source);
2435 check = source->source_funcs->check;
2437 context->in_check_or_prepare++;
2438 UNLOCK_CONTEXT (context);
2440 result = (*check) (source);
2442 LOCK_CONTEXT (context);
2443 context->in_check_or_prepare--;
2446 source->flags |= G_SOURCE_READY;
2449 if (source->flags & G_SOURCE_READY)
2451 source->ref_count++;
2452 g_ptr_array_add (context->pending_dispatches, source);
2456 /* never dispatch sources with less priority than the first
2457 * one we choose to dispatch
2459 max_priority = source->priority;
2463 source = next_valid_source (context, source);
2466 UNLOCK_CONTEXT (context);
2472 * g_main_context_dispatch:
2473 * @context: a #GMainContext
2475 * Dispatches all pending sources.
2478 g_main_context_dispatch (GMainContext *context)
2480 LOCK_CONTEXT (context);
2482 if (context->pending_dispatches->len > 0)
2484 g_main_dispatch (context);
2487 UNLOCK_CONTEXT (context);
2490 /* HOLDS context lock */
2492 g_main_context_iterate (GMainContext *context,
2499 gboolean some_ready;
2500 gint nfds, allocated_nfds;
2501 GPollFD *fds = NULL;
2503 UNLOCK_CONTEXT (context);
2505 #ifdef G_THREADS_ENABLED
2506 if (!g_main_context_acquire (context))
2508 gboolean got_ownership;
2510 g_return_val_if_fail (g_thread_supported (), FALSE);
2515 LOCK_CONTEXT (context);
2518 context->cond = g_cond_new ();
2520 got_ownership = g_main_context_wait (context,
2522 g_static_mutex_get_mutex (&context->mutex));
2526 UNLOCK_CONTEXT (context);
2531 LOCK_CONTEXT (context);
2532 #endif /* G_THREADS_ENABLED */
2534 if (!context->cached_poll_array)
2536 context->cached_poll_array_size = context->n_poll_records;
2537 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2540 allocated_nfds = context->cached_poll_array_size;
2541 fds = context->cached_poll_array;
2543 UNLOCK_CONTEXT (context);
2545 g_main_context_prepare (context, &max_priority);
2547 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
2548 allocated_nfds)) > allocated_nfds)
2550 LOCK_CONTEXT (context);
2552 context->cached_poll_array_size = allocated_nfds = nfds;
2553 context->cached_poll_array = fds = g_new (GPollFD, nfds);
2554 UNLOCK_CONTEXT (context);
2560 g_main_context_poll (context, timeout, max_priority, fds, nfds);
2562 some_ready = g_main_context_check (context, max_priority, fds, nfds);
2565 g_main_context_dispatch (context);
2567 #ifdef G_THREADS_ENABLED
2568 g_main_context_release (context);
2569 #endif /* G_THREADS_ENABLED */
2571 LOCK_CONTEXT (context);
2577 * g_main_context_pending:
2578 * @context: a #GMainContext (if %NULL, the default context will be used)
2580 * Checks if any sources have pending events for the given context.
2582 * Return value: %TRUE if events are pending.
2585 g_main_context_pending (GMainContext *context)
2590 context = g_main_context_default();
2592 LOCK_CONTEXT (context);
2593 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
2594 UNLOCK_CONTEXT (context);
2600 * g_main_context_iteration:
2601 * @context: a #GMainContext (if %NULL, the default context will be used)
2602 * @may_block: whether the call may block.
2604 * Runs a single iteration for the given main loop. This involves
2605 * checking to see if any event sources are ready to be processed,
2606 * then if no events sources are ready and @may_block is %TRUE, waiting
2607 * for a source to become ready, then dispatching the highest priority
2608 * events sources that are ready. Note that even when @may_block is %TRUE,
2609 * it is still possible for g_main_context_iteration() to return
2610 * %FALSE, since the the wait may be interrupted for other
2611 * reasons than an event source becoming ready.
2613 * Return value: %TRUE if events were dispatched.
2616 g_main_context_iteration (GMainContext *context, gboolean may_block)
2621 context = g_main_context_default();
2623 LOCK_CONTEXT (context);
2624 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
2625 UNLOCK_CONTEXT (context);
2632 * @context: a #GMainContext (if %NULL, the default context will be used).
2633 * @is_running: set to %TRUE to indicate that the loop is running. This
2634 * is not very important since calling g_main_loop_run() will set this to
2637 * Creates a new #GMainLoop structure.
2639 * Return value: a new #GMainLoop.
2642 g_main_loop_new (GMainContext *context,
2643 gboolean is_running)
2648 context = g_main_context_default();
2650 g_main_context_ref (context);
2652 loop = g_new0 (GMainLoop, 1);
2653 loop->context = context;
2654 loop->is_running = is_running != FALSE;
2655 loop->ref_count = 1;
2662 * @loop: a #GMainLoop
2664 * Increases the reference count on a #GMainLoop object by one.
2666 * Return value: @loop
2669 g_main_loop_ref (GMainLoop *loop)
2671 g_return_val_if_fail (loop != NULL, NULL);
2672 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2674 g_atomic_int_inc (&loop->ref_count);
2680 * g_main_loop_unref:
2681 * @loop: a #GMainLoop
2683 * Decreases the reference count on a #GMainLoop object by one. If
2684 * the result is zero, free the loop and free all associated memory.
2687 g_main_loop_unref (GMainLoop *loop)
2689 g_return_if_fail (loop != NULL);
2690 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2692 if (!g_atomic_int_dec_and_test (&loop->ref_count))
2695 g_main_context_unref (loop->context);
2701 * @loop: a #GMainLoop
2703 * Runs a main loop until g_main_loop_quit() is called on the loop.
2704 * If this is called for the thread of the loop's #GMainContext,
2705 * it will process events from the loop, otherwise it will
2709 g_main_loop_run (GMainLoop *loop)
2711 GThread *self = G_THREAD_SELF;
2713 g_return_if_fail (loop != NULL);
2714 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2716 #ifdef G_THREADS_ENABLED
2717 if (!g_main_context_acquire (loop->context))
2719 gboolean got_ownership = FALSE;
2721 /* Another thread owns this context */
2722 if (!g_thread_supported ())
2724 g_warning ("g_main_loop_run() was called from second thread but "
2725 "g_thread_init() was never called.");
2729 LOCK_CONTEXT (loop->context);
2731 g_atomic_int_inc (&loop->ref_count);
2733 if (!loop->is_running)
2734 loop->is_running = TRUE;
2736 if (!loop->context->cond)
2737 loop->context->cond = g_cond_new ();
2739 while (loop->is_running && !got_ownership)
2740 got_ownership = g_main_context_wait (loop->context,
2741 loop->context->cond,
2742 g_static_mutex_get_mutex (&loop->context->mutex));
2744 if (!loop->is_running)
2746 UNLOCK_CONTEXT (loop->context);
2748 g_main_context_release (loop->context);
2749 g_main_loop_unref (loop);
2753 g_assert (got_ownership);
2756 LOCK_CONTEXT (loop->context);
2757 #endif /* G_THREADS_ENABLED */
2759 if (loop->context->in_check_or_prepare)
2761 g_warning ("g_main_loop_run(): called recursively from within a source's "
2762 "check() or prepare() member, iteration not possible.");
2766 g_atomic_int_inc (&loop->ref_count);
2767 loop->is_running = TRUE;
2768 while (loop->is_running)
2769 g_main_context_iterate (loop->context, TRUE, TRUE, self);
2771 UNLOCK_CONTEXT (loop->context);
2773 #ifdef G_THREADS_ENABLED
2774 g_main_context_release (loop->context);
2775 #endif /* G_THREADS_ENABLED */
2777 g_main_loop_unref (loop);
2782 * @loop: a #GMainLoop
2784 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
2785 * for the loop will return.
2788 g_main_loop_quit (GMainLoop *loop)
2790 g_return_if_fail (loop != NULL);
2791 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2793 LOCK_CONTEXT (loop->context);
2794 loop->is_running = FALSE;
2795 g_main_context_wakeup_unlocked (loop->context);
2797 #ifdef G_THREADS_ENABLED
2798 if (loop->context->cond)
2799 g_cond_broadcast (loop->context->cond);
2800 #endif /* G_THREADS_ENABLED */
2802 UNLOCK_CONTEXT (loop->context);
2806 * g_main_loop_is_running:
2807 * @loop: a #GMainLoop.
2809 * Checks to see if the main loop is currently being run via g_main_loop_run().
2811 * Return value: %TRUE if the mainloop is currently being run.
2814 g_main_loop_is_running (GMainLoop *loop)
2816 g_return_val_if_fail (loop != NULL, FALSE);
2817 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
2819 return loop->is_running;
2823 * g_main_loop_get_context:
2824 * @loop: a #GMainLoop.
2826 * Returns the #GMainContext of @loop.
2828 * Return value: the #GMainContext of @loop
2831 g_main_loop_get_context (GMainLoop *loop)
2833 g_return_val_if_fail (loop != NULL, NULL);
2834 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2836 return loop->context;
2839 /* HOLDS: context's lock */
2841 g_main_context_poll (GMainContext *context,
2847 #ifdef G_MAIN_POLL_DEBUG
2853 GPollFunc poll_func;
2855 if (n_fds || timeout != 0)
2857 #ifdef G_MAIN_POLL_DEBUG
2858 g_print ("g_main_poll(%d) timeout: %d\n", n_fds, timeout);
2859 poll_timer = g_timer_new ();
2862 LOCK_CONTEXT (context);
2864 poll_func = context->poll_func;
2866 UNLOCK_CONTEXT (context);
2867 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
2870 g_warning ("poll(2) failed due to: %s.",
2871 g_strerror (errno));
2873 /* If g_poll () returns -1, it has already called g_warning() */
2877 #ifdef G_MAIN_POLL_DEBUG
2878 LOCK_CONTEXT (context);
2880 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
2883 g_timer_elapsed (poll_timer, NULL));
2884 g_timer_destroy (poll_timer);
2885 pollrec = context->poll_records;
2889 if (pollrec->fd->events)
2893 g_print (" [%d:", fds[i].fd);
2894 if (fds[i].revents & G_IO_IN)
2896 if (fds[i].revents & G_IO_OUT)
2898 if (fds[i].revents & G_IO_PRI)
2900 if (fds[i].revents & G_IO_ERR)
2902 if (fds[i].revents & G_IO_HUP)
2904 if (fds[i].revents & G_IO_NVAL)
2910 pollrec = pollrec->next;
2914 UNLOCK_CONTEXT (context);
2916 } /* if (n_fds || timeout != 0) */
2920 * g_main_context_add_poll:
2921 * @context: a #GMainContext (or %NULL for the default context)
2922 * @fd: a #GPollFD structure holding information about a file
2923 * descriptor to watch.
2924 * @priority: the priority for this file descriptor which should be
2925 * the same as the priority used for g_source_attach() to ensure that the
2926 * file descriptor is polled whenever the results may be needed.
2928 * Adds a file descriptor to the set of file descriptors polled for
2929 * this context. This will very seldomly be used directly. Instead
2930 * a typical event source will use g_source_add_poll() instead.
2933 g_main_context_add_poll (GMainContext *context,
2938 context = g_main_context_default ();
2940 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
2941 g_return_if_fail (fd);
2943 LOCK_CONTEXT (context);
2944 g_main_context_add_poll_unlocked (context, priority, fd);
2945 UNLOCK_CONTEXT (context);
2948 /* HOLDS: main_loop_lock */
2950 g_main_context_add_poll_unlocked (GMainContext *context,
2954 GPollRec *lastrec, *pollrec, *newrec;
2956 if (!context->poll_chunk)
2957 context->poll_chunk = g_mem_chunk_create (GPollRec, 32, G_ALLOC_ONLY);
2959 if (context->poll_free_list)
2961 newrec = context->poll_free_list;
2962 context->poll_free_list = newrec->next;
2965 newrec = g_chunk_new (GPollRec, context->poll_chunk);
2967 /* This file descriptor may be checked before we ever poll */
2970 newrec->priority = priority;
2973 pollrec = context->poll_records;
2974 while (pollrec && priority >= pollrec->priority)
2977 pollrec = pollrec->next;
2981 lastrec->next = newrec;
2983 context->poll_records = newrec;
2985 newrec->next = pollrec;
2987 context->n_poll_records++;
2989 #ifdef G_THREADS_ENABLED
2990 context->poll_changed = TRUE;
2992 /* Now wake up the main loop if it is waiting in the poll() */
2993 g_main_context_wakeup_unlocked (context);
2998 * g_main_context_remove_poll:
2999 * @context:a #GMainContext
3000 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3002 * Removes file descriptor from the set of file descriptors to be
3003 * polled for a particular context.
3006 g_main_context_remove_poll (GMainContext *context,
3010 context = g_main_context_default ();
3012 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3013 g_return_if_fail (fd);
3015 LOCK_CONTEXT (context);
3016 g_main_context_remove_poll_unlocked (context, fd);
3017 UNLOCK_CONTEXT (context);
3021 g_main_context_remove_poll_unlocked (GMainContext *context,
3024 GPollRec *pollrec, *lastrec;
3027 pollrec = context->poll_records;
3031 if (pollrec->fd == fd)
3033 if (lastrec != NULL)
3034 lastrec->next = pollrec->next;
3036 context->poll_records = pollrec->next;
3038 #ifdef ENABLE_GC_FRIENDLY
3040 #endif /* ENABLE_GC_FRIENDLY */
3042 pollrec->next = context->poll_free_list;
3043 context->poll_free_list = pollrec;
3045 context->n_poll_records--;
3049 pollrec = pollrec->next;
3052 #ifdef G_THREADS_ENABLED
3053 context->poll_changed = TRUE;
3055 /* Now wake up the main loop if it is waiting in the poll() */
3056 g_main_context_wakeup_unlocked (context);
3061 * g_source_get_current_time:
3062 * @source: a #GSource
3063 * @timeval: #GTimeVal structure in which to store current time.
3065 * Gets the "current time" to be used when checking
3066 * this source. The advantage of calling this function over
3067 * calling g_get_current_time() directly is that when
3068 * checking multiple sources, GLib can cache a single value
3069 * instead of having to repeatedly get the system time.
3072 g_source_get_current_time (GSource *source,
3075 GMainContext *context;
3077 g_return_if_fail (source->context != NULL);
3079 context = source->context;
3081 LOCK_CONTEXT (context);
3083 if (!context->time_is_current)
3085 g_get_current_time (&context->current_time);
3086 context->time_is_current = TRUE;
3089 *timeval = context->current_time;
3091 UNLOCK_CONTEXT (context);
3095 * g_main_context_set_poll_func:
3096 * @context: a #GMainContext
3097 * @func: the function to call to poll all file descriptors
3099 * Sets the function to use to handle polling of file descriptors. It
3100 * will be used instead of the poll() system call
3101 * (or GLib's replacement function, which is used where
3102 * poll() isn't available).
3104 * This function could possibly be used to integrate the GLib event
3105 * loop with an external event loop.
3108 g_main_context_set_poll_func (GMainContext *context,
3112 context = g_main_context_default ();
3114 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3116 LOCK_CONTEXT (context);
3119 context->poll_func = func;
3123 context->poll_func = (GPollFunc) poll;
3125 context->poll_func = (GPollFunc) g_poll;
3129 UNLOCK_CONTEXT (context);
3133 * g_main_context_get_poll_func:
3134 * @context: a #GMainContext
3136 * Gets the poll function set by g_main_context_set_poll_func().
3138 * Return value: the poll function
3141 g_main_context_get_poll_func (GMainContext *context)
3146 context = g_main_context_default ();
3148 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3150 LOCK_CONTEXT (context);
3151 result = context->poll_func;
3152 UNLOCK_CONTEXT (context);
3157 /* HOLDS: context's lock */
3158 /* Wake the main loop up from a poll() */
3160 g_main_context_wakeup_unlocked (GMainContext *context)
3162 #ifdef G_THREADS_ENABLED
3163 if (g_thread_supported() && context->poll_waiting)
3165 context->poll_waiting = FALSE;
3167 write (context->wake_up_pipe[1], "A", 1);
3169 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
3176 * g_main_context_wakeup:
3177 * @context: a #GMainContext
3179 * If @context is currently waiting in a poll(), interrupt
3180 * the poll(), and continue the iteration process.
3183 g_main_context_wakeup (GMainContext *context)
3186 context = g_main_context_default ();
3188 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3190 LOCK_CONTEXT (context);
3191 g_main_context_wakeup_unlocked (context);
3192 UNLOCK_CONTEXT (context);
3198 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3199 GTimeVal *current_time)
3201 guint seconds = timeout_source->interval / 1000;
3202 guint msecs = timeout_source->interval - seconds * 1000;
3204 timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
3205 timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
3206 if (timeout_source->expiration.tv_usec >= 1000000)
3208 timeout_source->expiration.tv_usec -= 1000000;
3209 timeout_source->expiration.tv_sec++;
3214 g_timeout_prepare (GSource *source,
3219 GTimeVal current_time;
3221 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3223 g_source_get_current_time (source, ¤t_time);
3225 sec = timeout_source->expiration.tv_sec - current_time.tv_sec;
3226 msec = (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000;
3228 /* We do the following in a rather convoluted fashion to deal with
3229 * the fact that we don't have an integral type big enough to hold
3230 * the difference of two timevals in millseconds.
3232 if (sec < 0 || (sec == 0 && msec < 0))
3236 glong interval_sec = timeout_source->interval / 1000;
3237 glong interval_msec = timeout_source->interval % 1000;
3245 if (sec > interval_sec ||
3246 (sec == interval_sec && msec > interval_msec))
3248 /* The system time has been set backwards, so we
3249 * reset the expiration time to now + timeout_source->interval;
3250 * this at least avoids hanging for long periods of time.
3252 g_timeout_set_expiration (timeout_source, ¤t_time);
3253 msec = MIN (G_MAXINT, timeout_source->interval);
3257 msec = MIN (G_MAXINT, (guint)msec + 1000 * (guint)sec);
3261 *timeout = (gint)msec;
3267 g_timeout_check (GSource *source)
3269 GTimeVal current_time;
3270 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3272 g_source_get_current_time (source, ¤t_time);
3274 return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
3275 ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
3276 (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
3280 g_timeout_dispatch (GSource *source,
3281 GSourceFunc callback,
3284 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3288 g_warning ("Timeout source dispatched without callback\n"
3289 "You must call g_source_set_callback().");
3293 if (callback (user_data))
3295 GTimeVal current_time;
3297 g_source_get_current_time (source, ¤t_time);
3298 g_timeout_set_expiration (timeout_source, ¤t_time);
3307 * g_timeout_source_new:
3308 * @interval: the timeout interval in milliseconds.
3310 * Creates a new timeout source.
3312 * The source will not initially be associated with any #GMainContext
3313 * and must be added to one with g_source_attach() before it will be
3316 * Return value: the newly-created timeout source
3319 g_timeout_source_new (guint interval)
3321 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3322 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3323 GTimeVal current_time;
3325 timeout_source->interval = interval;
3327 g_get_current_time (¤t_time);
3328 g_timeout_set_expiration (timeout_source, ¤t_time);
3334 * g_timeout_add_full:
3335 * @priority: the priority of the idle source. Typically this will be in the
3336 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3337 * @interval: the time between calls to the function, in milliseconds
3338 * (1/1000ths of a second)
3339 * @function: function to call
3340 * @data: data to pass to @function
3341 * @notify: function to call when the idle is removed, or %NULL
3343 * Sets a function to be called at regular intervals, with the given
3344 * priority. The function is called repeatedly until it returns
3345 * %FALSE, at which point the timeout is automatically destroyed and
3346 * the function will not be called again. The @notify function is
3347 * called when the timeout is destroyed. The first call to the
3348 * function will be at the end of the first @interval.
3350 * Note that timeout functions may be delayed, due to the processing of other
3351 * event sources. Thus they should not be relied on for precise timing.
3352 * After each call to the timeout function, the time of the next
3353 * timeout is recalculated based on the current time and the given interval
3354 * (it does not try to 'catch up' time lost in delays).
3356 * Return value: the id of event source.
3359 g_timeout_add_full (gint priority,
3361 GSourceFunc function,
3363 GDestroyNotify notify)
3368 g_return_val_if_fail (function != NULL, 0);
3370 source = g_timeout_source_new (interval);
3372 if (priority != G_PRIORITY_DEFAULT)
3373 g_source_set_priority (source, priority);
3375 g_source_set_callback (source, function, data, notify);
3376 id = g_source_attach (source, NULL);
3377 g_source_unref (source);
3384 * @interval: the time between calls to the function, in milliseconds
3385 * (1/1000ths of a second)
3386 * @function: function to call
3387 * @data: data to pass to @function
3389 * Sets a function to be called at regular intervals, with the default
3390 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
3391 * until it returns %FALSE, at which point the timeout is automatically
3392 * destroyed and the function will not be called again. The first call
3393 * to the function will be at the end of the first @interval.
3395 * Note that timeout functions may be delayed, due to the processing of other
3396 * event sources. Thus they should not be relied on for precise timing.
3397 * After each call to the timeout function, the time of the next
3398 * timeout is recalculated based on the current time and the given interval
3399 * (it does not try to 'catch up' time lost in delays).
3401 * Return value: the id of event source.
3404 g_timeout_add (guint32 interval,
3405 GSourceFunc function,
3408 return g_timeout_add_full (G_PRIORITY_DEFAULT,
3409 interval, function, data, NULL);
3412 /* Child watch functions */
3417 g_child_watch_prepare (GSource *source,
3426 g_child_watch_check (GSource *source)
3428 GChildWatchSource *child_watch_source;
3429 gboolean child_exited;
3431 child_watch_source = (GChildWatchSource *) source;
3433 child_exited = child_watch_source->poll.revents & G_IO_IN;
3440 * Note: We do _not_ check for the special value of STILL_ACTIVE
3441 * since we know that the process has exited and doing so runs into
3442 * problems if the child process "happens to return STILL_ACTIVE(259)"
3443 * as Microsoft's Platform SDK puts it.
3445 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
3447 gchar *emsg = g_win32_error_message (GetLastError ());
3448 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
3451 child_watch_source->child_status = -1;
3454 child_watch_source->child_status = child_status;
3457 return child_exited;
3460 #else /* G_OS_WIN32 */
3463 check_for_child_exited (GSource *source)
3465 GChildWatchSource *child_watch_source;
3468 /* protect against another SIGCHLD in the middle of this call */
3469 count = child_watch_count;
3471 child_watch_source = (GChildWatchSource *) source;
3473 if (child_watch_source->child_exited)
3476 if (child_watch_source->count < count)
3480 if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
3482 child_watch_source->child_status = child_status;
3483 child_watch_source->child_exited = TRUE;
3485 child_watch_source->count = count;
3488 return child_watch_source->child_exited;
3492 g_child_watch_prepare (GSource *source,
3495 GChildWatchSource *child_watch_source;
3498 child_watch_source = (GChildWatchSource *) source;
3500 return check_for_child_exited (source);
3505 g_child_watch_check (GSource *source)
3507 GChildWatchSource *child_watch_source;
3509 child_watch_source = (GChildWatchSource *) source;
3511 return check_for_child_exited (source);
3514 #endif /* G_OS_WIN32 */
3517 g_child_watch_dispatch (GSource *source,
3518 GSourceFunc callback,
3521 GChildWatchSource *child_watch_source;
3522 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
3524 child_watch_source = (GChildWatchSource *) source;
3528 g_warning ("Child watch source dispatched without callback\n"
3529 "You must call g_source_set_callback().");
3533 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
3535 /* We never keep a child watch source around as the child is gone */
3542 g_child_watch_signal_handler (int signum)
3544 child_watch_count ++;
3546 if (child_watch_init_state == CHILD_WATCH_INITIALIZED_THREADED)
3548 write (child_watch_wake_up_pipe[1], "B", 1);
3552 /* We count on the signal interrupting the poll in the same thread.
3558 g_child_watch_source_init_single (void)
3560 struct sigaction action;
3562 g_assert (! g_thread_supported());
3563 g_assert (child_watch_init_state == CHILD_WATCH_UNINITIALIZED);
3565 child_watch_init_state = CHILD_WATCH_INITIALIZED_SINGLE;
3567 action.sa_handler = g_child_watch_signal_handler;
3568 sigemptyset (&action.sa_mask);
3569 action.sa_flags = SA_NOCLDSTOP;
3570 sigaction (SIGCHLD, &action, NULL);
3574 child_watch_helper_thread (gpointer data)
3577 GPollFunc poll_func;
3580 poll_func = (GPollFunc)poll;
3585 fds.fd = child_watch_wake_up_pipe[0];
3586 fds.events = G_IO_IN;
3593 read (child_watch_wake_up_pipe[0], b, 20);
3595 /* We were woken up. Wake up all other contexts in all other threads */
3596 G_LOCK (main_context_list);
3597 for (list = main_context_list; list; list = list->next)
3599 GMainContext *context;
3601 context = list->data;
3602 if (g_atomic_int_get (&context->ref_count) > 0)
3603 /* Due to racing conditions we can find ref_count == 0, in
3604 * that case, however, the context is still not destroyed
3605 * and no poll can be active, otherwise the ref_count
3607 g_main_context_wakeup (context);
3609 G_UNLOCK (main_context_list);
3615 g_child_watch_source_init_multi_threaded (void)
3617 GError *error = NULL;
3618 struct sigaction action;
3620 g_assert (g_thread_supported());
3622 if (pipe (child_watch_wake_up_pipe) < 0)
3623 g_error ("Cannot create wake up pipe: %s\n", g_strerror (errno));
3624 fcntl (child_watch_wake_up_pipe[1], F_SETFL, O_NONBLOCK | fcntl (child_watch_wake_up_pipe[1], F_GETFL));
3626 /* We create a helper thread that polls on the wakeup pipe indefinitely */
3627 /* FIXME: Think this through for races */
3628 if (g_thread_create (child_watch_helper_thread, NULL, FALSE, &error) == NULL)
3629 g_error ("Cannot create a thread to monitor child exit status: %s\n", error->message);
3630 child_watch_init_state = CHILD_WATCH_INITIALIZED_THREADED;
3632 action.sa_handler = g_child_watch_signal_handler;
3633 sigemptyset (&action.sa_mask);
3634 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
3635 sigaction (SIGCHLD, &action, NULL);
3639 g_child_watch_source_init_promote_single_to_threaded (void)
3641 g_child_watch_source_init_multi_threaded ();
3645 g_child_watch_source_init (void)
3647 if (g_thread_supported())
3649 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
3650 g_child_watch_source_init_multi_threaded ();
3651 else if (child_watch_init_state == CHILD_WATCH_INITIALIZED_SINGLE)
3652 g_child_watch_source_init_promote_single_to_threaded ();
3656 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
3657 g_child_watch_source_init_single ();
3661 #endif /* !G_OS_WIN32 */
3664 * g_child_watch_source_new:
3665 * @pid: process id of a child process to watch. On Windows, a HANDLE
3666 * for the process to watch (which actually doesn't have to be a child).
3668 * Creates a new child_watch source.
3670 * The source will not initially be associated with any #GMainContext
3671 * and must be added to one with g_source_attach() before it will be
3674 * Note that on platforms where #GPid must be explicitely closed
3675 * (see g_spawn_close_pid()) @pid must not be closed while the
3676 * source is still active. Typically, you will want to call
3677 * g_spawn_close_pid() in the callback function for the source.
3679 * Note further that using g_child_watch_source_new() is not
3680 * compatible with calling <literal>waitpid(-1)</literal> in
3681 * the application. Calling waitpid() for individual pids will
3684 * Return value: the newly-created child watch source
3689 g_child_watch_source_new (GPid pid)
3691 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
3692 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
3695 child_watch_source->poll.fd = (int)pid;
3696 child_watch_source->poll.events = G_IO_IN;
3698 g_source_add_poll (source, &child_watch_source->poll);
3699 #else /* G_OS_WIN32 */
3700 g_child_watch_source_init ();
3701 #endif /* G_OS_WIN32 */
3703 child_watch_source->pid = pid;
3709 * g_child_watch_add_full:
3710 * @priority: the priority of the idle source. Typically this will be in the
3711 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3712 * @pid: process id of a child process to watch
3713 * @function: function to call
3714 * @data: data to pass to @function
3715 * @notify: function to call when the idle is removed, or %NULL
3717 * Sets a function to be called when the child indicated by @pid exits, at a
3718 * default priority, #G_PRIORITY_DEFAULT.
3720 * Note that on platforms where #GPid must be explicitely closed
3721 * (see g_spawn_close_pid()) @pid must not be closed while the
3722 * source is still active. Typically, you will want to call
3723 * g_spawn_close_pid() in the callback function for the source.
3725 * GLib supports only a single callback per process id.
3727 * Return value: the id of event source.
3732 g_child_watch_add_full (gint priority,
3734 GChildWatchFunc function,
3736 GDestroyNotify notify)
3741 g_return_val_if_fail (function != NULL, 0);
3743 source = g_child_watch_source_new (pid);
3745 if (priority != G_PRIORITY_DEFAULT)
3746 g_source_set_priority (source, priority);
3748 g_source_set_callback (source, (GSourceFunc) function, data, notify);
3749 id = g_source_attach (source, NULL);
3750 g_source_unref (source);
3756 * g_child_watch_add:
3757 * @pid: process id of a child process to watch
3758 * @function: function to call
3759 * @data: data to pass to @function
3761 * Sets a function to be called when the child indicated by @pid exits, at a
3762 * default priority, #G_PRIORITY_DEFAULT.
3764 * Note that on platforms where #GPid must be explicitely closed
3765 * (see g_spawn_close_pid()) @pid must not be closed while the
3766 * source is still active. Typically, you will want to call
3767 * g_spawn_close_pid() in the callback function for the source.
3769 * GLib supports only a single callback per process id.
3771 * Return value: the id of event source.
3776 g_child_watch_add (GPid pid,
3777 GChildWatchFunc function,
3780 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
3784 /* Idle functions */
3787 g_idle_prepare (GSource *source,
3796 g_idle_check (GSource *source)
3802 g_idle_dispatch (GSource *source,
3803 GSourceFunc callback,
3808 g_warning ("Idle source dispatched without callback\n"
3809 "You must call g_source_set_callback().");
3813 return callback (user_data);
3817 * g_idle_source_new:
3819 * Creates a new idle source.
3821 * The source will not initially be associated with any #GMainContext
3822 * and must be added to one with g_source_attach() before it will be
3823 * executed. Note that the default priority for idle sources is
3824 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
3825 * have a default priority of %G_PRIORITY_DEFAULT.
3827 * Return value: the newly-created idle source
3830 g_idle_source_new (void)
3834 source = g_source_new (&g_idle_funcs, sizeof (GSource));
3835 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
3842 * @priority: the priority of the idle source. Typically this will be in the
3843 * range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3844 * @function: function to call
3845 * @data: data to pass to @function
3846 * @notify: function to call when the idle is removed, or %NULL
3848 * Adds a function to be called whenever there are no higher priority
3849 * events pending. If the function returns %FALSE it is automatically
3850 * removed from the list of event sources and will not be called again.
3852 * Return value: the id of the event source.
3855 g_idle_add_full (gint priority,
3856 GSourceFunc function,
3858 GDestroyNotify notify)
3863 g_return_val_if_fail (function != NULL, 0);
3865 source = g_idle_source_new ();
3867 if (priority != G_PRIORITY_DEFAULT_IDLE)
3868 g_source_set_priority (source, priority);
3870 g_source_set_callback (source, function, data, notify);
3871 id = g_source_attach (source, NULL);
3872 g_source_unref (source);
3879 * @function: function to call
3880 * @data: data to pass to @function.
3882 * Adds a function to be called whenever there are no higher priority
3883 * events pending to the default main loop. The function is given the
3884 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
3885 * returns %FALSE it is automatically removed from the list of event
3886 * sources and will not be called again.
3888 * Return value: the id of the event source.
3891 g_idle_add (GSourceFunc function,
3894 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
3898 * g_idle_remove_by_data:
3899 * @data: the data for the idle source's callback.
3901 * Removes the idle function with the given data.
3903 * Return value: %TRUE if an idle source was found and removed.
3906 g_idle_remove_by_data (gpointer data)
3908 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
3911 #define __G_MAIN_C__
3912 #include "galiasdef.c"