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)
205 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
206 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
208 #define SOURCE_UNREF(source, context) \
210 if ((source)->ref_count > 1) \
211 (source)->ref_count--; \
213 g_source_unref_internal ((source), (context), TRUE); \
217 /* Forward declarations */
219 static void g_source_unref_internal (GSource *source,
220 GMainContext *context,
222 static void g_source_destroy_internal (GSource *source,
223 GMainContext *context,
225 static void g_main_context_poll (GMainContext *context,
230 static void g_main_context_add_poll_unlocked (GMainContext *context,
233 static void g_main_context_remove_poll_unlocked (GMainContext *context,
235 static void g_main_context_wakeup_unlocked (GMainContext *context);
237 static gboolean g_timeout_prepare (GSource *source,
239 static gboolean g_timeout_check (GSource *source);
240 static gboolean g_timeout_dispatch (GSource *source,
241 GSourceFunc callback,
243 static gboolean g_child_watch_prepare (GSource *source,
245 static gboolean g_child_watch_check (GSource *source);
246 static gboolean g_child_watch_dispatch (GSource *source,
247 GSourceFunc callback,
249 static gboolean g_idle_prepare (GSource *source,
251 static gboolean g_idle_check (GSource *source);
252 static gboolean g_idle_dispatch (GSource *source,
253 GSourceFunc callback,
256 G_LOCK_DEFINE_STATIC (main_loop);
257 static GMainContext *default_main_context;
258 static GSList *main_contexts_without_pipe = NULL;
261 /* Child status monitoring code */
263 CHILD_WATCH_UNINITIALIZED,
264 CHILD_WATCH_INITIALIZED_SINGLE,
265 CHILD_WATCH_INITIALIZED_THREADED
267 static gint child_watch_init_state = CHILD_WATCH_UNINITIALIZED;
268 static gint child_watch_count = 0;
269 static gint child_watch_wake_up_pipe[2] = {0, 0};
270 #endif /* !G_OS_WIN32 */
271 G_LOCK_DEFINE_STATIC (main_context_list);
272 static GSList *main_context_list = NULL;
274 GSourceFuncs g_timeout_funcs =
282 GSourceFuncs g_child_watch_funcs =
284 g_child_watch_prepare,
286 g_child_watch_dispatch,
290 GSourceFuncs g_idle_funcs =
299 /* SunOS has poll, but doesn't provide a prototype. */
300 # if defined (sun) && !defined (__SVR4)
301 extern gint poll (GPollFD *ufds, guint nfsd, gint timeout);
303 #else /* !HAVE_POLL */
308 g_poll (GPollFD *fds,
312 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
313 gboolean poll_msgs = FALSE;
320 for (f = fds; f < &fds[nfds]; ++f)
323 if (f->fd == G_WIN32_MSG_HANDLE)
325 else if (nhandles == MAXIMUM_WAIT_OBJECTS)
327 g_warning (G_STRLOC ": Too many handles to wait for!\n");
332 #ifdef G_MAIN_POLL_DEBUG
333 g_print ("g_poll: waiting for %#x\n", f->fd);
335 handles[nhandles++] = (HANDLE) f->fd;
344 /* Waiting for messages, and maybe events
345 * -> First PeekMessage
347 #ifdef G_MAIN_POLL_DEBUG
348 g_print ("PeekMessage\n");
350 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
351 ready = WAIT_OBJECT_0 + nhandles;
356 /* Waiting just for messages */
357 if (timeout == INFINITE)
362 #ifdef G_MAIN_POLL_DEBUG
363 g_print ("WaitMessage\n");
367 gchar *emsg = g_win32_error_message (GetLastError ());
368 g_warning (G_STRLOC ": WaitMessage() failed: %s", emsg);
371 ready = WAIT_OBJECT_0 + nhandles;
373 else if (timeout == 0)
375 /* Waiting just for messages, zero timeout.
376 * If we got here, there was no message
378 ready = WAIT_TIMEOUT;
382 /* Waiting just for messages, some timeout
383 * -> Set a timer, wait for message,
384 * kill timer, use PeekMessage
386 timer = SetTimer (NULL, 0, timeout, NULL);
389 gchar *emsg = g_win32_error_message (GetLastError ());
390 g_warning (G_STRLOC ": SetTimer() failed: %s", emsg);
392 ready = WAIT_TIMEOUT;
396 #ifdef G_MAIN_POLL_DEBUG
397 g_print ("WaitMessage\n");
400 KillTimer (NULL, timer);
401 #ifdef G_MAIN_POLL_DEBUG
402 g_print ("PeekMessage\n");
404 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE)
405 && msg.message != WM_TIMER)
406 ready = WAIT_OBJECT_0;
408 ready = WAIT_TIMEOUT;
414 /* Wait for either message or event
415 * -> Use MsgWaitForMultipleObjects
417 #ifdef G_MAIN_POLL_DEBUG
418 g_print ("MsgWaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
420 ready = MsgWaitForMultipleObjects (nhandles, handles, FALSE,
421 timeout, QS_ALLINPUT);
423 if (ready == WAIT_FAILED)
425 gchar *emsg = g_win32_error_message (GetLastError ());
426 g_warning (G_STRLOC ": MsgWaitForMultipleObjects() failed: %s", emsg);
432 else if (nhandles == 0)
434 /* Wait for nothing (huh?) */
439 /* Wait for just events
440 * -> Use WaitForMultipleObjects
442 #ifdef G_MAIN_POLL_DEBUG
443 g_print ("WaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
445 ready = WaitForMultipleObjects (nhandles, handles, FALSE, timeout);
446 if (ready == WAIT_FAILED)
448 gchar *emsg = g_win32_error_message (GetLastError ());
449 g_warning (G_STRLOC ": WaitForMultipleObjects() failed: %s", emsg);
454 #ifdef G_MAIN_POLL_DEBUG
455 g_print ("wait returns %ld%s\n",
457 (ready == WAIT_FAILED ? " (WAIT_FAILED)" :
458 (ready == WAIT_TIMEOUT ? " (WAIT_TIMEOUT)" :
459 (poll_msgs && ready == WAIT_OBJECT_0 + nhandles ? " (msg)" : ""))));
461 for (f = fds; f < &fds[nfds]; ++f)
464 if (ready == WAIT_FAILED)
466 else if (ready == WAIT_TIMEOUT)
468 else if (poll_msgs && ready == WAIT_OBJECT_0 + nhandles)
470 for (f = fds; f < &fds[nfds]; ++f)
473 if (f->events & G_IO_IN)
474 if (f->fd == G_WIN32_MSG_HANDLE)
475 f->revents |= G_IO_IN;
478 #if 1 /* TEST_WITHOUT_THIS */
479 else if (ready >= WAIT_OBJECT_0 && ready < WAIT_OBJECT_0 + nhandles)
480 for (f = fds; f < &fds[nfds]; ++f)
482 if ((f->events & (G_IO_IN | G_IO_OUT))
483 && f->fd == (gint) handles[ready - WAIT_OBJECT_0])
485 if (f->events & G_IO_IN)
486 f->revents |= G_IO_IN;
488 f->revents |= G_IO_OUT;
489 #ifdef G_MAIN_POLL_DEBUG
490 g_print ("g_poll: got event %#x\n", f->fd);
493 ResetEvent ((HANDLE) f->fd);
502 #else /* !G_OS_WIN32 */
504 /* The following implementation of poll() comes from the GNU C Library.
505 * Copyright (C) 1994, 1996, 1997 Free Software Foundation, Inc.
508 #include <string.h> /* for bzero on BSD systems */
510 #ifdef HAVE_SYS_SELECT_H
511 #include <sys/select.h>
512 #endif /* HAVE_SYS_SELECT_H */
516 #endif /* G_OS_BEOS */
519 # define SELECT_MASK fd_set
520 #else /* !NO_FD_SET */
522 typedef long fd_mask;
525 # define SELECT_MASK void
527 # define SELECT_MASK int
528 # endif /* !_IBMR2 */
529 #endif /* !NO_FD_SET */
532 g_poll (GPollFD *fds,
537 SELECT_MASK rset, wset, xset;
546 for (f = fds; f < &fds[nfds]; ++f)
549 if (f->events & G_IO_IN)
550 FD_SET (f->fd, &rset);
551 if (f->events & G_IO_OUT)
552 FD_SET (f->fd, &wset);
553 if (f->events & G_IO_PRI)
554 FD_SET (f->fd, &xset);
555 if (f->fd > maxfd && (f->events & (G_IO_IN|G_IO_OUT|G_IO_PRI)))
559 tv.tv_sec = timeout / 1000;
560 tv.tv_usec = (timeout % 1000) * 1000;
562 ready = select (maxfd + 1, &rset, &wset, &xset,
563 timeout == -1 ? NULL : &tv);
565 for (f = fds; f < &fds[nfds]; ++f)
570 if (FD_ISSET (f->fd, &rset))
571 f->revents |= G_IO_IN;
572 if (FD_ISSET (f->fd, &wset))
573 f->revents |= G_IO_OUT;
574 if (FD_ISSET (f->fd, &xset))
575 f->revents |= G_IO_PRI;
582 #endif /* !G_OS_WIN32 */
584 #endif /* !HAVE_POLL */
587 * g_main_context_ref:
588 * @context: a #GMainContext
590 * Increases the reference count on a #GMainContext object by one.
593 g_main_context_ref (GMainContext *context)
595 g_return_if_fail (context != NULL);
596 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
598 g_atomic_int_inc (&context->ref_count);
601 /* If DISABLE_MEM_POOLS is defined, then freeing the
602 * mem chunk won't free the records, so we have to
603 * do it manually. The conditionalization here is
604 * an optimization; g_mem_chunk_free() is a no-op
605 * when DISABLE_MEM_POOLS is set.
607 #ifdef DISABLE_MEM_POOLS
609 poll_rec_list_free (GMainContext *context,
614 GPollRec *tmp_rec = list;
616 g_chunk_free (tmp_rec, context->poll_chunk);
619 #endif /* DISABLE_MEM_POOLS */
622 * g_main_context_unref:
623 * @context: a #GMainContext
625 * Decreases the reference count on a #GMainContext object by one. If
626 * the result is zero, free the context and free all associated memory.
629 g_main_context_unref (GMainContext *context)
632 g_return_if_fail (context != NULL);
633 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
635 if (!g_atomic_int_dec_and_test (&context->ref_count))
638 G_LOCK (main_context_list);
639 main_context_list = g_slist_remove (main_context_list, context);
640 G_UNLOCK (main_context_list);
642 source = context->source_list;
645 GSource *next = source->next;
646 g_source_destroy_internal (source, context, TRUE);
650 #ifdef G_THREADS_ENABLED
651 g_static_mutex_free (&context->mutex);
654 g_ptr_array_free (context->pending_dispatches, TRUE);
655 g_free (context->cached_poll_array);
657 #ifdef DISABLE_MEM_POLLS
658 poll_rec_list_free (context, context->poll_records);
659 poll_rec_list_free (context, context->poll_free_list);
660 #endif /* DISABLE_MEM_POOLS */
662 if (context->poll_chunk)
663 g_mem_chunk_destroy (context->poll_chunk);
665 #ifdef G_THREADS_ENABLED
666 if (g_thread_supported())
669 close (context->wake_up_pipe[0]);
670 close (context->wake_up_pipe[1]);
672 CloseHandle (context->wake_up_semaphore);
676 main_contexts_without_pipe = g_slist_remove (main_contexts_without_pipe,
683 #ifdef G_THREADS_ENABLED
685 g_main_context_init_pipe (GMainContext *context)
688 if (context->wake_up_pipe[0] != -1)
690 if (pipe (context->wake_up_pipe) < 0)
691 g_error ("Cannot create pipe main loop wake-up: %s\n",
694 context->wake_up_rec.fd = context->wake_up_pipe[0];
695 context->wake_up_rec.events = G_IO_IN;
697 if (context->wake_up_semaphore != NULL)
699 context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
700 if (context->wake_up_semaphore == NULL)
701 g_error ("Cannot create wake-up semaphore: %s",
702 g_win32_error_message (GetLastError ()));
703 context->wake_up_rec.fd = (gint) context->wake_up_semaphore;
704 context->wake_up_rec.events = G_IO_IN;
705 # ifdef G_MAIN_POLL_DEBUG
706 g_print ("wake-up semaphore: %#x\n", (guint) context->wake_up_semaphore);
709 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
713 _g_main_thread_init ()
715 GSList *curr = main_contexts_without_pipe;
718 g_main_context_init_pipe ((GMainContext *)curr->data);
721 g_slist_free (main_contexts_without_pipe);
722 main_contexts_without_pipe = NULL;
724 #endif /* G_THREADS_ENABLED */
727 * g_main_context_new:
729 * Creates a new #GMainContext strcuture
731 * Return value: the new #GMainContext
734 g_main_context_new ()
736 GMainContext *context = g_new0 (GMainContext, 1);
738 #ifdef G_THREADS_ENABLED
739 g_static_mutex_init (&context->mutex);
741 context->owner = NULL;
742 context->waiters = NULL;
745 context->wake_up_pipe[0] = -1;
746 context->wake_up_pipe[1] = -1;
748 context->wake_up_semaphore = NULL;
752 context->ref_count = 1;
754 context->next_id = 1;
756 context->source_list = NULL;
759 context->poll_func = (GPollFunc)poll;
761 context->poll_func = g_poll;
764 context->cached_poll_array = NULL;
765 context->cached_poll_array_size = 0;
767 context->pending_dispatches = g_ptr_array_new ();
769 context->time_is_current = FALSE;
771 #ifdef G_THREADS_ENABLED
772 if (g_thread_supported ())
773 g_main_context_init_pipe (context);
775 main_contexts_without_pipe = g_slist_prepend (main_contexts_without_pipe,
779 G_LOCK (main_context_list);
780 main_context_list = g_slist_append (main_context_list, context);
781 G_UNLOCK (main_context_list);
787 * g_main_context_default:
789 * Returns the default main context. This is the main context used
790 * for main loop functions when a main loop is not explicitly
793 * Return value: the default main context.
796 g_main_context_default (void)
802 if (!default_main_context)
803 default_main_context = g_main_context_new ();
805 G_UNLOCK (main_loop);
807 return default_main_context;
810 /* Hooks for adding to the main loop */
814 * @source_funcs: structure containing functions that implement
815 * the sources behavior.
816 * @struct_size: size of the #GSource structure to create.
818 * Creates a new #GSource structure. The size is specified to
819 * allow creating structures derived from #GSource that contain
820 * additional data. The size passed in must be at least
821 * <literal>sizeof (GSource)</literal>.
823 * The source will not initially be associated with any #GMainContext
824 * and must be added to one with g_source_attach() before it will be
827 * Return value: the newly-created #GSource.
830 g_source_new (GSourceFuncs *source_funcs,
835 g_return_val_if_fail (source_funcs != NULL, NULL);
836 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
838 source = (GSource*) g_malloc0 (struct_size);
840 source->source_funcs = source_funcs;
841 source->ref_count = 1;
843 source->priority = G_PRIORITY_DEFAULT;
845 source->flags = G_HOOK_FLAG_ACTIVE;
847 /* NULL/0 initialization for all other fields */
852 /* Holds context's lock
855 g_source_list_add (GSource *source,
856 GMainContext *context)
858 GSource *tmp_source, *last_source;
861 tmp_source = context->source_list;
862 while (tmp_source && tmp_source->priority <= source->priority)
864 last_source = tmp_source;
865 tmp_source = tmp_source->next;
868 source->next = tmp_source;
870 tmp_source->prev = source;
872 source->prev = last_source;
874 last_source->next = source;
876 context->source_list = source;
879 /* Holds context's lock
882 g_source_list_remove (GSource *source,
883 GMainContext *context)
886 source->prev->next = source->next;
888 context->source_list = source->next;
891 source->next->prev = source->prev;
899 * @source: a #GSource
900 * @context: a #GMainContext (if %NULL, the default context will be used)
902 * Adds a #GSource to a @context so that it will be executed within
905 * Return value: the ID for the source within the #GMainContext
908 g_source_attach (GSource *source,
909 GMainContext *context)
914 g_return_val_if_fail (source->context == NULL, 0);
915 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
918 context = g_main_context_default ();
920 LOCK_CONTEXT (context);
922 source->context = context;
923 result = source->source_id = context->next_id++;
926 g_source_list_add (source, context);
928 tmp_list = source->poll_fds;
931 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
932 tmp_list = tmp_list->next;
935 #ifdef G_THREADS_ENABLED
936 /* Now wake up the main loop if it is waiting in the poll() */
937 g_main_context_wakeup_unlocked (context);
940 UNLOCK_CONTEXT (context);
946 g_source_destroy_internal (GSource *source,
947 GMainContext *context,
951 LOCK_CONTEXT (context);
953 if (!SOURCE_DESTROYED (source))
956 gpointer old_cb_data;
957 GSourceCallbackFuncs *old_cb_funcs;
959 source->flags &= ~G_HOOK_FLAG_ACTIVE;
961 old_cb_data = source->callback_data;
962 old_cb_funcs = source->callback_funcs;
964 source->callback_data = NULL;
965 source->callback_funcs = NULL;
969 UNLOCK_CONTEXT (context);
970 old_cb_funcs->unref (old_cb_data);
971 LOCK_CONTEXT (context);
974 if (!SOURCE_BLOCKED (source))
976 tmp_list = source->poll_fds;
979 g_main_context_remove_poll_unlocked (context, tmp_list->data);
980 tmp_list = tmp_list->next;
984 g_source_unref_internal (source, context, TRUE);
988 UNLOCK_CONTEXT (context);
993 * @source: a #GSource
995 * Removes a source from its #GMainContext, if any, and mark it as
996 * destroyed. The source cannot be subsequently added to another
1000 g_source_destroy (GSource *source)
1002 GMainContext *context;
1004 g_return_if_fail (source != NULL);
1006 context = source->context;
1009 g_source_destroy_internal (source, context, FALSE);
1011 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1016 * @source: a #GSource
1018 * Returns the numeric ID for a particular source. The ID of a source
1019 * is unique within a particular main loop context. The reverse
1020 * mapping from ID to source is done by g_main_context_find_source_by_id().
1022 * Return value: the ID for the source
1025 g_source_get_id (GSource *source)
1029 g_return_val_if_fail (source != NULL, 0);
1030 g_return_val_if_fail (source->context != NULL, 0);
1032 LOCK_CONTEXT (source->context);
1033 result = source->source_id;
1034 UNLOCK_CONTEXT (source->context);
1040 * g_source_get_context:
1041 * @source: a #GSource
1043 * Gets the #GMainContext with which the source is associated.
1044 * Calling this function on a destroyed source is an error.
1046 * Return value: the #GMainContext with which the source is associated,
1047 * or %NULL if the context has not yet been added
1051 g_source_get_context (GSource *source)
1053 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1055 return source->context;
1059 * g_source_add_poll:
1060 * @source:a #GSource
1061 * @fd: a #GPollFD structure holding information about a file
1062 * descriptor to watch.
1064 * Adds a file descriptor to the set of file descriptors polled for
1065 * this source. This is usually combined with g_source_new() to add an
1066 * event source. The event source's check function will typically test
1067 * the @revents field in the #GPollFD struct and return %TRUE if events need
1071 g_source_add_poll (GSource *source,
1074 GMainContext *context;
1076 g_return_if_fail (source != NULL);
1077 g_return_if_fail (fd != NULL);
1078 g_return_if_fail (!SOURCE_DESTROYED (source));
1080 context = source->context;
1083 LOCK_CONTEXT (context);
1085 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1089 if (!SOURCE_BLOCKED (source))
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 if (!SOURCE_BLOCKED (source))
1123 g_main_context_remove_poll_unlocked (context, fd);
1124 UNLOCK_CONTEXT (context);
1129 * g_source_set_callback_indirect:
1130 * @source: the source
1131 * @callback_data: pointer to callback data "object"
1132 * @callback_funcs: functions for reference counting @callback_data
1133 * and getting the callback and data
1135 * Sets the callback function storing the data as a refcounted callback
1136 * "object". This is used internally. Note that calling
1137 * g_source_set_callback_indirect() assumes
1138 * an initial reference count on @callback_data, and thus
1139 * @callback_funcs->unref will eventually be called once more
1140 * than @callback_funcs->ref.
1143 g_source_set_callback_indirect (GSource *source,
1144 gpointer callback_data,
1145 GSourceCallbackFuncs *callback_funcs)
1147 GMainContext *context;
1148 gpointer old_cb_data;
1149 GSourceCallbackFuncs *old_cb_funcs;
1151 g_return_if_fail (source != NULL);
1152 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1154 context = source->context;
1157 LOCK_CONTEXT (context);
1159 old_cb_data = source->callback_data;
1160 old_cb_funcs = source->callback_funcs;
1162 source->callback_data = callback_data;
1163 source->callback_funcs = callback_funcs;
1166 UNLOCK_CONTEXT (context);
1169 old_cb_funcs->unref (old_cb_data);
1173 g_source_callback_ref (gpointer cb_data)
1175 GSourceCallback *callback = cb_data;
1177 callback->ref_count++;
1182 g_source_callback_unref (gpointer cb_data)
1184 GSourceCallback *callback = cb_data;
1186 callback->ref_count--;
1187 if (callback->ref_count == 0)
1189 if (callback->notify)
1190 callback->notify (callback->data);
1196 g_source_callback_get (gpointer cb_data,
1201 GSourceCallback *callback = cb_data;
1203 *func = callback->func;
1204 *data = callback->data;
1207 static GSourceCallbackFuncs g_source_callback_funcs = {
1208 g_source_callback_ref,
1209 g_source_callback_unref,
1210 g_source_callback_get,
1214 * g_source_set_callback:
1215 * @source: the source
1216 * @func: a callback function
1217 * @data: the data to pass to callback function
1218 * @notify: a function to call when @data is no longer in use, or %NULL.
1220 * Sets the callback function for a source. The callback for a source is
1221 * called from the source's dispatch function.
1223 * The exact type of @func depends on the type of source; ie. you
1224 * should not count on @func being called with @data as its first
1227 * Typically, you won't use this function. Instead use functions specific
1228 * to the type of source you are using.
1231 g_source_set_callback (GSource *source,
1234 GDestroyNotify notify)
1236 GSourceCallback *new_callback;
1238 g_return_if_fail (source != NULL);
1240 new_callback = g_new (GSourceCallback, 1);
1242 new_callback->ref_count = 1;
1243 new_callback->func = func;
1244 new_callback->data = data;
1245 new_callback->notify = notify;
1247 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1251 * g_source_set_priority:
1252 * @source: a #GSource
1253 * @priority: the new priority.
1255 * Sets the priority of a source. While the main loop is being
1256 * run, a source will be dispatched if it is ready to be dispatched and no sources
1257 * at a higher (numerically smaller) priority are ready to be dispatched.
1260 g_source_set_priority (GSource *source,
1264 GMainContext *context;
1266 g_return_if_fail (source != NULL);
1268 context = source->context;
1271 LOCK_CONTEXT (context);
1273 source->priority = priority;
1277 /* Remove the source from the context's source and then
1278 * add it back so it is sorted in the correct plcae
1280 g_source_list_remove (source, source->context);
1281 g_source_list_add (source, source->context);
1283 if (!SOURCE_BLOCKED (source))
1285 tmp_list = source->poll_fds;
1288 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1289 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1291 tmp_list = tmp_list->next;
1295 UNLOCK_CONTEXT (source->context);
1300 * g_source_get_priority:
1301 * @source: a #GSource
1303 * Gets the priority of a source.
1305 * Return value: the priority of the source
1308 g_source_get_priority (GSource *source)
1310 g_return_val_if_fail (source != NULL, 0);
1312 return source->priority;
1316 * g_source_set_can_recurse:
1317 * @source: a #GSource
1318 * @can_recurse: whether recursion is allowed for this source
1320 * Sets whether a source can be called recursively. If @can_recurse is
1321 * %TRUE, then while the source is being dispatched then this source
1322 * will be processed normally. Otherwise, all processing of this
1323 * source is blocked until the dispatch function returns.
1326 g_source_set_can_recurse (GSource *source,
1327 gboolean can_recurse)
1329 GMainContext *context;
1331 g_return_if_fail (source != NULL);
1333 context = source->context;
1336 LOCK_CONTEXT (context);
1339 source->flags |= G_SOURCE_CAN_RECURSE;
1341 source->flags &= ~G_SOURCE_CAN_RECURSE;
1344 UNLOCK_CONTEXT (context);
1348 * g_source_get_can_recurse:
1349 * @source: a #GSource
1351 * Checks whether a source is allowed to be called recursively.
1352 * see g_source_set_can_recurse().
1354 * Return value: whether recursion is allowed.
1357 g_source_get_can_recurse (GSource *source)
1359 g_return_val_if_fail (source != NULL, FALSE);
1361 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1366 * @source: a #GSource
1368 * Increases the reference count on a source by one.
1370 * Return value: @source
1373 g_source_ref (GSource *source)
1375 GMainContext *context;
1377 g_return_val_if_fail (source != NULL, NULL);
1379 context = source->context;
1382 LOCK_CONTEXT (context);
1384 source->ref_count++;
1387 UNLOCK_CONTEXT (context);
1392 /* g_source_unref() but possible to call within context lock
1395 g_source_unref_internal (GSource *source,
1396 GMainContext *context,
1399 gpointer old_cb_data = NULL;
1400 GSourceCallbackFuncs *old_cb_funcs = NULL;
1402 g_return_if_fail (source != NULL);
1404 if (!have_lock && context)
1405 LOCK_CONTEXT (context);
1407 source->ref_count--;
1408 if (source->ref_count == 0)
1410 old_cb_data = source->callback_data;
1411 old_cb_funcs = source->callback_funcs;
1413 source->callback_data = NULL;
1414 source->callback_funcs = NULL;
1416 if (context && !SOURCE_DESTROYED (source))
1418 g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1419 source->ref_count++;
1422 g_source_list_remove (source, context);
1424 if (source->source_funcs->finalize)
1425 source->source_funcs->finalize (source);
1427 g_slist_free (source->poll_fds);
1428 source->poll_fds = NULL;
1432 if (!have_lock && context)
1433 UNLOCK_CONTEXT (context);
1438 UNLOCK_CONTEXT (context);
1440 old_cb_funcs->unref (old_cb_data);
1443 LOCK_CONTEXT (context);
1449 * @source: a #GSource
1451 * Decreases the reference count of a source by one. If the
1452 * resulting reference count is zero the source and associated
1453 * memory will be destroyed.
1456 g_source_unref (GSource *source)
1458 g_return_if_fail (source != NULL);
1460 g_source_unref_internal (source, source->context, FALSE);
1464 * g_main_context_find_source_by_id:
1465 * @context: a #GMainContext (if %NULL, the default context will be used)
1466 * @source_id: the source ID, as returned by g_source_get_id()
1468 * Finds a #GSource given a pair of context and ID
1470 * Return value: the #GSource if found, otherwise, %NULL
1473 g_main_context_find_source_by_id (GMainContext *context,
1478 g_return_val_if_fail (source_id > 0, NULL);
1480 if (context == NULL)
1481 context = g_main_context_default ();
1483 LOCK_CONTEXT (context);
1485 source = context->source_list;
1488 if (!SOURCE_DESTROYED (source) &&
1489 source->source_id == source_id)
1491 source = source->next;
1494 UNLOCK_CONTEXT (context);
1500 * g_main_context_find_source_by_funcs_user_data:
1501 * @context: a #GMainContext (if %NULL, the default context will be used).
1502 * @funcs: the @source_funcs passed to g_source_new().
1503 * @user_data: the user data from the callback.
1505 * Finds a source with the given source functions and user data. If
1506 * multiple sources exist with the same source function and user data,
1507 * the first one found will be returned.
1509 * Return value: the source, if one was found, otherwise %NULL
1512 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1513 GSourceFuncs *funcs,
1518 g_return_val_if_fail (funcs != NULL, NULL);
1520 if (context == NULL)
1521 context = g_main_context_default ();
1523 LOCK_CONTEXT (context);
1525 source = context->source_list;
1528 if (!SOURCE_DESTROYED (source) &&
1529 source->source_funcs == funcs &&
1530 source->callback_funcs)
1532 GSourceFunc callback;
1533 gpointer callback_data;
1535 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1537 if (callback_data == user_data)
1540 source = source->next;
1543 UNLOCK_CONTEXT (context);
1549 * g_main_context_find_source_by_user_data:
1550 * @context: a #GMainContext
1551 * @user_data: the user_data for the callback.
1553 * Finds a source with the given user data for the callback. If
1554 * multiple sources exist with the same user data, the first
1555 * one found will be returned.
1557 * Return value: the source, if one was found, otherwise %NULL
1560 g_main_context_find_source_by_user_data (GMainContext *context,
1565 if (context == NULL)
1566 context = g_main_context_default ();
1568 LOCK_CONTEXT (context);
1570 source = context->source_list;
1573 if (!SOURCE_DESTROYED (source) &&
1574 source->callback_funcs)
1576 GSourceFunc callback;
1577 gpointer callback_data = NULL;
1579 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1581 if (callback_data == user_data)
1584 source = source->next;
1587 UNLOCK_CONTEXT (context);
1594 * @tag: the id of the source to remove.
1596 * Removes the source with the given id from the default main context. The id of
1597 * a #GSource is given by g_source_get_id(), or will be returned by the
1598 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1599 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1600 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1602 * See also g_source_destroy().
1604 * Return value: %TRUE if the source was found and removed.
1607 g_source_remove (guint tag)
1611 g_return_val_if_fail (tag > 0, FALSE);
1613 source = g_main_context_find_source_by_id (NULL, tag);
1615 g_source_destroy (source);
1617 return source != NULL;
1621 * g_source_remove_by_user_data:
1622 * @user_data: the user_data for the callback.
1624 * Removes a source from the default main loop context given the user
1625 * data for the callback. If multiple sources exist with the same user
1626 * data, only one will be destroyed.
1628 * Return value: %TRUE if a source was found and removed.
1631 g_source_remove_by_user_data (gpointer user_data)
1635 source = g_main_context_find_source_by_user_data (NULL, user_data);
1638 g_source_destroy (source);
1646 * g_source_remove_by_funcs_user_data:
1647 * @funcs: The @source_funcs passed to g_source_new()
1648 * @user_data: the user data for the callback
1650 * Removes a source from the default main loop context given the
1651 * source functions and user data. If multiple sources exist with the
1652 * same source functions and user data, only one will be destroyed.
1654 * Return value: %TRUE if a source was found and removed.
1657 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1662 g_return_val_if_fail (funcs != NULL, FALSE);
1664 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1667 g_source_destroy (source);
1675 * g_get_current_time:
1676 * @result: #GTimeVal structure in which to store current time.
1678 * Equivalent to the UNIX gettimeofday() function, but portable.
1681 g_get_current_time (GTimeVal *result)
1686 g_return_if_fail (result != NULL);
1688 /*this is required on alpha, there the timeval structs are int's
1689 not longs and a cast only would fail horribly*/
1690 gettimeofday (&r, NULL);
1691 result->tv_sec = r.tv_sec;
1692 result->tv_usec = r.tv_usec;
1694 /* Avoid calling time() except for the first time.
1695 * GetTickCount() should be pretty fast and low-level?
1696 * I could also use ftime() but it seems unnecessarily overheady.
1698 static DWORD start_tick = 0;
1699 static time_t start_time;
1702 g_return_if_fail (result != NULL);
1704 if (start_tick == 0)
1706 start_tick = GetTickCount ();
1710 tick = GetTickCount ();
1712 result->tv_sec = (tick - start_tick) / 1000 + start_time;
1713 result->tv_usec = ((tick - start_tick) % 1000) * 1000;
1717 /* Running the main loop */
1720 get_depth_pointer (void)
1722 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
1723 gint *depth_pointer = g_static_private_get (&depth_private);
1726 depth_pointer = g_new (gint, 1);
1728 g_static_private_set (&depth_private, depth_pointer, g_free);
1731 return depth_pointer;
1737 * Return value: The main loop recursion level in the current thread
1739 * Returns the depth of the stack of calls to
1740 * g_main_context_dispatch() on any #GMainContext in the current thread.
1741 * That is, when called from the toplevel, it gives 0. When
1742 * called from within a callback from g_main_context_iteration()
1743 * (or g_main_loop_run(), etc.) it returns 1. When called from within
1744 * a callback to a recursive call to g_main_context_iterate(),
1745 * it returns 2. And so forth.
1747 * This function is useful in a situation like the following:
1748 * Imagine an extremely simple "garbage collected" system.
1751 * static GList *free_list;
1754 * allocate_memory (gsize size)
1756 * gpointer result = g_malloc (size);
1757 * free_list = g_list_prepend (free_list, result);
1762 * free_allocated_memory (void)
1765 * for (l = free_list; l; l = l->next);
1767 * g_list_free (free_list);
1775 * g_main_context_iteration (NULL, TRUE);
1776 * free_allocated_memory();
1780 * This works from an application, however, if you want to do the same
1781 * thing from a library, it gets more difficult, since you no longer
1782 * control the main loop. You might think you can simply use an idle
1783 * function to make the call to free_allocated_memory(), but that
1784 * doesn't work, since the idle function could be called from a
1785 * recursive callback. This can be fixed by using g_main_depth()
1789 * allocate_memory (gsize size)
1791 * FreeListBlock *block = g_new (FreeListBlock, 1);\
1792 * block->mem = g_malloc (size);
1793 * block->depth = g_main_depth ();
1794 * free_list = g_list_prepend (free_list, block);
1795 * return block->mem;
1799 * free_allocated_memory (void)
1803 * int depth = g_main_depth ();
1804 * for (l = free_list; l; );
1806 * GList *next = l->next;
1807 * FreeListBlock *block = l->data;
1808 * if (block->depth > depth)
1810 * g_free (block->mem);
1812 * free_list = g_list_delete_link (free_list, l);
1820 * There is a temptation to use g_main_depth() to solve
1821 * problems with reentrancy. For instance, while waiting for data
1822 * to be received from the network in response to a menu item,
1823 * the menu item might be selected again. It might seem that
1824 * one could make the menu item's callback return immediately
1825 * and do nothing if g_main_depth() returns a value greater than 1.
1826 * However, this should be avoided since the user then sees selecting
1827 * the menu item do nothing. Furthermore, you'll find yourself adding
1828 * these checks all over your code, since there are doubtless many,
1829 * many things that the user could do. Instead, you can use the
1830 * following techniques:
1835 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
1836 * the user from interacting with elements while the main
1837 * loop is recursing.
1842 * Avoid main loop recursion in situations where you can't handle
1843 * arbitrary callbacks. Instead, structure your code so that you
1844 * simply return to the main loop and then get called again when
1845 * there is more work to do.
1853 gint *depth = get_depth_pointer ();
1857 /* Temporarily remove all this source's file descriptors from the
1858 * poll(), so that if data comes available for one of the file descriptors
1859 * we don't continually spin in the poll()
1861 /* HOLDS: source->context's lock */
1863 block_source (GSource *source)
1867 g_return_if_fail (!SOURCE_BLOCKED (source));
1869 tmp_list = source->poll_fds;
1872 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
1873 tmp_list = tmp_list->next;
1877 /* HOLDS: source->context's lock */
1879 unblock_source (GSource *source)
1883 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
1884 g_return_if_fail (!SOURCE_DESTROYED (source));
1886 tmp_list = source->poll_fds;
1889 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
1890 tmp_list = tmp_list->next;
1894 /* HOLDS: context's lock */
1896 g_main_dispatch (GMainContext *context)
1898 gint *depth = get_depth_pointer ();
1901 for (i = 0; i < context->pending_dispatches->len; i++)
1903 GSource *source = context->pending_dispatches->pdata[i];
1905 context->pending_dispatches->pdata[i] = NULL;
1908 source->flags &= ~G_SOURCE_READY;
1910 if (!SOURCE_DESTROYED (source))
1912 gboolean was_in_call;
1913 gpointer user_data = NULL;
1914 GSourceFunc callback = NULL;
1915 GSourceCallbackFuncs *cb_funcs;
1917 gboolean need_destroy;
1919 gboolean (*dispatch) (GSource *,
1923 dispatch = source->source_funcs->dispatch;
1924 cb_funcs = source->callback_funcs;
1925 cb_data = source->callback_data;
1928 cb_funcs->ref (cb_data);
1930 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
1931 block_source (source);
1933 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
1934 source->flags |= G_HOOK_FLAG_IN_CALL;
1937 cb_funcs->get (cb_data, source, &callback, &user_data);
1939 UNLOCK_CONTEXT (context);
1942 need_destroy = ! dispatch (source,
1947 LOCK_CONTEXT (context);
1950 cb_funcs->unref (cb_data);
1953 source->flags &= ~G_HOOK_FLAG_IN_CALL;
1955 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
1956 !SOURCE_DESTROYED (source))
1957 unblock_source (source);
1959 /* Note: this depends on the fact that we can't switch
1960 * sources from one main context to another
1962 if (need_destroy && !SOURCE_DESTROYED (source))
1964 g_assert (source->context == context);
1965 g_source_destroy_internal (source, context, TRUE);
1969 SOURCE_UNREF (source, context);
1972 g_ptr_array_set_size (context->pending_dispatches, 0);
1975 /* Holds context's lock */
1976 static inline GSource *
1977 next_valid_source (GMainContext *context,
1980 GSource *new_source = source ? source->next : context->source_list;
1984 if (!SOURCE_DESTROYED (new_source))
1986 new_source->ref_count++;
1990 new_source = new_source->next;
1994 SOURCE_UNREF (source, context);
2000 * g_main_context_acquire:
2001 * @context: a #GMainContext
2003 * Tries to become the owner of the specified context.
2004 * If some other context is the owner of the context,
2005 * returns %FALSE immediately. Ownership is properly
2006 * recursive: the owner can require ownership again
2007 * and will release ownership when g_main_context_release()
2008 * is called as many times as g_main_context_acquire().
2010 * You must be the owner of a context before you
2011 * can call g_main_context_prepare(), g_main_context_query(),
2012 * g_main_context_check(), g_main_context_dispatch().
2014 * Return value: %TRUE if the operation succeeded, and
2015 * this thread is now the owner of @context.
2018 g_main_context_acquire (GMainContext *context)
2020 #ifdef G_THREADS_ENABLED
2021 gboolean result = FALSE;
2022 GThread *self = G_THREAD_SELF;
2024 if (context == NULL)
2025 context = g_main_context_default ();
2027 LOCK_CONTEXT (context);
2029 if (!context->owner)
2031 context->owner = self;
2032 g_assert (context->owner_count == 0);
2035 if (context->owner == self)
2037 context->owner_count++;
2041 UNLOCK_CONTEXT (context);
2044 #else /* !G_THREADS_ENABLED */
2046 #endif /* G_THREADS_ENABLED */
2050 * g_main_context_release:
2051 * @context: a #GMainContext
2053 * Releases ownership of a context previously acquired by this thread
2054 * with g_main_context_acquire(). If the context was acquired multiple
2055 * times, the only release ownership when g_main_context_release()
2056 * is called as many times as it was acquired.
2059 g_main_context_release (GMainContext *context)
2061 #ifdef G_THREADS_ENABLED
2062 if (context == NULL)
2063 context = g_main_context_default ();
2065 LOCK_CONTEXT (context);
2067 context->owner_count--;
2068 if (context->owner_count == 0)
2070 context->owner = NULL;
2072 if (context->waiters)
2074 GMainWaiter *waiter = context->waiters->data;
2075 gboolean loop_internal_waiter =
2076 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
2077 context->waiters = g_slist_delete_link (context->waiters,
2079 if (!loop_internal_waiter)
2080 g_mutex_lock (waiter->mutex);
2082 g_cond_signal (waiter->cond);
2084 if (!loop_internal_waiter)
2085 g_mutex_unlock (waiter->mutex);
2089 UNLOCK_CONTEXT (context);
2090 #endif /* G_THREADS_ENABLED */
2094 * g_main_context_wait:
2095 * @context: a #GMainContext
2096 * @cond: a condition variable
2097 * @mutex: a mutex, currently held
2099 * Tries to become the owner of the specified context,
2100 * as with g_main_context_acquire(). But if another thread
2101 * is the owner, atomically drop @mutex and wait on @cond until
2102 * that owner releases ownership or until @cond is signaled, then
2103 * try again (once) to become the owner.
2105 * Return value: %TRUE if the operation succeeded, and
2106 * this thread is now the owner of @context.
2109 g_main_context_wait (GMainContext *context,
2113 #ifdef G_THREADS_ENABLED
2114 gboolean result = FALSE;
2115 GThread *self = G_THREAD_SELF;
2116 gboolean loop_internal_waiter;
2118 if (context == NULL)
2119 context = g_main_context_default ();
2121 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2123 if (!loop_internal_waiter)
2124 LOCK_CONTEXT (context);
2126 if (context->owner && context->owner != self)
2131 waiter.mutex = mutex;
2133 context->waiters = g_slist_append (context->waiters, &waiter);
2135 if (!loop_internal_waiter)
2136 UNLOCK_CONTEXT (context);
2137 g_cond_wait (cond, mutex);
2138 if (!loop_internal_waiter)
2139 LOCK_CONTEXT (context);
2141 context->waiters = g_slist_remove (context->waiters, &waiter);
2144 if (!context->owner)
2146 context->owner = self;
2147 g_assert (context->owner_count == 0);
2150 if (context->owner == self)
2152 context->owner_count++;
2156 if (!loop_internal_waiter)
2157 UNLOCK_CONTEXT (context);
2160 #else /* !G_THREADS_ENABLED */
2162 #endif /* G_THREADS_ENABLED */
2166 * g_main_context_prepare:
2167 * @context: a #GMainContext
2168 * @priority: location to store priority of highest priority
2169 * source already ready.
2171 * Prepares to poll sources within a main loop. The resulting information
2172 * for polling is determined by calling g_main_context_query ().
2174 * Return value: %TRUE if some source is ready to be dispatched
2178 g_main_context_prepare (GMainContext *context,
2183 gint current_priority = G_MAXINT;
2186 if (context == NULL)
2187 context = g_main_context_default ();
2189 LOCK_CONTEXT (context);
2191 context->time_is_current = FALSE;
2193 if (context->in_check_or_prepare)
2195 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2196 "prepare() member.");
2197 UNLOCK_CONTEXT (context);
2201 #ifdef G_THREADS_ENABLED
2202 if (context->poll_waiting)
2204 g_warning("g_main_context_prepare(): main loop already active in another thread");
2205 UNLOCK_CONTEXT (context);
2209 context->poll_waiting = TRUE;
2210 #endif /* G_THREADS_ENABLED */
2213 /* If recursing, finish up current dispatch, before starting over */
2214 if (context->pending_dispatches)
2217 g_main_dispatch (context, ¤t_time);
2219 UNLOCK_CONTEXT (context);
2224 /* If recursing, clear list of pending dispatches */
2226 for (i = 0; i < context->pending_dispatches->len; i++)
2228 if (context->pending_dispatches->pdata[i])
2229 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2231 g_ptr_array_set_size (context->pending_dispatches, 0);
2233 /* Prepare all sources */
2235 context->timeout = -1;
2237 source = next_valid_source (context, NULL);
2240 gint source_timeout = -1;
2242 if ((n_ready > 0) && (source->priority > current_priority))
2244 SOURCE_UNREF (source, context);
2247 if (SOURCE_BLOCKED (source))
2250 if (!(source->flags & G_SOURCE_READY))
2253 gboolean (*prepare) (GSource *source,
2256 prepare = source->source_funcs->prepare;
2257 context->in_check_or_prepare++;
2258 UNLOCK_CONTEXT (context);
2260 result = (*prepare) (source, &source_timeout);
2262 LOCK_CONTEXT (context);
2263 context->in_check_or_prepare--;
2266 source->flags |= G_SOURCE_READY;
2269 if (source->flags & G_SOURCE_READY)
2272 current_priority = source->priority;
2273 context->timeout = 0;
2276 if (source_timeout >= 0)
2278 if (context->timeout < 0)
2279 context->timeout = source_timeout;
2281 context->timeout = MIN (context->timeout, source_timeout);
2285 source = next_valid_source (context, source);
2288 UNLOCK_CONTEXT (context);
2291 *priority = current_priority;
2293 return (n_ready > 0);
2297 * g_main_context_query:
2298 * @context: a #GMainContext
2299 * @max_priority: maximum priority source to check
2300 * @timeout_: location to store timeout to be used in polling
2301 * @fds: location to store #GPollFD records that need to be polled.
2302 * @n_fds: length of @fds.
2304 * Determines information necessary to poll this main loop.
2306 * Return value: the number of records actually stored in @fds,
2307 * or, if more than @n_fds records need to be stored, the number
2308 * of records that need to be stored.
2311 g_main_context_query (GMainContext *context,
2320 LOCK_CONTEXT (context);
2322 pollrec = context->poll_records;
2324 while (pollrec && max_priority >= pollrec->priority)
2326 if (pollrec->fd->events)
2330 fds[n_poll].fd = pollrec->fd->fd;
2331 /* In direct contradiction to the Unix98 spec, IRIX runs into
2332 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2333 * flags in the events field of the pollfd while it should
2334 * just ignoring them. So we mask them out here.
2336 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2337 fds[n_poll].revents = 0;
2342 pollrec = pollrec->next;
2345 #ifdef G_THREADS_ENABLED
2346 context->poll_changed = FALSE;
2351 *timeout = context->timeout;
2353 context->time_is_current = FALSE;
2356 UNLOCK_CONTEXT (context);
2362 * g_main_context_check:
2363 * @context: a #GMainContext
2364 * @max_priority: the maximum numerical priority of sources to check
2365 * @fds: array of #GPollFD's that was passed to the last call to
2366 * g_main_context_query()
2367 * @n_fds: return value of g_main_context_query()
2369 * Passes the results of polling back to the main loop.
2371 * Return value: %TRUE if some sources are ready to be dispatched.
2374 g_main_context_check (GMainContext *context,
2384 LOCK_CONTEXT (context);
2386 if (context->in_check_or_prepare)
2388 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2389 "prepare() member.");
2390 UNLOCK_CONTEXT (context);
2394 #ifdef G_THREADS_ENABLED
2395 if (!context->poll_waiting)
2399 read (context->wake_up_pipe[0], &a, 1);
2403 context->poll_waiting = FALSE;
2405 /* If the set of poll file descriptors changed, bail out
2406 * and let the main loop rerun
2408 if (context->poll_changed)
2410 UNLOCK_CONTEXT (context);
2413 #endif /* G_THREADS_ENABLED */
2415 pollrec = context->poll_records;
2419 if (pollrec->fd->events)
2421 pollrec->fd->revents = fds[i].revents;
2424 pollrec = pollrec->next;
2427 source = next_valid_source (context, NULL);
2430 if ((n_ready > 0) && (source->priority > max_priority))
2432 SOURCE_UNREF (source, context);
2435 if (SOURCE_BLOCKED (source))
2438 if (!(source->flags & G_SOURCE_READY))
2441 gboolean (*check) (GSource *source);
2443 check = source->source_funcs->check;
2445 context->in_check_or_prepare++;
2446 UNLOCK_CONTEXT (context);
2448 result = (*check) (source);
2450 LOCK_CONTEXT (context);
2451 context->in_check_or_prepare--;
2454 source->flags |= G_SOURCE_READY;
2457 if (source->flags & G_SOURCE_READY)
2459 source->ref_count++;
2460 g_ptr_array_add (context->pending_dispatches, source);
2464 /* never dispatch sources with less priority than the first
2465 * one we choose to dispatch
2467 max_priority = source->priority;
2471 source = next_valid_source (context, source);
2474 UNLOCK_CONTEXT (context);
2480 * g_main_context_dispatch:
2481 * @context: a #GMainContext
2483 * Dispatches all pending sources.
2486 g_main_context_dispatch (GMainContext *context)
2488 LOCK_CONTEXT (context);
2490 if (context->pending_dispatches->len > 0)
2492 g_main_dispatch (context);
2495 UNLOCK_CONTEXT (context);
2498 /* HOLDS context lock */
2500 g_main_context_iterate (GMainContext *context,
2507 gboolean some_ready;
2508 gint nfds, allocated_nfds;
2509 GPollFD *fds = NULL;
2511 UNLOCK_CONTEXT (context);
2513 #ifdef G_THREADS_ENABLED
2514 if (!g_main_context_acquire (context))
2516 gboolean got_ownership;
2518 g_return_val_if_fail (g_thread_supported (), FALSE);
2523 LOCK_CONTEXT (context);
2526 context->cond = g_cond_new ();
2528 got_ownership = g_main_context_wait (context,
2530 g_static_mutex_get_mutex (&context->mutex));
2534 UNLOCK_CONTEXT (context);
2539 LOCK_CONTEXT (context);
2540 #endif /* G_THREADS_ENABLED */
2542 if (!context->cached_poll_array)
2544 context->cached_poll_array_size = context->n_poll_records;
2545 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2548 allocated_nfds = context->cached_poll_array_size;
2549 fds = context->cached_poll_array;
2551 UNLOCK_CONTEXT (context);
2553 g_main_context_prepare (context, &max_priority);
2555 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
2556 allocated_nfds)) > allocated_nfds)
2558 LOCK_CONTEXT (context);
2560 context->cached_poll_array_size = allocated_nfds = nfds;
2561 context->cached_poll_array = fds = g_new (GPollFD, nfds);
2562 UNLOCK_CONTEXT (context);
2568 g_main_context_poll (context, timeout, max_priority, fds, nfds);
2570 some_ready = g_main_context_check (context, max_priority, fds, nfds);
2573 g_main_context_dispatch (context);
2575 #ifdef G_THREADS_ENABLED
2576 g_main_context_release (context);
2577 #endif /* G_THREADS_ENABLED */
2579 LOCK_CONTEXT (context);
2585 * g_main_context_pending:
2586 * @context: a #GMainContext (if %NULL, the default context will be used)
2588 * Checks if any sources have pending events for the given context.
2590 * Return value: %TRUE if events are pending.
2593 g_main_context_pending (GMainContext *context)
2598 context = g_main_context_default();
2600 LOCK_CONTEXT (context);
2601 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
2602 UNLOCK_CONTEXT (context);
2608 * g_main_context_iteration:
2609 * @context: a #GMainContext (if %NULL, the default context will be used)
2610 * @may_block: whether the call may block.
2612 * Runs a single iteration for the given main loop. This involves
2613 * checking to see if any event sources are ready to be processed,
2614 * then if no events sources are ready and @may_block is %TRUE, waiting
2615 * for a source to become ready, then dispatching the highest priority
2616 * events sources that are ready. Note that even when @may_block is %TRUE,
2617 * it is still possible for g_main_context_iteration() to return
2618 * %FALSE, since the the wait may be interrupted for other
2619 * reasons than an event source becoming ready.
2621 * Return value: %TRUE if events were dispatched.
2624 g_main_context_iteration (GMainContext *context, gboolean may_block)
2629 context = g_main_context_default();
2631 LOCK_CONTEXT (context);
2632 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
2633 UNLOCK_CONTEXT (context);
2640 * @context: a #GMainContext (if %NULL, the default context will be used).
2641 * @is_running: set to %TRUE to indicate that the loop is running. This
2642 * is not very important since calling g_main_loop_run() will set this to
2645 * Creates a new #GMainLoop structure.
2647 * Return value: a new #GMainLoop.
2650 g_main_loop_new (GMainContext *context,
2651 gboolean is_running)
2656 context = g_main_context_default();
2658 g_main_context_ref (context);
2660 loop = g_new0 (GMainLoop, 1);
2661 loop->context = context;
2662 loop->is_running = is_running != FALSE;
2663 loop->ref_count = 1;
2670 * @loop: a #GMainLoop
2672 * Increases the reference count on a #GMainLoop object by one.
2674 * Return value: @loop
2677 g_main_loop_ref (GMainLoop *loop)
2679 g_return_val_if_fail (loop != NULL, NULL);
2680 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2682 g_atomic_int_inc (&loop->ref_count);
2688 * g_main_loop_unref:
2689 * @loop: a #GMainLoop
2691 * Decreases the reference count on a #GMainLoop object by one. If
2692 * the result is zero, free the loop and free all associated memory.
2695 g_main_loop_unref (GMainLoop *loop)
2697 g_return_if_fail (loop != NULL);
2698 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2700 if (!g_atomic_int_dec_and_test (&loop->ref_count))
2703 g_main_context_unref (loop->context);
2709 * @loop: a #GMainLoop
2711 * Runs a main loop until g_main_loop_quit() is called on the loop.
2712 * If this is called for the thread of the loop's #GMainContext,
2713 * it will process events from the loop, otherwise it will
2717 g_main_loop_run (GMainLoop *loop)
2719 GThread *self = G_THREAD_SELF;
2721 g_return_if_fail (loop != NULL);
2722 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2724 #ifdef G_THREADS_ENABLED
2725 if (!g_main_context_acquire (loop->context))
2727 gboolean got_ownership = FALSE;
2729 /* Another thread owns this context */
2730 if (!g_thread_supported ())
2732 g_warning ("g_main_loop_run() was called from second thread but "
2733 "g_thread_init() was never called.");
2737 LOCK_CONTEXT (loop->context);
2739 g_atomic_int_inc (&loop->ref_count);
2741 if (!loop->is_running)
2742 loop->is_running = TRUE;
2744 if (!loop->context->cond)
2745 loop->context->cond = g_cond_new ();
2747 while (loop->is_running && !got_ownership)
2748 got_ownership = g_main_context_wait (loop->context,
2749 loop->context->cond,
2750 g_static_mutex_get_mutex (&loop->context->mutex));
2752 if (!loop->is_running)
2754 UNLOCK_CONTEXT (loop->context);
2756 g_main_context_release (loop->context);
2757 g_main_loop_unref (loop);
2761 g_assert (got_ownership);
2764 LOCK_CONTEXT (loop->context);
2765 #endif /* G_THREADS_ENABLED */
2767 if (loop->context->in_check_or_prepare)
2769 g_warning ("g_main_loop_run(): called recursively from within a source's "
2770 "check() or prepare() member, iteration not possible.");
2774 g_atomic_int_inc (&loop->ref_count);
2775 loop->is_running = TRUE;
2776 while (loop->is_running)
2777 g_main_context_iterate (loop->context, TRUE, TRUE, self);
2779 UNLOCK_CONTEXT (loop->context);
2781 #ifdef G_THREADS_ENABLED
2782 g_main_context_release (loop->context);
2783 #endif /* G_THREADS_ENABLED */
2785 g_main_loop_unref (loop);
2790 * @loop: a #GMainLoop
2792 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
2793 * for the loop will return.
2796 g_main_loop_quit (GMainLoop *loop)
2798 g_return_if_fail (loop != NULL);
2799 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2801 LOCK_CONTEXT (loop->context);
2802 loop->is_running = FALSE;
2803 g_main_context_wakeup_unlocked (loop->context);
2805 #ifdef G_THREADS_ENABLED
2806 if (loop->context->cond)
2807 g_cond_broadcast (loop->context->cond);
2808 #endif /* G_THREADS_ENABLED */
2810 UNLOCK_CONTEXT (loop->context);
2814 * g_main_loop_is_running:
2815 * @loop: a #GMainLoop.
2817 * Checks to see if the main loop is currently being run via g_main_loop_run().
2819 * Return value: %TRUE if the mainloop is currently being run.
2822 g_main_loop_is_running (GMainLoop *loop)
2824 g_return_val_if_fail (loop != NULL, FALSE);
2825 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
2827 return loop->is_running;
2831 * g_main_loop_get_context:
2832 * @loop: a #GMainLoop.
2834 * Returns the #GMainContext of @loop.
2836 * Return value: the #GMainContext of @loop
2839 g_main_loop_get_context (GMainLoop *loop)
2841 g_return_val_if_fail (loop != NULL, NULL);
2842 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2844 return loop->context;
2847 /* HOLDS: context's lock */
2849 g_main_context_poll (GMainContext *context,
2855 #ifdef G_MAIN_POLL_DEBUG
2861 GPollFunc poll_func;
2863 if (n_fds || timeout != 0)
2865 #ifdef G_MAIN_POLL_DEBUG
2866 g_print ("g_main_poll(%d) timeout: %d\n", n_fds, timeout);
2867 poll_timer = g_timer_new ();
2870 LOCK_CONTEXT (context);
2872 poll_func = context->poll_func;
2874 UNLOCK_CONTEXT (context);
2875 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
2878 g_warning ("poll(2) failed due to: %s.",
2879 g_strerror (errno));
2881 /* If g_poll () returns -1, it has already called g_warning() */
2885 #ifdef G_MAIN_POLL_DEBUG
2886 LOCK_CONTEXT (context);
2888 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
2891 g_timer_elapsed (poll_timer, NULL));
2892 g_timer_destroy (poll_timer);
2893 pollrec = context->poll_records;
2897 if (pollrec->fd->events)
2901 g_print (" [%d:", fds[i].fd);
2902 if (fds[i].revents & G_IO_IN)
2904 if (fds[i].revents & G_IO_OUT)
2906 if (fds[i].revents & G_IO_PRI)
2908 if (fds[i].revents & G_IO_ERR)
2910 if (fds[i].revents & G_IO_HUP)
2912 if (fds[i].revents & G_IO_NVAL)
2918 pollrec = pollrec->next;
2922 UNLOCK_CONTEXT (context);
2924 } /* if (n_fds || timeout != 0) */
2928 * g_main_context_add_poll:
2929 * @context: a #GMainContext (or %NULL for the default context)
2930 * @fd: a #GPollFD structure holding information about a file
2931 * descriptor to watch.
2932 * @priority: the priority for this file descriptor which should be
2933 * the same as the priority used for g_source_attach() to ensure that the
2934 * file descriptor is polled whenever the results may be needed.
2936 * Adds a file descriptor to the set of file descriptors polled for
2937 * this context. This will very seldomly be used directly. Instead
2938 * a typical event source will use g_source_add_poll() instead.
2941 g_main_context_add_poll (GMainContext *context,
2946 context = g_main_context_default ();
2948 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
2949 g_return_if_fail (fd);
2951 LOCK_CONTEXT (context);
2952 g_main_context_add_poll_unlocked (context, priority, fd);
2953 UNLOCK_CONTEXT (context);
2956 /* HOLDS: main_loop_lock */
2958 g_main_context_add_poll_unlocked (GMainContext *context,
2962 GPollRec *lastrec, *pollrec, *newrec;
2964 if (!context->poll_chunk)
2965 context->poll_chunk = g_mem_chunk_create (GPollRec, 32, G_ALLOC_ONLY);
2967 if (context->poll_free_list)
2969 newrec = context->poll_free_list;
2970 context->poll_free_list = newrec->next;
2973 newrec = g_chunk_new (GPollRec, context->poll_chunk);
2975 /* This file descriptor may be checked before we ever poll */
2978 newrec->priority = priority;
2981 pollrec = context->poll_records;
2982 while (pollrec && priority >= pollrec->priority)
2985 pollrec = pollrec->next;
2989 lastrec->next = newrec;
2991 context->poll_records = newrec;
2993 newrec->next = pollrec;
2995 context->n_poll_records++;
2997 #ifdef G_THREADS_ENABLED
2998 context->poll_changed = TRUE;
3000 /* Now wake up the main loop if it is waiting in the poll() */
3001 g_main_context_wakeup_unlocked (context);
3006 * g_main_context_remove_poll:
3007 * @context:a #GMainContext
3008 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3010 * Removes file descriptor from the set of file descriptors to be
3011 * polled for a particular context.
3014 g_main_context_remove_poll (GMainContext *context,
3018 context = g_main_context_default ();
3020 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3021 g_return_if_fail (fd);
3023 LOCK_CONTEXT (context);
3024 g_main_context_remove_poll_unlocked (context, fd);
3025 UNLOCK_CONTEXT (context);
3029 g_main_context_remove_poll_unlocked (GMainContext *context,
3032 GPollRec *pollrec, *lastrec;
3035 pollrec = context->poll_records;
3039 if (pollrec->fd == fd)
3041 if (lastrec != NULL)
3042 lastrec->next = pollrec->next;
3044 context->poll_records = pollrec->next;
3046 #ifdef ENABLE_GC_FRIENDLY
3048 #endif /* ENABLE_GC_FRIENDLY */
3050 pollrec->next = context->poll_free_list;
3051 context->poll_free_list = pollrec;
3053 context->n_poll_records--;
3057 pollrec = pollrec->next;
3060 #ifdef G_THREADS_ENABLED
3061 context->poll_changed = TRUE;
3063 /* Now wake up the main loop if it is waiting in the poll() */
3064 g_main_context_wakeup_unlocked (context);
3069 * g_source_get_current_time:
3070 * @source: a #GSource
3071 * @timeval: #GTimeVal structure in which to store current time.
3073 * Gets the "current time" to be used when checking
3074 * this source. The advantage of calling this function over
3075 * calling g_get_current_time() directly is that when
3076 * checking multiple sources, GLib can cache a single value
3077 * instead of having to repeatedly get the system time.
3080 g_source_get_current_time (GSource *source,
3083 GMainContext *context;
3085 g_return_if_fail (source->context != NULL);
3087 context = source->context;
3089 LOCK_CONTEXT (context);
3091 if (!context->time_is_current)
3093 g_get_current_time (&context->current_time);
3094 context->time_is_current = TRUE;
3097 *timeval = context->current_time;
3099 UNLOCK_CONTEXT (context);
3103 * g_main_context_set_poll_func:
3104 * @context: a #GMainContext
3105 * @func: the function to call to poll all file descriptors
3107 * Sets the function to use to handle polling of file descriptors. It
3108 * will be used instead of the poll() system call
3109 * (or GLib's replacement function, which is used where
3110 * poll() isn't available).
3112 * This function could possibly be used to integrate the GLib event
3113 * loop with an external event loop.
3116 g_main_context_set_poll_func (GMainContext *context,
3120 context = g_main_context_default ();
3122 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3124 LOCK_CONTEXT (context);
3127 context->poll_func = func;
3131 context->poll_func = (GPollFunc) poll;
3133 context->poll_func = (GPollFunc) g_poll;
3137 UNLOCK_CONTEXT (context);
3141 * g_main_context_get_poll_func:
3142 * @context: a #GMainContext
3144 * Gets the poll function set by g_main_context_set_poll_func().
3146 * Return value: the poll function
3149 g_main_context_get_poll_func (GMainContext *context)
3154 context = g_main_context_default ();
3156 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3158 LOCK_CONTEXT (context);
3159 result = context->poll_func;
3160 UNLOCK_CONTEXT (context);
3165 /* HOLDS: context's lock */
3166 /* Wake the main loop up from a poll() */
3168 g_main_context_wakeup_unlocked (GMainContext *context)
3170 #ifdef G_THREADS_ENABLED
3171 if (g_thread_supported() && context->poll_waiting)
3173 context->poll_waiting = FALSE;
3175 write (context->wake_up_pipe[1], "A", 1);
3177 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
3184 * g_main_context_wakeup:
3185 * @context: a #GMainContext
3187 * If @context is currently waiting in a poll(), interrupt
3188 * the poll(), and continue the iteration process.
3191 g_main_context_wakeup (GMainContext *context)
3194 context = g_main_context_default ();
3196 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3198 LOCK_CONTEXT (context);
3199 g_main_context_wakeup_unlocked (context);
3200 UNLOCK_CONTEXT (context);
3206 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3207 GTimeVal *current_time)
3209 guint seconds = timeout_source->interval / 1000;
3210 guint msecs = timeout_source->interval - seconds * 1000;
3212 timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
3213 timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
3214 if (timeout_source->expiration.tv_usec >= 1000000)
3216 timeout_source->expiration.tv_usec -= 1000000;
3217 timeout_source->expiration.tv_sec++;
3222 g_timeout_prepare (GSource *source,
3227 GTimeVal current_time;
3229 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3231 g_source_get_current_time (source, ¤t_time);
3233 sec = timeout_source->expiration.tv_sec - current_time.tv_sec;
3234 msec = (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000;
3236 /* We do the following in a rather convoluted fashion to deal with
3237 * the fact that we don't have an integral type big enough to hold
3238 * the difference of two timevals in millseconds.
3240 if (sec < 0 || (sec == 0 && msec < 0))
3244 glong interval_sec = timeout_source->interval / 1000;
3245 glong interval_msec = timeout_source->interval % 1000;
3253 if (sec > interval_sec ||
3254 (sec == interval_sec && msec > interval_msec))
3256 /* The system time has been set backwards, so we
3257 * reset the expiration time to now + timeout_source->interval;
3258 * this at least avoids hanging for long periods of time.
3260 g_timeout_set_expiration (timeout_source, ¤t_time);
3261 msec = MIN (G_MAXINT, timeout_source->interval);
3265 msec = MIN (G_MAXINT, (guint)msec + 1000 * (guint)sec);
3269 *timeout = (gint)msec;
3275 g_timeout_check (GSource *source)
3277 GTimeVal current_time;
3278 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3280 g_source_get_current_time (source, ¤t_time);
3282 return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
3283 ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
3284 (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
3288 g_timeout_dispatch (GSource *source,
3289 GSourceFunc callback,
3292 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3296 g_warning ("Timeout source dispatched without callback\n"
3297 "You must call g_source_set_callback().");
3301 if (callback (user_data))
3303 GTimeVal current_time;
3305 g_source_get_current_time (source, ¤t_time);
3306 g_timeout_set_expiration (timeout_source, ¤t_time);
3315 * g_timeout_source_new:
3316 * @interval: the timeout interval in milliseconds.
3318 * Creates a new timeout source.
3320 * The source will not initially be associated with any #GMainContext
3321 * and must be added to one with g_source_attach() before it will be
3324 * Return value: the newly-created timeout source
3327 g_timeout_source_new (guint interval)
3329 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3330 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3331 GTimeVal current_time;
3333 timeout_source->interval = interval;
3335 g_get_current_time (¤t_time);
3336 g_timeout_set_expiration (timeout_source, ¤t_time);
3342 * g_timeout_add_full:
3343 * @priority: the priority of the idle source. Typically this will be in the
3344 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3345 * @interval: the time between calls to the function, in milliseconds
3346 * (1/1000ths of a second)
3347 * @function: function to call
3348 * @data: data to pass to @function
3349 * @notify: function to call when the idle is removed, or %NULL
3351 * Sets a function to be called at regular intervals, with the given
3352 * priority. The function is called repeatedly until it returns
3353 * %FALSE, at which point the timeout is automatically destroyed and
3354 * the function will not be called again. The @notify function is
3355 * called when the timeout is destroyed. The first call to the
3356 * function will be at the end of the first @interval.
3358 * Note that timeout functions may be delayed, due to the processing of other
3359 * event sources. Thus they should not be relied on for precise timing.
3360 * After each call to the timeout function, the time of the next
3361 * timeout is recalculated based on the current time and the given interval
3362 * (it does not try to 'catch up' time lost in delays).
3364 * Return value: the id of event source.
3367 g_timeout_add_full (gint priority,
3369 GSourceFunc function,
3371 GDestroyNotify notify)
3376 g_return_val_if_fail (function != NULL, 0);
3378 source = g_timeout_source_new (interval);
3380 if (priority != G_PRIORITY_DEFAULT)
3381 g_source_set_priority (source, priority);
3383 g_source_set_callback (source, function, data, notify);
3384 id = g_source_attach (source, NULL);
3385 g_source_unref (source);
3392 * @interval: the time between calls to the function, in milliseconds
3393 * (1/1000ths of a second)
3394 * @function: function to call
3395 * @data: data to pass to @function
3397 * Sets a function to be called at regular intervals, with the default
3398 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
3399 * until it returns %FALSE, at which point the timeout is automatically
3400 * destroyed and the function will not be called again. The first call
3401 * to the function will be at the end of the first @interval.
3403 * Note that timeout functions may be delayed, due to the processing of other
3404 * event sources. Thus they should not be relied on for precise timing.
3405 * After each call to the timeout function, the time of the next
3406 * timeout is recalculated based on the current time and the given interval
3407 * (it does not try to 'catch up' time lost in delays).
3409 * Return value: the id of event source.
3412 g_timeout_add (guint32 interval,
3413 GSourceFunc function,
3416 return g_timeout_add_full (G_PRIORITY_DEFAULT,
3417 interval, function, data, NULL);
3420 /* Child watch functions */
3425 g_child_watch_prepare (GSource *source,
3434 g_child_watch_check (GSource *source)
3436 GChildWatchSource *child_watch_source;
3437 gboolean child_exited;
3439 child_watch_source = (GChildWatchSource *) source;
3441 child_exited = child_watch_source->poll.revents & G_IO_IN;
3448 * Note: We do _not_ check for the special value of STILL_ACTIVE
3449 * since we know that the process has exited and doing so runs into
3450 * problems if the child process "happens to return STILL_ACTIVE(259)"
3451 * as Microsoft's Platform SDK puts it.
3453 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
3455 gchar *emsg = g_win32_error_message (GetLastError ());
3456 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
3459 child_watch_source->child_status = -1;
3462 child_watch_source->child_status = child_status;
3465 return child_exited;
3468 #else /* G_OS_WIN32 */
3471 check_for_child_exited (GSource *source)
3473 GChildWatchSource *child_watch_source;
3476 /* protect against another SIGCHLD in the middle of this call */
3477 count = child_watch_count;
3479 child_watch_source = (GChildWatchSource *) source;
3481 if (child_watch_source->child_exited)
3484 if (child_watch_source->count < count)
3488 if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
3490 child_watch_source->child_status = child_status;
3491 child_watch_source->child_exited = TRUE;
3493 child_watch_source->count = count;
3496 return child_watch_source->child_exited;
3500 g_child_watch_prepare (GSource *source,
3503 GChildWatchSource *child_watch_source;
3506 child_watch_source = (GChildWatchSource *) source;
3508 return check_for_child_exited (source);
3513 g_child_watch_check (GSource *source)
3515 GChildWatchSource *child_watch_source;
3517 child_watch_source = (GChildWatchSource *) source;
3519 return check_for_child_exited (source);
3522 #endif /* G_OS_WIN32 */
3525 g_child_watch_dispatch (GSource *source,
3526 GSourceFunc callback,
3529 GChildWatchSource *child_watch_source;
3530 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
3532 child_watch_source = (GChildWatchSource *) source;
3536 g_warning ("Child watch source dispatched without callback\n"
3537 "You must call g_source_set_callback().");
3541 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
3543 /* We never keep a child watch source around as the child is gone */
3550 g_child_watch_signal_handler (int signum)
3552 child_watch_count ++;
3554 if (child_watch_init_state == CHILD_WATCH_INITIALIZED_THREADED)
3556 write (child_watch_wake_up_pipe[1], "B", 1);
3560 /* We count on the signal interrupting the poll in the same thread.
3566 g_child_watch_source_init_single (void)
3568 g_assert (! g_thread_supported());
3569 g_assert (child_watch_init_state == CHILD_WATCH_UNINITIALIZED);
3571 child_watch_init_state = CHILD_WATCH_INITIALIZED_SINGLE;
3573 signal (SIGCHLD, g_child_watch_signal_handler);
3577 child_watch_helper_thread (gpointer data)
3580 GPollFunc poll_func;
3583 poll_func = (GPollFunc)poll;
3588 fds.fd = child_watch_wake_up_pipe[0];
3589 fds.events = G_IO_IN;
3596 read (child_watch_wake_up_pipe[0], b, 20);
3598 /* We were woken up. Wake up all other contexts in all other threads */
3599 G_LOCK (main_context_list);
3600 for (list = main_context_list; list; list = list->next)
3602 GMainContext *context;
3604 context = list->data;
3605 if (g_atomic_int_get (&context->ref_count) > 0)
3606 /* Due to racing conditions we can find ref_count == 0, in
3607 * that case, however, the context is still not destroyed
3608 * and no poll can be active, otherwise the ref_count
3610 g_main_context_wakeup (context);
3612 G_UNLOCK (main_context_list);
3618 g_child_watch_source_init_multi_threaded (void)
3620 GError *error = NULL;
3622 g_assert (g_thread_supported());
3624 if (pipe (child_watch_wake_up_pipe) < 0)
3625 g_error ("Cannot create wake up pipe: %s\n", g_strerror (errno));
3626 fcntl (child_watch_wake_up_pipe[1], F_SETFL, O_NONBLOCK | fcntl (child_watch_wake_up_pipe[1], F_GETFL));
3628 /* We create a helper thread that polls on the wakeup pipe indefinitely */
3629 /* FIXME: Think this through for races */
3630 if (g_thread_create (child_watch_helper_thread, NULL, FALSE, &error) == NULL)
3631 g_error ("Cannot create a thread to monitor child exit status: %s\n", error->message);
3632 child_watch_init_state = CHILD_WATCH_INITIALIZED_THREADED;
3633 signal (SIGCHLD, g_child_watch_signal_handler);
3637 g_child_watch_source_init_promote_single_to_threaded (void)
3639 g_child_watch_source_init_multi_threaded ();
3643 g_child_watch_source_init (void)
3645 if (g_thread_supported())
3647 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
3648 g_child_watch_source_init_multi_threaded ();
3649 else if (child_watch_init_state == CHILD_WATCH_INITIALIZED_SINGLE)
3650 g_child_watch_source_init_promote_single_to_threaded ();
3654 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
3655 g_child_watch_source_init_single ();
3659 #endif /* !G_OS_WIN32 */
3662 * g_child_watch_source_new:
3663 * @pid: process id of a child process to watch. On Windows, a HANDLE
3664 * for the process to watch (which actually doesn't have to be a child).
3666 * Creates a new child_watch source.
3668 * The source will not initially be associated with any #GMainContext
3669 * and must be added to one with g_source_attach() before it will be
3672 * Note that on platforms where #GPid must be explicitely closed
3673 * (see g_spawn_close_pid()) @pid must not be closed while the
3674 * source is still active. Typically, you will want to call
3675 * g_spawn_close_pid() in the callback function for the source.
3677 * Return value: the newly-created child watch source
3682 g_child_watch_source_new (GPid pid)
3684 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
3685 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
3688 child_watch_source->poll.fd = (int)pid;
3689 child_watch_source->poll.events = G_IO_IN;
3691 g_source_add_poll (source, &child_watch_source->poll);
3692 #else /* G_OS_WIN32 */
3693 g_child_watch_source_init ();
3694 #endif /* G_OS_WIN32 */
3696 child_watch_source->pid = pid;
3702 * g_child_watch_add_full:
3703 * @priority: the priority of the idle source. Typically this will be in the
3704 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3705 * @pid: process id of a child process to watch
3706 * @function: function to call
3707 * @data: data to pass to @function
3708 * @notify: function to call when the idle is removed, or %NULL
3710 * Sets a function to be called when the child indicated by @pid exits, at a
3711 * default priority, #G_PRIORITY_DEFAULT.
3713 * Note that on platforms where #GPid must be explicitely closed
3714 * (see g_spawn_close_pid()) @pid must not be closed while the
3715 * source is still active. Typically, you will want to call
3716 * g_spawn_close_pid() in the callback function for the source.
3718 * Return value: the id of event source.
3723 g_child_watch_add_full (gint priority,
3725 GChildWatchFunc function,
3727 GDestroyNotify notify)
3732 g_return_val_if_fail (function != NULL, 0);
3734 source = g_child_watch_source_new (pid);
3736 if (priority != G_PRIORITY_DEFAULT)
3737 g_source_set_priority (source, priority);
3739 g_source_set_callback (source, (GSourceFunc) function, data, notify);
3740 id = g_source_attach (source, NULL);
3741 g_source_unref (source);
3747 * g_child_watch_add:
3748 * @pid: process id of a child process to watch
3749 * @function: function to call
3750 * @data: data to pass to @function
3752 * Sets a function to be called when the child indicated by @pid exits, at a
3753 * default priority, #G_PRIORITY_DEFAULT.
3755 * Note that on platforms where #GPid must be explicitely closed
3756 * (see g_spawn_close_pid()) @pid must not be closed while the
3757 * source is still active. Typically, you will want to call
3758 * g_spawn_close_pid() in the callback function for the source.
3760 * Return value: the id of event source.
3765 g_child_watch_add (GPid pid,
3766 GChildWatchFunc function,
3769 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
3773 /* Idle functions */
3776 g_idle_prepare (GSource *source,
3785 g_idle_check (GSource *source)
3791 g_idle_dispatch (GSource *source,
3792 GSourceFunc callback,
3797 g_warning ("Idle source dispatched without callback\n"
3798 "You must call g_source_set_callback().");
3802 return callback (user_data);
3806 * g_idle_source_new:
3808 * Creates a new idle source.
3810 * The source will not initially be associated with any #GMainContext
3811 * and must be added to one with g_source_attach() before it will be
3812 * executed. Note that the default priority for idle sources is
3813 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
3814 * have a default priority of %G_PRIORITY_DEFAULT.
3816 * Return value: the newly-created idle source
3819 g_idle_source_new (void)
3823 source = g_source_new (&g_idle_funcs, sizeof (GSource));
3824 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
3831 * @priority: the priority of the idle source. Typically this will be in the
3832 * range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3833 * @function: function to call
3834 * @data: data to pass to @function
3835 * @notify: function to call when the idle is removed, or %NULL
3837 * Adds a function to be called whenever there are no higher priority
3838 * events pending. If the function returns %FALSE it is automatically
3839 * removed from the list of event sources and will not be called again.
3841 * Return value: the id of the event source.
3844 g_idle_add_full (gint priority,
3845 GSourceFunc function,
3847 GDestroyNotify notify)
3852 g_return_val_if_fail (function != NULL, 0);
3854 source = g_idle_source_new ();
3856 if (priority != G_PRIORITY_DEFAULT_IDLE)
3857 g_source_set_priority (source, priority);
3859 g_source_set_callback (source, function, data, notify);
3860 id = g_source_attach (source, NULL);
3861 g_source_unref (source);
3868 * @function: function to call
3869 * @data: data to pass to @function.
3871 * Adds a function to be called whenever there are no higher priority
3872 * events pending to the default main loop. The function is given the
3873 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
3874 * returns %FALSE it is automatically removed from the list of event
3875 * sources and will not be called again.
3877 * Return value: the id of the event source.
3880 g_idle_add (GSourceFunc function,
3883 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
3887 * g_idle_remove_by_data:
3888 * @data: the data for the idle source's callback.
3890 * Removes the idle function with the given data.
3892 * Return value: %TRUE if an idle source was found and removed.
3895 g_idle_remove_by_data (gpointer data)
3897 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);