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 */
83 typedef struct _GTimeoutSource GTimeoutSource;
84 typedef struct _GChildWatchSource GChildWatchSource;
85 typedef struct _GPollRec GPollRec;
86 typedef struct _GSourceCallback GSourceCallback;
90 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
91 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
94 #ifdef G_THREADS_ENABLED
95 typedef struct _GMainWaiter GMainWaiter;
106 #ifdef G_THREADS_ENABLED
107 /* The following lock is used for both the list of sources
108 * and the list of poll records
119 GPtrArray *pending_dispatches;
120 gint timeout; /* Timeout for current iteration */
123 GSource *source_list;
124 gint in_check_or_prepare;
126 GPollRec *poll_records;
127 GPollRec *poll_free_list;
128 GMemChunk *poll_chunk;
129 guint n_poll_records;
130 GPollFD *cached_poll_array;
131 guint cached_poll_array_size;
133 #ifdef G_THREADS_ENABLED
135 /* this pipe is used to wake up the main loop when a source is added.
137 gint wake_up_pipe[2];
138 #else /* G_OS_WIN32 */
139 HANDLE wake_up_semaphore;
140 #endif /* G_OS_WIN32 */
143 gboolean poll_waiting;
145 /* Flag indicating whether the set of fd's changed during a poll */
146 gboolean poll_changed;
147 #endif /* G_THREADS_ENABLED */
151 GTimeVal current_time;
152 gboolean time_is_current;
155 struct _GSourceCallback
160 GDestroyNotify notify;
165 GMainContext *context;
170 struct _GTimeoutSource
177 struct _GChildWatchSource
184 #else /* G_OS_WIN32 */
186 gboolean child_exited;
187 #endif /* G_OS_WIN32 */
197 #ifdef G_THREADS_ENABLED
198 #define LOCK_CONTEXT(context) g_static_mutex_lock (&context->mutex)
199 #define UNLOCK_CONTEXT(context) g_static_mutex_unlock (&context->mutex)
200 #define G_THREAD_SELF g_thread_self ()
202 #define LOCK_CONTEXT(context) (void)0
203 #define UNLOCK_CONTEXT(context) (void)0
204 #define G_THREAD_SELF NULL
207 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
208 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
209 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
211 #define SOURCE_UNREF(source, context) \
213 if ((source)->ref_count > 1) \
214 (source)->ref_count--; \
216 g_source_unref_internal ((source), (context), TRUE); \
220 /* Forward declarations */
222 static void g_source_unref_internal (GSource *source,
223 GMainContext *context,
225 static void g_source_destroy_internal (GSource *source,
226 GMainContext *context,
228 static void g_main_context_poll (GMainContext *context,
233 static void g_main_context_add_poll_unlocked (GMainContext *context,
236 static void g_main_context_remove_poll_unlocked (GMainContext *context,
238 static void g_main_context_wakeup_unlocked (GMainContext *context);
240 static gboolean g_timeout_prepare (GSource *source,
242 static gboolean g_timeout_check (GSource *source);
243 static gboolean g_timeout_dispatch (GSource *source,
244 GSourceFunc callback,
246 static gboolean g_child_watch_prepare (GSource *source,
248 static gboolean g_child_watch_check (GSource *source);
249 static gboolean g_child_watch_dispatch (GSource *source,
250 GSourceFunc callback,
252 static gboolean g_idle_prepare (GSource *source,
254 static gboolean g_idle_check (GSource *source);
255 static gboolean g_idle_dispatch (GSource *source,
256 GSourceFunc callback,
259 G_LOCK_DEFINE_STATIC (main_loop);
260 static GMainContext *default_main_context;
261 static GSList *main_contexts_without_pipe = NULL;
264 /* Child status monitoring code */
266 CHILD_WATCH_UNINITIALIZED,
267 CHILD_WATCH_INITIALIZED_SINGLE,
268 CHILD_WATCH_INITIALIZED_THREADED
270 static gint child_watch_init_state = CHILD_WATCH_UNINITIALIZED;
271 static gint child_watch_count = 1;
272 static gint child_watch_wake_up_pipe[2] = {0, 0};
273 #endif /* !G_OS_WIN32 */
274 G_LOCK_DEFINE_STATIC (main_context_list);
275 static GSList *main_context_list = NULL;
277 GSourceFuncs g_timeout_funcs =
285 GSourceFuncs g_child_watch_funcs =
287 g_child_watch_prepare,
289 g_child_watch_dispatch,
293 GSourceFuncs g_idle_funcs =
302 /* SunOS has poll, but doesn't provide a prototype. */
303 # if defined (sun) && !defined (__SVR4)
304 extern gint poll (GPollFD *ufds, guint nfsd, gint timeout);
306 #else /* !HAVE_POLL */
311 g_poll (GPollFD *fds,
315 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
316 gboolean poll_msgs = FALSE;
323 for (f = fds; f < &fds[nfds]; ++f)
326 if (f->fd == G_WIN32_MSG_HANDLE)
328 else if (nhandles == MAXIMUM_WAIT_OBJECTS)
330 g_warning (G_STRLOC ": Too many handles to wait for!\n");
335 #ifdef G_MAIN_POLL_DEBUG
336 g_print ("g_poll: waiting for %#x\n", f->fd);
338 handles[nhandles++] = (HANDLE) f->fd;
347 /* Waiting for messages, and maybe events
348 * -> First PeekMessage
350 #ifdef G_MAIN_POLL_DEBUG
351 g_print ("PeekMessage\n");
353 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
354 ready = WAIT_OBJECT_0 + nhandles;
359 /* Waiting just for messages */
360 if (timeout == INFINITE)
365 #ifdef G_MAIN_POLL_DEBUG
366 g_print ("WaitMessage\n");
370 gchar *emsg = g_win32_error_message (GetLastError ());
371 g_warning (G_STRLOC ": WaitMessage() failed: %s", emsg);
374 ready = WAIT_OBJECT_0 + nhandles;
376 else if (timeout == 0)
378 /* Waiting just for messages, zero timeout.
379 * If we got here, there was no message
381 ready = WAIT_TIMEOUT;
385 /* Waiting just for messages, some timeout
386 * -> Set a timer, wait for message,
387 * kill timer, use PeekMessage
389 timer = SetTimer (NULL, 0, timeout, NULL);
392 gchar *emsg = g_win32_error_message (GetLastError ());
393 g_warning (G_STRLOC ": SetTimer() failed: %s", emsg);
395 ready = WAIT_TIMEOUT;
399 #ifdef G_MAIN_POLL_DEBUG
400 g_print ("WaitMessage\n");
403 KillTimer (NULL, timer);
404 #ifdef G_MAIN_POLL_DEBUG
405 g_print ("PeekMessage\n");
407 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE)
408 && msg.message != WM_TIMER)
409 ready = WAIT_OBJECT_0;
411 ready = WAIT_TIMEOUT;
417 /* Wait for either message or event
418 * -> Use MsgWaitForMultipleObjects
420 #ifdef G_MAIN_POLL_DEBUG
421 g_print ("MsgWaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
423 ready = MsgWaitForMultipleObjects (nhandles, handles, FALSE,
424 timeout, QS_ALLINPUT);
426 if (ready == WAIT_FAILED)
428 gchar *emsg = g_win32_error_message (GetLastError ());
429 g_warning (G_STRLOC ": MsgWaitForMultipleObjects() failed: %s", emsg);
435 else if (nhandles == 0)
437 /* Wait for nothing (huh?) */
442 /* Wait for just events
443 * -> Use WaitForMultipleObjects
445 #ifdef G_MAIN_POLL_DEBUG
446 g_print ("WaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
448 ready = WaitForMultipleObjects (nhandles, handles, FALSE, timeout);
449 if (ready == WAIT_FAILED)
451 gchar *emsg = g_win32_error_message (GetLastError ());
452 g_warning (G_STRLOC ": WaitForMultipleObjects() failed: %s", emsg);
457 #ifdef G_MAIN_POLL_DEBUG
458 g_print ("wait returns %ld%s\n",
460 (ready == WAIT_FAILED ? " (WAIT_FAILED)" :
461 (ready == WAIT_TIMEOUT ? " (WAIT_TIMEOUT)" :
462 (poll_msgs && ready == WAIT_OBJECT_0 + nhandles ? " (msg)" : ""))));
464 for (f = fds; f < &fds[nfds]; ++f)
467 if (ready == WAIT_FAILED)
469 else if (ready == WAIT_TIMEOUT)
471 else if (poll_msgs && ready == WAIT_OBJECT_0 + nhandles)
473 for (f = fds; f < &fds[nfds]; ++f)
476 if (f->events & G_IO_IN)
477 if (f->fd == G_WIN32_MSG_HANDLE)
478 f->revents |= G_IO_IN;
481 else if (ready >= WAIT_OBJECT_0 && ready < WAIT_OBJECT_0 + nhandles)
482 for (f = fds; f < &fds[nfds]; ++f)
484 if (f->fd == (gint) handles[ready - WAIT_OBJECT_0])
486 f->revents = f->events;
487 #ifdef G_MAIN_POLL_DEBUG
488 g_print ("g_poll: got event %#x\n", f->fd);
496 #else /* !G_OS_WIN32 */
498 /* The following implementation of poll() comes from the GNU C Library.
499 * Copyright (C) 1994, 1996, 1997 Free Software Foundation, Inc.
502 #include <string.h> /* for bzero on BSD systems */
504 #ifdef HAVE_SYS_SELECT_H
505 #include <sys/select.h>
506 #endif /* HAVE_SYS_SELECT_H */
510 #endif /* G_OS_BEOS */
513 # define SELECT_MASK fd_set
514 #else /* !NO_FD_SET */
516 typedef long fd_mask;
519 # define SELECT_MASK void
521 # define SELECT_MASK int
522 # endif /* !_IBMR2 */
523 #endif /* !NO_FD_SET */
526 g_poll (GPollFD *fds,
531 SELECT_MASK rset, wset, xset;
540 for (f = fds; f < &fds[nfds]; ++f)
543 if (f->events & G_IO_IN)
544 FD_SET (f->fd, &rset);
545 if (f->events & G_IO_OUT)
546 FD_SET (f->fd, &wset);
547 if (f->events & G_IO_PRI)
548 FD_SET (f->fd, &xset);
549 if (f->fd > maxfd && (f->events & (G_IO_IN|G_IO_OUT|G_IO_PRI)))
553 tv.tv_sec = timeout / 1000;
554 tv.tv_usec = (timeout % 1000) * 1000;
556 ready = select (maxfd + 1, &rset, &wset, &xset,
557 timeout == -1 ? NULL : &tv);
559 for (f = fds; f < &fds[nfds]; ++f)
564 if (FD_ISSET (f->fd, &rset))
565 f->revents |= G_IO_IN;
566 if (FD_ISSET (f->fd, &wset))
567 f->revents |= G_IO_OUT;
568 if (FD_ISSET (f->fd, &xset))
569 f->revents |= G_IO_PRI;
576 #endif /* !G_OS_WIN32 */
578 #endif /* !HAVE_POLL */
581 * g_main_context_ref:
582 * @context: a #GMainContext
584 * Increases the reference count on a #GMainContext object by one.
586 * Returns: the @context that was passed in (since 2.6)
589 g_main_context_ref (GMainContext *context)
591 g_return_val_if_fail (context != NULL, NULL);
592 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
594 g_atomic_int_inc (&context->ref_count);
599 /* If DISABLE_MEM_POOLS is defined, then freeing the
600 * mem chunk won't free the records, so we have to
601 * do it manually. The conditionalization here is
602 * an optimization; g_mem_chunk_free() is a no-op
603 * when DISABLE_MEM_POOLS is set.
605 #ifdef DISABLE_MEM_POOLS
607 poll_rec_list_free (GMainContext *context,
612 GPollRec *tmp_rec = list;
614 g_chunk_free (tmp_rec, context->poll_chunk);
617 #endif /* DISABLE_MEM_POOLS */
620 * g_main_context_unref:
621 * @context: a #GMainContext
623 * Decreases the reference count on a #GMainContext object by one. If
624 * the result is zero, free the context and free all associated memory.
627 g_main_context_unref (GMainContext *context)
630 g_return_if_fail (context != NULL);
631 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
633 if (!g_atomic_int_dec_and_test (&context->ref_count))
636 G_LOCK (main_context_list);
637 main_context_list = g_slist_remove (main_context_list, context);
638 G_UNLOCK (main_context_list);
640 source = context->source_list;
643 GSource *next = source->next;
644 g_source_destroy_internal (source, context, TRUE);
648 #ifdef G_THREADS_ENABLED
649 g_static_mutex_free (&context->mutex);
652 g_ptr_array_free (context->pending_dispatches, TRUE);
653 g_free (context->cached_poll_array);
655 #ifdef DISABLE_MEM_POLLS
656 poll_rec_list_free (context, context->poll_records);
657 poll_rec_list_free (context, context->poll_free_list);
658 #endif /* DISABLE_MEM_POOLS */
660 if (context->poll_chunk)
661 g_mem_chunk_destroy (context->poll_chunk);
663 #ifdef G_THREADS_ENABLED
664 if (g_thread_supported())
667 close (context->wake_up_pipe[0]);
668 close (context->wake_up_pipe[1]);
670 CloseHandle (context->wake_up_semaphore);
674 main_contexts_without_pipe = g_slist_remove (main_contexts_without_pipe,
681 #ifdef G_THREADS_ENABLED
683 g_main_context_init_pipe (GMainContext *context)
686 if (context->wake_up_pipe[0] != -1)
688 if (pipe (context->wake_up_pipe) < 0)
689 g_error ("Cannot create pipe main loop wake-up: %s\n",
692 context->wake_up_rec.fd = context->wake_up_pipe[0];
693 context->wake_up_rec.events = G_IO_IN;
695 if (context->wake_up_semaphore != NULL)
697 context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
698 if (context->wake_up_semaphore == NULL)
699 g_error ("Cannot create wake-up semaphore: %s",
700 g_win32_error_message (GetLastError ()));
701 context->wake_up_rec.fd = (gint) context->wake_up_semaphore;
702 context->wake_up_rec.events = G_IO_IN;
703 # ifdef G_MAIN_POLL_DEBUG
704 g_print ("wake-up semaphore: %#x\n", (guint) context->wake_up_semaphore);
707 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
711 _g_main_thread_init (void)
713 GSList *curr = main_contexts_without_pipe;
716 g_main_context_init_pipe ((GMainContext *)curr->data);
719 g_slist_free (main_contexts_without_pipe);
720 main_contexts_without_pipe = NULL;
722 #endif /* G_THREADS_ENABLED */
725 * g_main_context_new:
727 * Creates a new #GMainContext strcuture
729 * Return value: the new #GMainContext
732 g_main_context_new (void)
734 GMainContext *context = g_new0 (GMainContext, 1);
736 #ifdef G_THREADS_ENABLED
737 g_static_mutex_init (&context->mutex);
739 context->owner = NULL;
740 context->waiters = NULL;
743 context->wake_up_pipe[0] = -1;
744 context->wake_up_pipe[1] = -1;
746 context->wake_up_semaphore = NULL;
750 context->ref_count = 1;
752 context->next_id = 1;
754 context->source_list = NULL;
757 context->poll_func = (GPollFunc)poll;
759 context->poll_func = g_poll;
762 context->cached_poll_array = NULL;
763 context->cached_poll_array_size = 0;
765 context->pending_dispatches = g_ptr_array_new ();
767 context->time_is_current = FALSE;
769 #ifdef G_THREADS_ENABLED
770 if (g_thread_supported ())
771 g_main_context_init_pipe (context);
773 main_contexts_without_pipe = g_slist_prepend (main_contexts_without_pipe,
777 G_LOCK (main_context_list);
778 main_context_list = g_slist_append (main_context_list, context);
779 G_UNLOCK (main_context_list);
785 * g_main_context_default:
787 * Returns the default main context. This is the main context used
788 * for main loop functions when a main loop is not explicitly
791 * Return value: the default main context.
794 g_main_context_default (void)
800 if (!default_main_context)
801 default_main_context = g_main_context_new ();
803 G_UNLOCK (main_loop);
805 return default_main_context;
808 /* Hooks for adding to the main loop */
812 * @source_funcs: structure containing functions that implement
813 * the sources behavior.
814 * @struct_size: size of the #GSource structure to create.
816 * Creates a new #GSource structure. The size is specified to
817 * allow creating structures derived from #GSource that contain
818 * additional data. The size passed in must be at least
819 * <literal>sizeof (GSource)</literal>.
821 * The source will not initially be associated with any #GMainContext
822 * and must be added to one with g_source_attach() before it will be
825 * Return value: the newly-created #GSource.
828 g_source_new (GSourceFuncs *source_funcs,
833 g_return_val_if_fail (source_funcs != NULL, NULL);
834 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
836 source = (GSource*) g_malloc0 (struct_size);
838 source->source_funcs = source_funcs;
839 source->ref_count = 1;
841 source->priority = G_PRIORITY_DEFAULT;
843 source->flags = G_HOOK_FLAG_ACTIVE;
845 /* NULL/0 initialization for all other fields */
850 /* Holds context's lock
853 g_source_list_add (GSource *source,
854 GMainContext *context)
856 GSource *tmp_source, *last_source;
859 tmp_source = context->source_list;
860 while (tmp_source && tmp_source->priority <= source->priority)
862 last_source = tmp_source;
863 tmp_source = tmp_source->next;
866 source->next = tmp_source;
868 tmp_source->prev = source;
870 source->prev = last_source;
872 last_source->next = source;
874 context->source_list = source;
877 /* Holds context's lock
880 g_source_list_remove (GSource *source,
881 GMainContext *context)
884 source->prev->next = source->next;
886 context->source_list = source->next;
889 source->next->prev = source->prev;
897 * @source: a #GSource
898 * @context: a #GMainContext (if %NULL, the default context will be used)
900 * Adds a #GSource to a @context so that it will be executed within
903 * Return value: the ID for the source within the #GMainContext
906 g_source_attach (GSource *source,
907 GMainContext *context)
912 g_return_val_if_fail (source->context == NULL, 0);
913 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
916 context = g_main_context_default ();
918 LOCK_CONTEXT (context);
920 source->context = context;
921 result = source->source_id = context->next_id++;
924 g_source_list_add (source, context);
926 tmp_list = source->poll_fds;
929 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
930 tmp_list = tmp_list->next;
933 #ifdef G_THREADS_ENABLED
934 /* Now wake up the main loop if it is waiting in the poll() */
935 g_main_context_wakeup_unlocked (context);
938 UNLOCK_CONTEXT (context);
944 g_source_destroy_internal (GSource *source,
945 GMainContext *context,
949 LOCK_CONTEXT (context);
951 if (!SOURCE_DESTROYED (source))
954 gpointer old_cb_data;
955 GSourceCallbackFuncs *old_cb_funcs;
957 source->flags &= ~G_HOOK_FLAG_ACTIVE;
959 old_cb_data = source->callback_data;
960 old_cb_funcs = source->callback_funcs;
962 source->callback_data = NULL;
963 source->callback_funcs = NULL;
967 UNLOCK_CONTEXT (context);
968 old_cb_funcs->unref (old_cb_data);
969 LOCK_CONTEXT (context);
972 if (!SOURCE_BLOCKED (source))
974 tmp_list = source->poll_fds;
977 g_main_context_remove_poll_unlocked (context, tmp_list->data);
978 tmp_list = tmp_list->next;
982 g_source_unref_internal (source, context, TRUE);
986 UNLOCK_CONTEXT (context);
991 * @source: a #GSource
993 * Removes a source from its #GMainContext, if any, and mark it as
994 * destroyed. The source cannot be subsequently added to another
998 g_source_destroy (GSource *source)
1000 GMainContext *context;
1002 g_return_if_fail (source != NULL);
1004 context = source->context;
1007 g_source_destroy_internal (source, context, FALSE);
1009 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1014 * @source: a #GSource
1016 * Returns the numeric ID for a particular source. The ID of a source
1017 * is unique within a particular main loop context. The reverse
1018 * mapping from ID to source is done by g_main_context_find_source_by_id().
1020 * Return value: the ID for the source
1023 g_source_get_id (GSource *source)
1027 g_return_val_if_fail (source != NULL, 0);
1028 g_return_val_if_fail (source->context != NULL, 0);
1030 LOCK_CONTEXT (source->context);
1031 result = source->source_id;
1032 UNLOCK_CONTEXT (source->context);
1038 * g_source_get_context:
1039 * @source: a #GSource
1041 * Gets the #GMainContext with which the source is associated.
1042 * Calling this function on a destroyed source is an error.
1044 * Return value: the #GMainContext with which the source is associated,
1045 * or %NULL if the context has not yet been added
1049 g_source_get_context (GSource *source)
1051 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1053 return source->context;
1057 * g_source_add_poll:
1058 * @source:a #GSource
1059 * @fd: a #GPollFD structure holding information about a file
1060 * descriptor to watch.
1062 * Adds a file descriptor to the set of file descriptors polled for
1063 * this source. This is usually combined with g_source_new() to add an
1064 * event source. The event source's check function will typically test
1065 * the @revents field in the #GPollFD struct and return %TRUE if events need
1069 g_source_add_poll (GSource *source,
1072 GMainContext *context;
1074 g_return_if_fail (source != NULL);
1075 g_return_if_fail (fd != NULL);
1076 g_return_if_fail (!SOURCE_DESTROYED (source));
1078 context = source->context;
1081 LOCK_CONTEXT (context);
1083 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1087 if (!SOURCE_BLOCKED (source))
1088 g_main_context_add_poll_unlocked (context, source->priority, fd);
1089 UNLOCK_CONTEXT (context);
1094 * g_source_remove_poll:
1095 * @source:a #GSource
1096 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1098 * Removes a file descriptor from the set of file descriptors polled for
1102 g_source_remove_poll (GSource *source,
1105 GMainContext *context;
1107 g_return_if_fail (source != NULL);
1108 g_return_if_fail (fd != NULL);
1109 g_return_if_fail (!SOURCE_DESTROYED (source));
1111 context = source->context;
1114 LOCK_CONTEXT (context);
1116 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1120 if (!SOURCE_BLOCKED (source))
1121 g_main_context_remove_poll_unlocked (context, fd);
1122 UNLOCK_CONTEXT (context);
1127 * g_source_set_callback_indirect:
1128 * @source: the source
1129 * @callback_data: pointer to callback data "object"
1130 * @callback_funcs: functions for reference counting @callback_data
1131 * and getting the callback and data
1133 * Sets the callback function storing the data as a refcounted callback
1134 * "object". This is used internally. Note that calling
1135 * g_source_set_callback_indirect() assumes
1136 * an initial reference count on @callback_data, and thus
1137 * @callback_funcs->unref will eventually be called once more
1138 * than @callback_funcs->ref.
1141 g_source_set_callback_indirect (GSource *source,
1142 gpointer callback_data,
1143 GSourceCallbackFuncs *callback_funcs)
1145 GMainContext *context;
1146 gpointer old_cb_data;
1147 GSourceCallbackFuncs *old_cb_funcs;
1149 g_return_if_fail (source != NULL);
1150 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1152 context = source->context;
1155 LOCK_CONTEXT (context);
1157 old_cb_data = source->callback_data;
1158 old_cb_funcs = source->callback_funcs;
1160 source->callback_data = callback_data;
1161 source->callback_funcs = callback_funcs;
1164 UNLOCK_CONTEXT (context);
1167 old_cb_funcs->unref (old_cb_data);
1171 g_source_callback_ref (gpointer cb_data)
1173 GSourceCallback *callback = cb_data;
1175 callback->ref_count++;
1180 g_source_callback_unref (gpointer cb_data)
1182 GSourceCallback *callback = cb_data;
1184 callback->ref_count--;
1185 if (callback->ref_count == 0)
1187 if (callback->notify)
1188 callback->notify (callback->data);
1194 g_source_callback_get (gpointer cb_data,
1199 GSourceCallback *callback = cb_data;
1201 *func = callback->func;
1202 *data = callback->data;
1205 static GSourceCallbackFuncs g_source_callback_funcs = {
1206 g_source_callback_ref,
1207 g_source_callback_unref,
1208 g_source_callback_get,
1212 * g_source_set_callback:
1213 * @source: the source
1214 * @func: a callback function
1215 * @data: the data to pass to callback function
1216 * @notify: a function to call when @data is no longer in use, or %NULL.
1218 * Sets the callback function for a source. The callback for a source is
1219 * called from the source's dispatch function.
1221 * The exact type of @func depends on the type of source; ie. you
1222 * should not count on @func being called with @data as its first
1225 * Typically, you won't use this function. Instead use functions specific
1226 * to the type of source you are using.
1229 g_source_set_callback (GSource *source,
1232 GDestroyNotify notify)
1234 GSourceCallback *new_callback;
1236 g_return_if_fail (source != NULL);
1238 new_callback = g_new (GSourceCallback, 1);
1240 new_callback->ref_count = 1;
1241 new_callback->func = func;
1242 new_callback->data = data;
1243 new_callback->notify = notify;
1245 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1249 * g_source_set_priority:
1250 * @source: a #GSource
1251 * @priority: the new priority.
1253 * Sets the priority of a source. While the main loop is being
1254 * run, a source will be dispatched if it is ready to be dispatched and no sources
1255 * at a higher (numerically smaller) priority are ready to be dispatched.
1258 g_source_set_priority (GSource *source,
1262 GMainContext *context;
1264 g_return_if_fail (source != NULL);
1266 context = source->context;
1269 LOCK_CONTEXT (context);
1271 source->priority = priority;
1275 /* Remove the source from the context's source and then
1276 * add it back so it is sorted in the correct plcae
1278 g_source_list_remove (source, source->context);
1279 g_source_list_add (source, source->context);
1281 if (!SOURCE_BLOCKED (source))
1283 tmp_list = source->poll_fds;
1286 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1287 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1289 tmp_list = tmp_list->next;
1293 UNLOCK_CONTEXT (source->context);
1298 * g_source_get_priority:
1299 * @source: a #GSource
1301 * Gets the priority of a source.
1303 * Return value: the priority of the source
1306 g_source_get_priority (GSource *source)
1308 g_return_val_if_fail (source != NULL, 0);
1310 return source->priority;
1314 * g_source_set_can_recurse:
1315 * @source: a #GSource
1316 * @can_recurse: whether recursion is allowed for this source
1318 * Sets whether a source can be called recursively. If @can_recurse is
1319 * %TRUE, then while the source is being dispatched then this source
1320 * will be processed normally. Otherwise, all processing of this
1321 * source is blocked until the dispatch function returns.
1324 g_source_set_can_recurse (GSource *source,
1325 gboolean can_recurse)
1327 GMainContext *context;
1329 g_return_if_fail (source != NULL);
1331 context = source->context;
1334 LOCK_CONTEXT (context);
1337 source->flags |= G_SOURCE_CAN_RECURSE;
1339 source->flags &= ~G_SOURCE_CAN_RECURSE;
1342 UNLOCK_CONTEXT (context);
1346 * g_source_get_can_recurse:
1347 * @source: a #GSource
1349 * Checks whether a source is allowed to be called recursively.
1350 * see g_source_set_can_recurse().
1352 * Return value: whether recursion is allowed.
1355 g_source_get_can_recurse (GSource *source)
1357 g_return_val_if_fail (source != NULL, FALSE);
1359 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1364 * @source: a #GSource
1366 * Increases the reference count on a source by one.
1368 * Return value: @source
1371 g_source_ref (GSource *source)
1373 GMainContext *context;
1375 g_return_val_if_fail (source != NULL, NULL);
1377 context = source->context;
1380 LOCK_CONTEXT (context);
1382 source->ref_count++;
1385 UNLOCK_CONTEXT (context);
1390 /* g_source_unref() but possible to call within context lock
1393 g_source_unref_internal (GSource *source,
1394 GMainContext *context,
1397 gpointer old_cb_data = NULL;
1398 GSourceCallbackFuncs *old_cb_funcs = NULL;
1400 g_return_if_fail (source != NULL);
1402 if (!have_lock && context)
1403 LOCK_CONTEXT (context);
1405 source->ref_count--;
1406 if (source->ref_count == 0)
1408 old_cb_data = source->callback_data;
1409 old_cb_funcs = source->callback_funcs;
1411 source->callback_data = NULL;
1412 source->callback_funcs = NULL;
1414 if (context && !SOURCE_DESTROYED (source))
1416 g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1417 source->ref_count++;
1420 g_source_list_remove (source, context);
1422 if (source->source_funcs->finalize)
1423 source->source_funcs->finalize (source);
1425 g_slist_free (source->poll_fds);
1426 source->poll_fds = NULL;
1430 if (!have_lock && context)
1431 UNLOCK_CONTEXT (context);
1436 UNLOCK_CONTEXT (context);
1438 old_cb_funcs->unref (old_cb_data);
1441 LOCK_CONTEXT (context);
1447 * @source: a #GSource
1449 * Decreases the reference count of a source by one. If the
1450 * resulting reference count is zero the source and associated
1451 * memory will be destroyed.
1454 g_source_unref (GSource *source)
1456 g_return_if_fail (source != NULL);
1458 g_source_unref_internal (source, source->context, FALSE);
1462 * g_main_context_find_source_by_id:
1463 * @context: a #GMainContext (if %NULL, the default context will be used)
1464 * @source_id: the source ID, as returned by g_source_get_id()
1466 * Finds a #GSource given a pair of context and ID
1468 * Return value: the #GSource if found, otherwise, %NULL
1471 g_main_context_find_source_by_id (GMainContext *context,
1476 g_return_val_if_fail (source_id > 0, NULL);
1478 if (context == NULL)
1479 context = g_main_context_default ();
1481 LOCK_CONTEXT (context);
1483 source = context->source_list;
1486 if (!SOURCE_DESTROYED (source) &&
1487 source->source_id == source_id)
1489 source = source->next;
1492 UNLOCK_CONTEXT (context);
1498 * g_main_context_find_source_by_funcs_user_data:
1499 * @context: a #GMainContext (if %NULL, the default context will be used).
1500 * @funcs: the @source_funcs passed to g_source_new().
1501 * @user_data: the user data from the callback.
1503 * Finds a source with the given source functions and user data. If
1504 * multiple sources exist with the same source function and user data,
1505 * the first one found will be returned.
1507 * Return value: the source, if one was found, otherwise %NULL
1510 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1511 GSourceFuncs *funcs,
1516 g_return_val_if_fail (funcs != NULL, NULL);
1518 if (context == NULL)
1519 context = g_main_context_default ();
1521 LOCK_CONTEXT (context);
1523 source = context->source_list;
1526 if (!SOURCE_DESTROYED (source) &&
1527 source->source_funcs == funcs &&
1528 source->callback_funcs)
1530 GSourceFunc callback;
1531 gpointer callback_data;
1533 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1535 if (callback_data == user_data)
1538 source = source->next;
1541 UNLOCK_CONTEXT (context);
1547 * g_main_context_find_source_by_user_data:
1548 * @context: a #GMainContext
1549 * @user_data: the user_data for the callback.
1551 * Finds a source with the given user data for the callback. If
1552 * multiple sources exist with the same user data, the first
1553 * one found will be returned.
1555 * Return value: the source, if one was found, otherwise %NULL
1558 g_main_context_find_source_by_user_data (GMainContext *context,
1563 if (context == NULL)
1564 context = g_main_context_default ();
1566 LOCK_CONTEXT (context);
1568 source = context->source_list;
1571 if (!SOURCE_DESTROYED (source) &&
1572 source->callback_funcs)
1574 GSourceFunc callback;
1575 gpointer callback_data = NULL;
1577 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1579 if (callback_data == user_data)
1582 source = source->next;
1585 UNLOCK_CONTEXT (context);
1592 * @tag: the id of the source to remove.
1594 * Removes the source with the given id from the default main context. The id of
1595 * a #GSource is given by g_source_get_id(), or will be returned by the
1596 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1597 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1598 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1600 * See also g_source_destroy().
1602 * Return value: %TRUE if the source was found and removed.
1605 g_source_remove (guint tag)
1609 g_return_val_if_fail (tag > 0, FALSE);
1611 source = g_main_context_find_source_by_id (NULL, tag);
1613 g_source_destroy (source);
1615 return source != NULL;
1619 * g_source_remove_by_user_data:
1620 * @user_data: the user_data for the callback.
1622 * Removes a source from the default main loop context given the user
1623 * data for the callback. If multiple sources exist with the same user
1624 * data, only one will be destroyed.
1626 * Return value: %TRUE if a source was found and removed.
1629 g_source_remove_by_user_data (gpointer user_data)
1633 source = g_main_context_find_source_by_user_data (NULL, user_data);
1636 g_source_destroy (source);
1644 * g_source_remove_by_funcs_user_data:
1645 * @funcs: The @source_funcs passed to g_source_new()
1646 * @user_data: the user data for the callback
1648 * Removes a source from the default main loop context given the
1649 * source functions and user data. If multiple sources exist with the
1650 * same source functions and user data, only one will be destroyed.
1652 * Return value: %TRUE if a source was found and removed.
1655 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1660 g_return_val_if_fail (funcs != NULL, FALSE);
1662 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1665 g_source_destroy (source);
1673 * g_get_current_time:
1674 * @result: #GTimeVal structure in which to store current time.
1676 * Equivalent to the UNIX gettimeofday() function, but portable.
1679 g_get_current_time (GTimeVal *result)
1684 g_return_if_fail (result != NULL);
1686 /*this is required on alpha, there the timeval structs are int's
1687 not longs and a cast only would fail horribly*/
1688 gettimeofday (&r, NULL);
1689 result->tv_sec = r.tv_sec;
1690 result->tv_usec = r.tv_usec;
1693 guint64 *time64 = (guint64 *) &ft;
1695 GetSystemTimeAsFileTime (&ft);
1697 /* Convert from 100s of nanoseconds since 1601-01-01
1698 * to Unix epoch. Yes, this is Y2038 unsafe.
1700 *time64 -= G_GINT64_CONSTANT (116444736000000000);
1703 result->tv_sec = *time64 / 1000000;
1704 result->tv_usec = *time64 % 1000000;
1708 /* Running the main loop */
1711 get_depth_pointer (void)
1713 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
1714 gint *depth_pointer = g_static_private_get (&depth_private);
1717 depth_pointer = g_new (gint, 1);
1719 g_static_private_set (&depth_private, depth_pointer, g_free);
1722 return depth_pointer;
1728 * Return value: The main loop recursion level in the current thread
1730 * Returns the depth of the stack of calls to
1731 * g_main_context_dispatch() on any #GMainContext in the current thread.
1732 * That is, when called from the toplevel, it gives 0. When
1733 * called from within a callback from g_main_context_iteration()
1734 * (or g_main_loop_run(), etc.) it returns 1. When called from within
1735 * a callback to a recursive call to g_main_context_iterate(),
1736 * it returns 2. And so forth.
1738 * This function is useful in a situation like the following:
1739 * Imagine an extremely simple "garbage collected" system.
1742 * static GList *free_list;
1745 * allocate_memory (gsize size)
1747 * gpointer result = g_malloc (size);
1748 * free_list = g_list_prepend (free_list, result);
1753 * free_allocated_memory (void)
1756 * for (l = free_list; l; l = l->next);
1758 * g_list_free (free_list);
1766 * g_main_context_iteration (NULL, TRUE);
1767 * free_allocated_memory();
1771 * This works from an application, however, if you want to do the same
1772 * thing from a library, it gets more difficult, since you no longer
1773 * control the main loop. You might think you can simply use an idle
1774 * function to make the call to free_allocated_memory(), but that
1775 * doesn't work, since the idle function could be called from a
1776 * recursive callback. This can be fixed by using g_main_depth()
1780 * allocate_memory (gsize size)
1782 * FreeListBlock *block = g_new (FreeListBlock, 1);\
1783 * block->mem = g_malloc (size);
1784 * block->depth = g_main_depth ();
1785 * free_list = g_list_prepend (free_list, block);
1786 * return block->mem;
1790 * free_allocated_memory (void)
1794 * int depth = g_main_depth ();
1795 * for (l = free_list; l; );
1797 * GList *next = l->next;
1798 * FreeListBlock *block = l->data;
1799 * if (block->depth > depth)
1801 * g_free (block->mem);
1803 * free_list = g_list_delete_link (free_list, l);
1811 * There is a temptation to use g_main_depth() to solve
1812 * problems with reentrancy. For instance, while waiting for data
1813 * to be received from the network in response to a menu item,
1814 * the menu item might be selected again. It might seem that
1815 * one could make the menu item's callback return immediately
1816 * and do nothing if g_main_depth() returns a value greater than 1.
1817 * However, this should be avoided since the user then sees selecting
1818 * the menu item do nothing. Furthermore, you'll find yourself adding
1819 * these checks all over your code, since there are doubtless many,
1820 * many things that the user could do. Instead, you can use the
1821 * following techniques:
1826 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
1827 * the user from interacting with elements while the main
1828 * loop is recursing.
1833 * Avoid main loop recursion in situations where you can't handle
1834 * arbitrary callbacks. Instead, structure your code so that you
1835 * simply return to the main loop and then get called again when
1836 * there is more work to do.
1844 gint *depth = get_depth_pointer ();
1848 /* Temporarily remove all this source's file descriptors from the
1849 * poll(), so that if data comes available for one of the file descriptors
1850 * we don't continually spin in the poll()
1852 /* HOLDS: source->context's lock */
1854 block_source (GSource *source)
1858 g_return_if_fail (!SOURCE_BLOCKED (source));
1860 tmp_list = source->poll_fds;
1863 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
1864 tmp_list = tmp_list->next;
1868 /* HOLDS: source->context's lock */
1870 unblock_source (GSource *source)
1874 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
1875 g_return_if_fail (!SOURCE_DESTROYED (source));
1877 tmp_list = source->poll_fds;
1880 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
1881 tmp_list = tmp_list->next;
1885 /* HOLDS: context's lock */
1887 g_main_dispatch (GMainContext *context)
1889 gint *depth = get_depth_pointer ();
1892 for (i = 0; i < context->pending_dispatches->len; i++)
1894 GSource *source = context->pending_dispatches->pdata[i];
1896 context->pending_dispatches->pdata[i] = NULL;
1899 source->flags &= ~G_SOURCE_READY;
1901 if (!SOURCE_DESTROYED (source))
1903 gboolean was_in_call;
1904 gpointer user_data = NULL;
1905 GSourceFunc callback = NULL;
1906 GSourceCallbackFuncs *cb_funcs;
1908 gboolean need_destroy;
1910 gboolean (*dispatch) (GSource *,
1914 dispatch = source->source_funcs->dispatch;
1915 cb_funcs = source->callback_funcs;
1916 cb_data = source->callback_data;
1919 cb_funcs->ref (cb_data);
1921 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
1922 block_source (source);
1924 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
1925 source->flags |= G_HOOK_FLAG_IN_CALL;
1928 cb_funcs->get (cb_data, source, &callback, &user_data);
1930 UNLOCK_CONTEXT (context);
1933 need_destroy = ! dispatch (source,
1938 LOCK_CONTEXT (context);
1941 cb_funcs->unref (cb_data);
1944 source->flags &= ~G_HOOK_FLAG_IN_CALL;
1946 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
1947 !SOURCE_DESTROYED (source))
1948 unblock_source (source);
1950 /* Note: this depends on the fact that we can't switch
1951 * sources from one main context to another
1953 if (need_destroy && !SOURCE_DESTROYED (source))
1955 g_assert (source->context == context);
1956 g_source_destroy_internal (source, context, TRUE);
1960 SOURCE_UNREF (source, context);
1963 g_ptr_array_set_size (context->pending_dispatches, 0);
1966 /* Holds context's lock */
1967 static inline GSource *
1968 next_valid_source (GMainContext *context,
1971 GSource *new_source = source ? source->next : context->source_list;
1975 if (!SOURCE_DESTROYED (new_source))
1977 new_source->ref_count++;
1981 new_source = new_source->next;
1985 SOURCE_UNREF (source, context);
1991 * g_main_context_acquire:
1992 * @context: a #GMainContext
1994 * Tries to become the owner of the specified context.
1995 * If some other context is the owner of the context,
1996 * returns %FALSE immediately. Ownership is properly
1997 * recursive: the owner can require ownership again
1998 * and will release ownership when g_main_context_release()
1999 * is called as many times as g_main_context_acquire().
2001 * You must be the owner of a context before you
2002 * can call g_main_context_prepare(), g_main_context_query(),
2003 * g_main_context_check(), g_main_context_dispatch().
2005 * Return value: %TRUE if the operation succeeded, and
2006 * this thread is now the owner of @context.
2009 g_main_context_acquire (GMainContext *context)
2011 #ifdef G_THREADS_ENABLED
2012 gboolean result = FALSE;
2013 GThread *self = G_THREAD_SELF;
2015 if (context == NULL)
2016 context = g_main_context_default ();
2018 LOCK_CONTEXT (context);
2020 if (!context->owner)
2022 context->owner = self;
2023 g_assert (context->owner_count == 0);
2026 if (context->owner == self)
2028 context->owner_count++;
2032 UNLOCK_CONTEXT (context);
2035 #else /* !G_THREADS_ENABLED */
2037 #endif /* G_THREADS_ENABLED */
2041 * g_main_context_release:
2042 * @context: a #GMainContext
2044 * Releases ownership of a context previously acquired by this thread
2045 * with g_main_context_acquire(). If the context was acquired multiple
2046 * times, the only release ownership when g_main_context_release()
2047 * is called as many times as it was acquired.
2050 g_main_context_release (GMainContext *context)
2052 #ifdef G_THREADS_ENABLED
2053 if (context == NULL)
2054 context = g_main_context_default ();
2056 LOCK_CONTEXT (context);
2058 context->owner_count--;
2059 if (context->owner_count == 0)
2061 context->owner = NULL;
2063 if (context->waiters)
2065 GMainWaiter *waiter = context->waiters->data;
2066 gboolean loop_internal_waiter =
2067 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
2068 context->waiters = g_slist_delete_link (context->waiters,
2070 if (!loop_internal_waiter)
2071 g_mutex_lock (waiter->mutex);
2073 g_cond_signal (waiter->cond);
2075 if (!loop_internal_waiter)
2076 g_mutex_unlock (waiter->mutex);
2080 UNLOCK_CONTEXT (context);
2081 #endif /* G_THREADS_ENABLED */
2085 * g_main_context_wait:
2086 * @context: a #GMainContext
2087 * @cond: a condition variable
2088 * @mutex: a mutex, currently held
2090 * Tries to become the owner of the specified context,
2091 * as with g_main_context_acquire(). But if another thread
2092 * is the owner, atomically drop @mutex and wait on @cond until
2093 * that owner releases ownership or until @cond is signaled, then
2094 * try again (once) to become the owner.
2096 * Return value: %TRUE if the operation succeeded, and
2097 * this thread is now the owner of @context.
2100 g_main_context_wait (GMainContext *context,
2104 #ifdef G_THREADS_ENABLED
2105 gboolean result = FALSE;
2106 GThread *self = G_THREAD_SELF;
2107 gboolean loop_internal_waiter;
2109 if (context == NULL)
2110 context = g_main_context_default ();
2112 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2114 if (!loop_internal_waiter)
2115 LOCK_CONTEXT (context);
2117 if (context->owner && context->owner != self)
2122 waiter.mutex = mutex;
2124 context->waiters = g_slist_append (context->waiters, &waiter);
2126 if (!loop_internal_waiter)
2127 UNLOCK_CONTEXT (context);
2128 g_cond_wait (cond, mutex);
2129 if (!loop_internal_waiter)
2130 LOCK_CONTEXT (context);
2132 context->waiters = g_slist_remove (context->waiters, &waiter);
2135 if (!context->owner)
2137 context->owner = self;
2138 g_assert (context->owner_count == 0);
2141 if (context->owner == self)
2143 context->owner_count++;
2147 if (!loop_internal_waiter)
2148 UNLOCK_CONTEXT (context);
2151 #else /* !G_THREADS_ENABLED */
2153 #endif /* G_THREADS_ENABLED */
2157 * g_main_context_prepare:
2158 * @context: a #GMainContext
2159 * @priority: location to store priority of highest priority
2160 * source already ready.
2162 * Prepares to poll sources within a main loop. The resulting information
2163 * for polling is determined by calling g_main_context_query ().
2165 * Return value: %TRUE if some source is ready to be dispatched
2169 g_main_context_prepare (GMainContext *context,
2174 gint current_priority = G_MAXINT;
2177 if (context == NULL)
2178 context = g_main_context_default ();
2180 LOCK_CONTEXT (context);
2182 context->time_is_current = FALSE;
2184 if (context->in_check_or_prepare)
2186 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2187 "prepare() member.");
2188 UNLOCK_CONTEXT (context);
2192 #ifdef G_THREADS_ENABLED
2193 if (context->poll_waiting)
2195 g_warning("g_main_context_prepare(): main loop already active in another thread");
2196 UNLOCK_CONTEXT (context);
2200 context->poll_waiting = TRUE;
2201 #endif /* G_THREADS_ENABLED */
2204 /* If recursing, finish up current dispatch, before starting over */
2205 if (context->pending_dispatches)
2208 g_main_dispatch (context, ¤t_time);
2210 UNLOCK_CONTEXT (context);
2215 /* If recursing, clear list of pending dispatches */
2217 for (i = 0; i < context->pending_dispatches->len; i++)
2219 if (context->pending_dispatches->pdata[i])
2220 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2222 g_ptr_array_set_size (context->pending_dispatches, 0);
2224 /* Prepare all sources */
2226 context->timeout = -1;
2228 source = next_valid_source (context, NULL);
2231 gint source_timeout = -1;
2233 if ((n_ready > 0) && (source->priority > current_priority))
2235 SOURCE_UNREF (source, context);
2238 if (SOURCE_BLOCKED (source))
2241 if (!(source->flags & G_SOURCE_READY))
2244 gboolean (*prepare) (GSource *source,
2247 prepare = source->source_funcs->prepare;
2248 context->in_check_or_prepare++;
2249 UNLOCK_CONTEXT (context);
2251 result = (*prepare) (source, &source_timeout);
2253 LOCK_CONTEXT (context);
2254 context->in_check_or_prepare--;
2257 source->flags |= G_SOURCE_READY;
2260 if (source->flags & G_SOURCE_READY)
2263 current_priority = source->priority;
2264 context->timeout = 0;
2267 if (source_timeout >= 0)
2269 if (context->timeout < 0)
2270 context->timeout = source_timeout;
2272 context->timeout = MIN (context->timeout, source_timeout);
2276 source = next_valid_source (context, source);
2279 UNLOCK_CONTEXT (context);
2282 *priority = current_priority;
2284 return (n_ready > 0);
2288 * g_main_context_query:
2289 * @context: a #GMainContext
2290 * @max_priority: maximum priority source to check
2291 * @timeout_: location to store timeout to be used in polling
2292 * @fds: location to store #GPollFD records that need to be polled.
2293 * @n_fds: length of @fds.
2295 * Determines information necessary to poll this main loop.
2297 * Return value: the number of records actually stored in @fds,
2298 * or, if more than @n_fds records need to be stored, the number
2299 * of records that need to be stored.
2302 g_main_context_query (GMainContext *context,
2311 LOCK_CONTEXT (context);
2313 pollrec = context->poll_records;
2315 while (pollrec && max_priority >= pollrec->priority)
2317 if (pollrec->fd->events)
2321 fds[n_poll].fd = pollrec->fd->fd;
2322 /* In direct contradiction to the Unix98 spec, IRIX runs into
2323 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2324 * flags in the events field of the pollfd while it should
2325 * just ignoring them. So we mask them out here.
2327 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2328 fds[n_poll].revents = 0;
2333 pollrec = pollrec->next;
2336 #ifdef G_THREADS_ENABLED
2337 context->poll_changed = FALSE;
2342 *timeout = context->timeout;
2344 context->time_is_current = FALSE;
2347 UNLOCK_CONTEXT (context);
2353 * g_main_context_check:
2354 * @context: a #GMainContext
2355 * @max_priority: the maximum numerical priority of sources to check
2356 * @fds: array of #GPollFD's that was passed to the last call to
2357 * g_main_context_query()
2358 * @n_fds: return value of g_main_context_query()
2360 * Passes the results of polling back to the main loop.
2362 * Return value: %TRUE if some sources are ready to be dispatched.
2365 g_main_context_check (GMainContext *context,
2375 LOCK_CONTEXT (context);
2377 if (context->in_check_or_prepare)
2379 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2380 "prepare() member.");
2381 UNLOCK_CONTEXT (context);
2385 #ifdef G_THREADS_ENABLED
2386 if (!context->poll_waiting)
2390 read (context->wake_up_pipe[0], &a, 1);
2394 context->poll_waiting = FALSE;
2396 /* If the set of poll file descriptors changed, bail out
2397 * and let the main loop rerun
2399 if (context->poll_changed)
2401 UNLOCK_CONTEXT (context);
2404 #endif /* G_THREADS_ENABLED */
2406 pollrec = context->poll_records;
2410 if (pollrec->fd->events)
2412 pollrec->fd->revents = fds[i].revents;
2415 pollrec = pollrec->next;
2418 source = next_valid_source (context, NULL);
2421 if ((n_ready > 0) && (source->priority > max_priority))
2423 SOURCE_UNREF (source, context);
2426 if (SOURCE_BLOCKED (source))
2429 if (!(source->flags & G_SOURCE_READY))
2432 gboolean (*check) (GSource *source);
2434 check = source->source_funcs->check;
2436 context->in_check_or_prepare++;
2437 UNLOCK_CONTEXT (context);
2439 result = (*check) (source);
2441 LOCK_CONTEXT (context);
2442 context->in_check_or_prepare--;
2445 source->flags |= G_SOURCE_READY;
2448 if (source->flags & G_SOURCE_READY)
2450 source->ref_count++;
2451 g_ptr_array_add (context->pending_dispatches, source);
2455 /* never dispatch sources with less priority than the first
2456 * one we choose to dispatch
2458 max_priority = source->priority;
2462 source = next_valid_source (context, source);
2465 UNLOCK_CONTEXT (context);
2471 * g_main_context_dispatch:
2472 * @context: a #GMainContext
2474 * Dispatches all pending sources.
2477 g_main_context_dispatch (GMainContext *context)
2479 LOCK_CONTEXT (context);
2481 if (context->pending_dispatches->len > 0)
2483 g_main_dispatch (context);
2486 UNLOCK_CONTEXT (context);
2489 /* HOLDS context lock */
2491 g_main_context_iterate (GMainContext *context,
2498 gboolean some_ready;
2499 gint nfds, allocated_nfds;
2500 GPollFD *fds = NULL;
2502 UNLOCK_CONTEXT (context);
2504 #ifdef G_THREADS_ENABLED
2505 if (!g_main_context_acquire (context))
2507 gboolean got_ownership;
2509 g_return_val_if_fail (g_thread_supported (), FALSE);
2514 LOCK_CONTEXT (context);
2517 context->cond = g_cond_new ();
2519 got_ownership = g_main_context_wait (context,
2521 g_static_mutex_get_mutex (&context->mutex));
2525 UNLOCK_CONTEXT (context);
2530 LOCK_CONTEXT (context);
2531 #endif /* G_THREADS_ENABLED */
2533 if (!context->cached_poll_array)
2535 context->cached_poll_array_size = context->n_poll_records;
2536 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2539 allocated_nfds = context->cached_poll_array_size;
2540 fds = context->cached_poll_array;
2542 UNLOCK_CONTEXT (context);
2544 g_main_context_prepare (context, &max_priority);
2546 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
2547 allocated_nfds)) > allocated_nfds)
2549 LOCK_CONTEXT (context);
2551 context->cached_poll_array_size = allocated_nfds = nfds;
2552 context->cached_poll_array = fds = g_new (GPollFD, nfds);
2553 UNLOCK_CONTEXT (context);
2559 g_main_context_poll (context, timeout, max_priority, fds, nfds);
2561 some_ready = g_main_context_check (context, max_priority, fds, nfds);
2564 g_main_context_dispatch (context);
2566 #ifdef G_THREADS_ENABLED
2567 g_main_context_release (context);
2568 #endif /* G_THREADS_ENABLED */
2570 LOCK_CONTEXT (context);
2576 * g_main_context_pending:
2577 * @context: a #GMainContext (if %NULL, the default context will be used)
2579 * Checks if any sources have pending events for the given context.
2581 * Return value: %TRUE if events are pending.
2584 g_main_context_pending (GMainContext *context)
2589 context = g_main_context_default();
2591 LOCK_CONTEXT (context);
2592 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
2593 UNLOCK_CONTEXT (context);
2599 * g_main_context_iteration:
2600 * @context: a #GMainContext (if %NULL, the default context will be used)
2601 * @may_block: whether the call may block.
2603 * Runs a single iteration for the given main loop. This involves
2604 * checking to see if any event sources are ready to be processed,
2605 * then if no events sources are ready and @may_block is %TRUE, waiting
2606 * for a source to become ready, then dispatching the highest priority
2607 * events sources that are ready. Note that even when @may_block is %TRUE,
2608 * it is still possible for g_main_context_iteration() to return
2609 * %FALSE, since the the wait may be interrupted for other
2610 * reasons than an event source becoming ready.
2612 * Return value: %TRUE if events were dispatched.
2615 g_main_context_iteration (GMainContext *context, gboolean may_block)
2620 context = g_main_context_default();
2622 LOCK_CONTEXT (context);
2623 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
2624 UNLOCK_CONTEXT (context);
2631 * @context: a #GMainContext (if %NULL, the default context will be used).
2632 * @is_running: set to %TRUE to indicate that the loop is running. This
2633 * is not very important since calling g_main_loop_run() will set this to
2636 * Creates a new #GMainLoop structure.
2638 * Return value: a new #GMainLoop.
2641 g_main_loop_new (GMainContext *context,
2642 gboolean is_running)
2647 context = g_main_context_default();
2649 g_main_context_ref (context);
2651 loop = g_new0 (GMainLoop, 1);
2652 loop->context = context;
2653 loop->is_running = is_running != FALSE;
2654 loop->ref_count = 1;
2661 * @loop: a #GMainLoop
2663 * Increases the reference count on a #GMainLoop object by one.
2665 * Return value: @loop
2668 g_main_loop_ref (GMainLoop *loop)
2670 g_return_val_if_fail (loop != NULL, NULL);
2671 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2673 g_atomic_int_inc (&loop->ref_count);
2679 * g_main_loop_unref:
2680 * @loop: a #GMainLoop
2682 * Decreases the reference count on a #GMainLoop object by one. If
2683 * the result is zero, free the loop and free all associated memory.
2686 g_main_loop_unref (GMainLoop *loop)
2688 g_return_if_fail (loop != NULL);
2689 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2691 if (!g_atomic_int_dec_and_test (&loop->ref_count))
2694 g_main_context_unref (loop->context);
2700 * @loop: a #GMainLoop
2702 * Runs a main loop until g_main_loop_quit() is called on the loop.
2703 * If this is called for the thread of the loop's #GMainContext,
2704 * it will process events from the loop, otherwise it will
2708 g_main_loop_run (GMainLoop *loop)
2710 GThread *self = G_THREAD_SELF;
2712 g_return_if_fail (loop != NULL);
2713 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2715 #ifdef G_THREADS_ENABLED
2716 if (!g_main_context_acquire (loop->context))
2718 gboolean got_ownership = FALSE;
2720 /* Another thread owns this context */
2721 if (!g_thread_supported ())
2723 g_warning ("g_main_loop_run() was called from second thread but "
2724 "g_thread_init() was never called.");
2728 LOCK_CONTEXT (loop->context);
2730 g_atomic_int_inc (&loop->ref_count);
2732 if (!loop->is_running)
2733 loop->is_running = TRUE;
2735 if (!loop->context->cond)
2736 loop->context->cond = g_cond_new ();
2738 while (loop->is_running && !got_ownership)
2739 got_ownership = g_main_context_wait (loop->context,
2740 loop->context->cond,
2741 g_static_mutex_get_mutex (&loop->context->mutex));
2743 if (!loop->is_running)
2745 UNLOCK_CONTEXT (loop->context);
2747 g_main_context_release (loop->context);
2748 g_main_loop_unref (loop);
2752 g_assert (got_ownership);
2755 LOCK_CONTEXT (loop->context);
2756 #endif /* G_THREADS_ENABLED */
2758 if (loop->context->in_check_or_prepare)
2760 g_warning ("g_main_loop_run(): called recursively from within a source's "
2761 "check() or prepare() member, iteration not possible.");
2765 g_atomic_int_inc (&loop->ref_count);
2766 loop->is_running = TRUE;
2767 while (loop->is_running)
2768 g_main_context_iterate (loop->context, TRUE, TRUE, self);
2770 UNLOCK_CONTEXT (loop->context);
2772 #ifdef G_THREADS_ENABLED
2773 g_main_context_release (loop->context);
2774 #endif /* G_THREADS_ENABLED */
2776 g_main_loop_unref (loop);
2781 * @loop: a #GMainLoop
2783 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
2784 * for the loop will return.
2787 g_main_loop_quit (GMainLoop *loop)
2789 g_return_if_fail (loop != NULL);
2790 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2792 LOCK_CONTEXT (loop->context);
2793 loop->is_running = FALSE;
2794 g_main_context_wakeup_unlocked (loop->context);
2796 #ifdef G_THREADS_ENABLED
2797 if (loop->context->cond)
2798 g_cond_broadcast (loop->context->cond);
2799 #endif /* G_THREADS_ENABLED */
2801 UNLOCK_CONTEXT (loop->context);
2805 * g_main_loop_is_running:
2806 * @loop: a #GMainLoop.
2808 * Checks to see if the main loop is currently being run via g_main_loop_run().
2810 * Return value: %TRUE if the mainloop is currently being run.
2813 g_main_loop_is_running (GMainLoop *loop)
2815 g_return_val_if_fail (loop != NULL, FALSE);
2816 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
2818 return loop->is_running;
2822 * g_main_loop_get_context:
2823 * @loop: a #GMainLoop.
2825 * Returns the #GMainContext of @loop.
2827 * Return value: the #GMainContext of @loop
2830 g_main_loop_get_context (GMainLoop *loop)
2832 g_return_val_if_fail (loop != NULL, NULL);
2833 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2835 return loop->context;
2838 /* HOLDS: context's lock */
2840 g_main_context_poll (GMainContext *context,
2846 #ifdef G_MAIN_POLL_DEBUG
2852 GPollFunc poll_func;
2854 if (n_fds || timeout != 0)
2856 #ifdef G_MAIN_POLL_DEBUG
2857 g_print ("g_main_poll(%d) timeout: %d\n", n_fds, timeout);
2858 poll_timer = g_timer_new ();
2861 LOCK_CONTEXT (context);
2863 poll_func = context->poll_func;
2865 UNLOCK_CONTEXT (context);
2866 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
2869 g_warning ("poll(2) failed due to: %s.",
2870 g_strerror (errno));
2872 /* If g_poll () returns -1, it has already called g_warning() */
2876 #ifdef G_MAIN_POLL_DEBUG
2877 LOCK_CONTEXT (context);
2879 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
2882 g_timer_elapsed (poll_timer, NULL));
2883 g_timer_destroy (poll_timer);
2884 pollrec = context->poll_records;
2888 if (pollrec->fd->events)
2892 g_print (" [%d:", fds[i].fd);
2893 if (fds[i].revents & G_IO_IN)
2895 if (fds[i].revents & G_IO_OUT)
2897 if (fds[i].revents & G_IO_PRI)
2899 if (fds[i].revents & G_IO_ERR)
2901 if (fds[i].revents & G_IO_HUP)
2903 if (fds[i].revents & G_IO_NVAL)
2909 pollrec = pollrec->next;
2913 UNLOCK_CONTEXT (context);
2915 } /* if (n_fds || timeout != 0) */
2919 * g_main_context_add_poll:
2920 * @context: a #GMainContext (or %NULL for the default context)
2921 * @fd: a #GPollFD structure holding information about a file
2922 * descriptor to watch.
2923 * @priority: the priority for this file descriptor which should be
2924 * the same as the priority used for g_source_attach() to ensure that the
2925 * file descriptor is polled whenever the results may be needed.
2927 * Adds a file descriptor to the set of file descriptors polled for
2928 * this context. This will very seldomly be used directly. Instead
2929 * a typical event source will use g_source_add_poll() instead.
2932 g_main_context_add_poll (GMainContext *context,
2937 context = g_main_context_default ();
2939 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
2940 g_return_if_fail (fd);
2942 LOCK_CONTEXT (context);
2943 g_main_context_add_poll_unlocked (context, priority, fd);
2944 UNLOCK_CONTEXT (context);
2947 /* HOLDS: main_loop_lock */
2949 g_main_context_add_poll_unlocked (GMainContext *context,
2953 GPollRec *lastrec, *pollrec, *newrec;
2955 if (!context->poll_chunk)
2956 context->poll_chunk = g_mem_chunk_create (GPollRec, 32, G_ALLOC_ONLY);
2958 if (context->poll_free_list)
2960 newrec = context->poll_free_list;
2961 context->poll_free_list = newrec->next;
2964 newrec = g_chunk_new (GPollRec, context->poll_chunk);
2966 /* This file descriptor may be checked before we ever poll */
2969 newrec->priority = priority;
2972 pollrec = context->poll_records;
2973 while (pollrec && priority >= pollrec->priority)
2976 pollrec = pollrec->next;
2980 lastrec->next = newrec;
2982 context->poll_records = newrec;
2984 newrec->next = pollrec;
2986 context->n_poll_records++;
2988 #ifdef G_THREADS_ENABLED
2989 context->poll_changed = TRUE;
2991 /* Now wake up the main loop if it is waiting in the poll() */
2992 g_main_context_wakeup_unlocked (context);
2997 * g_main_context_remove_poll:
2998 * @context:a #GMainContext
2999 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3001 * Removes file descriptor from the set of file descriptors to be
3002 * polled for a particular context.
3005 g_main_context_remove_poll (GMainContext *context,
3009 context = g_main_context_default ();
3011 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3012 g_return_if_fail (fd);
3014 LOCK_CONTEXT (context);
3015 g_main_context_remove_poll_unlocked (context, fd);
3016 UNLOCK_CONTEXT (context);
3020 g_main_context_remove_poll_unlocked (GMainContext *context,
3023 GPollRec *pollrec, *lastrec;
3026 pollrec = context->poll_records;
3030 if (pollrec->fd == fd)
3032 if (lastrec != NULL)
3033 lastrec->next = pollrec->next;
3035 context->poll_records = pollrec->next;
3037 #ifdef ENABLE_GC_FRIENDLY
3039 #endif /* ENABLE_GC_FRIENDLY */
3041 pollrec->next = context->poll_free_list;
3042 context->poll_free_list = pollrec;
3044 context->n_poll_records--;
3048 pollrec = pollrec->next;
3051 #ifdef G_THREADS_ENABLED
3052 context->poll_changed = TRUE;
3054 /* Now wake up the main loop if it is waiting in the poll() */
3055 g_main_context_wakeup_unlocked (context);
3060 * g_source_get_current_time:
3061 * @source: a #GSource
3062 * @timeval: #GTimeVal structure in which to store current time.
3064 * Gets the "current time" to be used when checking
3065 * this source. The advantage of calling this function over
3066 * calling g_get_current_time() directly is that when
3067 * checking multiple sources, GLib can cache a single value
3068 * instead of having to repeatedly get the system time.
3071 g_source_get_current_time (GSource *source,
3074 GMainContext *context;
3076 g_return_if_fail (source->context != NULL);
3078 context = source->context;
3080 LOCK_CONTEXT (context);
3082 if (!context->time_is_current)
3084 g_get_current_time (&context->current_time);
3085 context->time_is_current = TRUE;
3088 *timeval = context->current_time;
3090 UNLOCK_CONTEXT (context);
3094 * g_main_context_set_poll_func:
3095 * @context: a #GMainContext
3096 * @func: the function to call to poll all file descriptors
3098 * Sets the function to use to handle polling of file descriptors. It
3099 * will be used instead of the poll() system call
3100 * (or GLib's replacement function, which is used where
3101 * poll() isn't available).
3103 * This function could possibly be used to integrate the GLib event
3104 * loop with an external event loop.
3107 g_main_context_set_poll_func (GMainContext *context,
3111 context = g_main_context_default ();
3113 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3115 LOCK_CONTEXT (context);
3118 context->poll_func = func;
3122 context->poll_func = (GPollFunc) poll;
3124 context->poll_func = (GPollFunc) g_poll;
3128 UNLOCK_CONTEXT (context);
3132 * g_main_context_get_poll_func:
3133 * @context: a #GMainContext
3135 * Gets the poll function set by g_main_context_set_poll_func().
3137 * Return value: the poll function
3140 g_main_context_get_poll_func (GMainContext *context)
3145 context = g_main_context_default ();
3147 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3149 LOCK_CONTEXT (context);
3150 result = context->poll_func;
3151 UNLOCK_CONTEXT (context);
3156 /* HOLDS: context's lock */
3157 /* Wake the main loop up from a poll() */
3159 g_main_context_wakeup_unlocked (GMainContext *context)
3161 #ifdef G_THREADS_ENABLED
3162 if (g_thread_supported() && context->poll_waiting)
3164 context->poll_waiting = FALSE;
3166 write (context->wake_up_pipe[1], "A", 1);
3168 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
3175 * g_main_context_wakeup:
3176 * @context: a #GMainContext
3178 * If @context is currently waiting in a poll(), interrupt
3179 * the poll(), and continue the iteration process.
3182 g_main_context_wakeup (GMainContext *context)
3185 context = g_main_context_default ();
3187 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3189 LOCK_CONTEXT (context);
3190 g_main_context_wakeup_unlocked (context);
3191 UNLOCK_CONTEXT (context);
3197 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3198 GTimeVal *current_time)
3200 guint seconds = timeout_source->interval / 1000;
3201 guint msecs = timeout_source->interval - seconds * 1000;
3203 timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
3204 timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
3205 if (timeout_source->expiration.tv_usec >= 1000000)
3207 timeout_source->expiration.tv_usec -= 1000000;
3208 timeout_source->expiration.tv_sec++;
3213 g_timeout_prepare (GSource *source,
3218 GTimeVal current_time;
3220 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3222 g_source_get_current_time (source, ¤t_time);
3224 sec = timeout_source->expiration.tv_sec - current_time.tv_sec;
3225 msec = (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000;
3227 /* We do the following in a rather convoluted fashion to deal with
3228 * the fact that we don't have an integral type big enough to hold
3229 * the difference of two timevals in millseconds.
3231 if (sec < 0 || (sec == 0 && msec < 0))
3235 glong interval_sec = timeout_source->interval / 1000;
3236 glong interval_msec = timeout_source->interval % 1000;
3244 if (sec > interval_sec ||
3245 (sec == interval_sec && msec > interval_msec))
3247 /* The system time has been set backwards, so we
3248 * reset the expiration time to now + timeout_source->interval;
3249 * this at least avoids hanging for long periods of time.
3251 g_timeout_set_expiration (timeout_source, ¤t_time);
3252 msec = MIN (G_MAXINT, timeout_source->interval);
3256 msec = MIN (G_MAXINT, (guint)msec + 1000 * (guint)sec);
3260 *timeout = (gint)msec;
3266 g_timeout_check (GSource *source)
3268 GTimeVal current_time;
3269 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3271 g_source_get_current_time (source, ¤t_time);
3273 return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
3274 ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
3275 (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
3279 g_timeout_dispatch (GSource *source,
3280 GSourceFunc callback,
3283 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3287 g_warning ("Timeout source dispatched without callback\n"
3288 "You must call g_source_set_callback().");
3292 if (callback (user_data))
3294 GTimeVal current_time;
3296 g_source_get_current_time (source, ¤t_time);
3297 g_timeout_set_expiration (timeout_source, ¤t_time);
3306 * g_timeout_source_new:
3307 * @interval: the timeout interval in milliseconds.
3309 * Creates a new timeout source.
3311 * The source will not initially be associated with any #GMainContext
3312 * and must be added to one with g_source_attach() before it will be
3315 * Return value: the newly-created timeout source
3318 g_timeout_source_new (guint interval)
3320 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3321 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3322 GTimeVal current_time;
3324 timeout_source->interval = interval;
3326 g_get_current_time (¤t_time);
3327 g_timeout_set_expiration (timeout_source, ¤t_time);
3333 * g_timeout_add_full:
3334 * @priority: the priority of the idle source. Typically this will be in the
3335 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3336 * @interval: the time between calls to the function, in milliseconds
3337 * (1/1000ths of a second)
3338 * @function: function to call
3339 * @data: data to pass to @function
3340 * @notify: function to call when the idle is removed, or %NULL
3342 * Sets a function to be called at regular intervals, with the given
3343 * priority. The function is called repeatedly until it returns
3344 * %FALSE, at which point the timeout is automatically destroyed and
3345 * the function will not be called again. The @notify function is
3346 * called when the timeout is destroyed. The first call to the
3347 * function will be at the end of the first @interval.
3349 * Note that timeout functions may be delayed, due to the processing of other
3350 * event sources. Thus they should not be relied on for precise timing.
3351 * After each call to the timeout function, the time of the next
3352 * timeout is recalculated based on the current time and the given interval
3353 * (it does not try to 'catch up' time lost in delays).
3355 * Return value: the id of event source.
3358 g_timeout_add_full (gint priority,
3360 GSourceFunc function,
3362 GDestroyNotify notify)
3367 g_return_val_if_fail (function != NULL, 0);
3369 source = g_timeout_source_new (interval);
3371 if (priority != G_PRIORITY_DEFAULT)
3372 g_source_set_priority (source, priority);
3374 g_source_set_callback (source, function, data, notify);
3375 id = g_source_attach (source, NULL);
3376 g_source_unref (source);
3383 * @interval: the time between calls to the function, in milliseconds
3384 * (1/1000ths of a second)
3385 * @function: function to call
3386 * @data: data to pass to @function
3388 * Sets a function to be called at regular intervals, with the default
3389 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
3390 * until it returns %FALSE, at which point the timeout is automatically
3391 * destroyed and the function will not be called again. The first call
3392 * to the function will be at the end of the first @interval.
3394 * Note that timeout functions may be delayed, due to the processing of other
3395 * event sources. Thus they should not be relied on for precise timing.
3396 * After each call to the timeout function, the time of the next
3397 * timeout is recalculated based on the current time and the given interval
3398 * (it does not try to 'catch up' time lost in delays).
3400 * Return value: the id of event source.
3403 g_timeout_add (guint32 interval,
3404 GSourceFunc function,
3407 return g_timeout_add_full (G_PRIORITY_DEFAULT,
3408 interval, function, data, NULL);
3411 /* Child watch functions */
3416 g_child_watch_prepare (GSource *source,
3425 g_child_watch_check (GSource *source)
3427 GChildWatchSource *child_watch_source;
3428 gboolean child_exited;
3430 child_watch_source = (GChildWatchSource *) source;
3432 child_exited = child_watch_source->poll.revents & G_IO_IN;
3439 * Note: We do _not_ check for the special value of STILL_ACTIVE
3440 * since we know that the process has exited and doing so runs into
3441 * problems if the child process "happens to return STILL_ACTIVE(259)"
3442 * as Microsoft's Platform SDK puts it.
3444 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
3446 gchar *emsg = g_win32_error_message (GetLastError ());
3447 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
3450 child_watch_source->child_status = -1;
3453 child_watch_source->child_status = child_status;
3456 return child_exited;
3459 #else /* G_OS_WIN32 */
3462 check_for_child_exited (GSource *source)
3464 GChildWatchSource *child_watch_source;
3467 /* protect against another SIGCHLD in the middle of this call */
3468 count = child_watch_count;
3470 child_watch_source = (GChildWatchSource *) source;
3472 if (child_watch_source->child_exited)
3475 if (child_watch_source->count < count)
3479 if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
3481 child_watch_source->child_status = child_status;
3482 child_watch_source->child_exited = TRUE;
3484 child_watch_source->count = count;
3487 return child_watch_source->child_exited;
3491 g_child_watch_prepare (GSource *source,
3494 GChildWatchSource *child_watch_source;
3497 child_watch_source = (GChildWatchSource *) source;
3499 return check_for_child_exited (source);
3504 g_child_watch_check (GSource *source)
3506 GChildWatchSource *child_watch_source;
3508 child_watch_source = (GChildWatchSource *) source;
3510 return check_for_child_exited (source);
3513 #endif /* G_OS_WIN32 */
3516 g_child_watch_dispatch (GSource *source,
3517 GSourceFunc callback,
3520 GChildWatchSource *child_watch_source;
3521 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
3523 child_watch_source = (GChildWatchSource *) source;
3527 g_warning ("Child watch source dispatched without callback\n"
3528 "You must call g_source_set_callback().");
3532 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
3534 /* We never keep a child watch source around as the child is gone */
3541 g_child_watch_signal_handler (int signum)
3543 child_watch_count ++;
3545 if (child_watch_init_state == CHILD_WATCH_INITIALIZED_THREADED)
3547 write (child_watch_wake_up_pipe[1], "B", 1);
3551 /* We count on the signal interrupting the poll in the same thread.
3557 g_child_watch_source_init_single (void)
3559 struct sigaction action;
3561 g_assert (! g_thread_supported());
3562 g_assert (child_watch_init_state == CHILD_WATCH_UNINITIALIZED);
3564 child_watch_init_state = CHILD_WATCH_INITIALIZED_SINGLE;
3566 action.sa_handler = g_child_watch_signal_handler;
3567 sigemptyset (&action.sa_mask);
3568 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
3569 sigaction (SIGCHLD, &action, NULL);
3573 child_watch_helper_thread (gpointer data)
3576 GPollFunc poll_func;
3579 poll_func = (GPollFunc)poll;
3584 fds.fd = child_watch_wake_up_pipe[0];
3585 fds.events = G_IO_IN;
3592 read (child_watch_wake_up_pipe[0], b, 20);
3594 /* We were woken up. Wake up all other contexts in all other threads */
3595 G_LOCK (main_context_list);
3596 for (list = main_context_list; list; list = list->next)
3598 GMainContext *context;
3600 context = list->data;
3601 if (g_atomic_int_get (&context->ref_count) > 0)
3602 /* Due to racing conditions we can find ref_count == 0, in
3603 * that case, however, the context is still not destroyed
3604 * and no poll can be active, otherwise the ref_count
3606 g_main_context_wakeup (context);
3608 G_UNLOCK (main_context_list);
3614 g_child_watch_source_init_multi_threaded (void)
3616 GError *error = NULL;
3617 struct sigaction action;
3619 g_assert (g_thread_supported());
3621 if (pipe (child_watch_wake_up_pipe) < 0)
3622 g_error ("Cannot create wake up pipe: %s\n", g_strerror (errno));
3623 fcntl (child_watch_wake_up_pipe[1], F_SETFL, O_NONBLOCK | fcntl (child_watch_wake_up_pipe[1], F_GETFL));
3625 /* We create a helper thread that polls on the wakeup pipe indefinitely */
3626 /* FIXME: Think this through for races */
3627 if (g_thread_create (child_watch_helper_thread, NULL, FALSE, &error) == NULL)
3628 g_error ("Cannot create a thread to monitor child exit status: %s\n", error->message);
3629 child_watch_init_state = CHILD_WATCH_INITIALIZED_THREADED;
3631 action.sa_handler = g_child_watch_signal_handler;
3632 sigemptyset (&action.sa_mask);
3633 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
3634 sigaction (SIGCHLD, &action, NULL);
3638 g_child_watch_source_init_promote_single_to_threaded (void)
3640 g_child_watch_source_init_multi_threaded ();
3644 g_child_watch_source_init (void)
3646 if (g_thread_supported())
3648 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
3649 g_child_watch_source_init_multi_threaded ();
3650 else if (child_watch_init_state == CHILD_WATCH_INITIALIZED_SINGLE)
3651 g_child_watch_source_init_promote_single_to_threaded ();
3655 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
3656 g_child_watch_source_init_single ();
3660 #endif /* !G_OS_WIN32 */
3663 * g_child_watch_source_new:
3664 * @pid: process id of a child process to watch. On Windows, a HANDLE
3665 * for the process to watch (which actually doesn't have to be a child).
3667 * Creates a new child_watch source.
3669 * The source will not initially be associated with any #GMainContext
3670 * and must be added to one with g_source_attach() before it will be
3673 * Note that on platforms where #GPid must be explicitely closed
3674 * (see g_spawn_close_pid()) @pid must not be closed while the
3675 * source is still active. Typically, you will want to call
3676 * g_spawn_close_pid() in the callback function for the source.
3678 * Return value: the newly-created child watch source
3683 g_child_watch_source_new (GPid pid)
3685 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
3686 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
3689 child_watch_source->poll.fd = (int)pid;
3690 child_watch_source->poll.events = G_IO_IN;
3692 g_source_add_poll (source, &child_watch_source->poll);
3693 #else /* G_OS_WIN32 */
3694 g_child_watch_source_init ();
3695 #endif /* G_OS_WIN32 */
3697 child_watch_source->pid = pid;
3703 * g_child_watch_add_full:
3704 * @priority: the priority of the idle source. Typically this will be in the
3705 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3706 * @pid: process id of a child process to watch
3707 * @function: function to call
3708 * @data: data to pass to @function
3709 * @notify: function to call when the idle is removed, or %NULL
3711 * Sets a function to be called when the child indicated by @pid exits, at a
3712 * default priority, #G_PRIORITY_DEFAULT.
3714 * Note that on platforms where #GPid must be explicitely closed
3715 * (see g_spawn_close_pid()) @pid must not be closed while the
3716 * source is still active. Typically, you will want to call
3717 * g_spawn_close_pid() in the callback function for the source.
3719 * GLib supports only a single callback per process id.
3721 * Return value: the id of event source.
3726 g_child_watch_add_full (gint priority,
3728 GChildWatchFunc function,
3730 GDestroyNotify notify)
3735 g_return_val_if_fail (function != NULL, 0);
3737 source = g_child_watch_source_new (pid);
3739 if (priority != G_PRIORITY_DEFAULT)
3740 g_source_set_priority (source, priority);
3742 g_source_set_callback (source, (GSourceFunc) function, data, notify);
3743 id = g_source_attach (source, NULL);
3744 g_source_unref (source);
3750 * g_child_watch_add:
3751 * @pid: process id of a child process to watch
3752 * @function: function to call
3753 * @data: data to pass to @function
3755 * Sets a function to be called when the child indicated by @pid exits, at a
3756 * default priority, #G_PRIORITY_DEFAULT.
3758 * Note that on platforms where #GPid must be explicitely closed
3759 * (see g_spawn_close_pid()) @pid must not be closed while the
3760 * source is still active. Typically, you will want to call
3761 * g_spawn_close_pid() in the callback function for the source.
3763 * GLib supports only a single callback per process id.
3765 * Return value: the id of event source.
3770 g_child_watch_add (GPid pid,
3771 GChildWatchFunc function,
3774 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
3778 /* Idle functions */
3781 g_idle_prepare (GSource *source,
3790 g_idle_check (GSource *source)
3796 g_idle_dispatch (GSource *source,
3797 GSourceFunc callback,
3802 g_warning ("Idle source dispatched without callback\n"
3803 "You must call g_source_set_callback().");
3807 return callback (user_data);
3811 * g_idle_source_new:
3813 * Creates a new idle source.
3815 * The source will not initially be associated with any #GMainContext
3816 * and must be added to one with g_source_attach() before it will be
3817 * executed. Note that the default priority for idle sources is
3818 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
3819 * have a default priority of %G_PRIORITY_DEFAULT.
3821 * Return value: the newly-created idle source
3824 g_idle_source_new (void)
3828 source = g_source_new (&g_idle_funcs, sizeof (GSource));
3829 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
3836 * @priority: the priority of the idle source. Typically this will be in the
3837 * range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3838 * @function: function to call
3839 * @data: data to pass to @function
3840 * @notify: function to call when the idle is removed, or %NULL
3842 * Adds a function to be called whenever there are no higher priority
3843 * events pending. If the function returns %FALSE it is automatically
3844 * removed from the list of event sources and will not be called again.
3846 * Return value: the id of the event source.
3849 g_idle_add_full (gint priority,
3850 GSourceFunc function,
3852 GDestroyNotify notify)
3857 g_return_val_if_fail (function != NULL, 0);
3859 source = g_idle_source_new ();
3861 if (priority != G_PRIORITY_DEFAULT_IDLE)
3862 g_source_set_priority (source, priority);
3864 g_source_set_callback (source, function, data, notify);
3865 id = g_source_attach (source, NULL);
3866 g_source_unref (source);
3873 * @function: function to call
3874 * @data: data to pass to @function.
3876 * Adds a function to be called whenever there are no higher priority
3877 * events pending to the default main loop. The function is given the
3878 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
3879 * returns %FALSE it is automatically removed from the list of event
3880 * sources and will not be called again.
3882 * Return value: the id of the event source.
3885 g_idle_add (GSourceFunc function,
3888 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
3892 * g_idle_remove_by_data:
3893 * @data: the data for the idle source's callback.
3895 * Removes the idle function with the given data.
3897 * Return value: %TRUE if an idle source was found and removed.
3900 g_idle_remove_by_data (gpointer data)
3902 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
3905 #define __G_MAIN_C__
3906 #include "galiasdef.c"