1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * gmain.c: Main loop abstraction, timeouts, and idle functions
5 * Copyright 1998 Owen Taylor
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the
19 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 * Boston, MA 02111-1307, USA.
24 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
25 * file for a list of people on the GLib Team. See the ChangeLog
26 * files for a list of changes. These files are distributed with
27 * GLib at ftp://ftp.gtk.org/pub/gtk/.
36 /* uncomment the next line to get poll() debugging info */
37 /* #define G_MAIN_POLL_DEBUG */
40 #include "gthreadinit.h"
42 #include <sys/types.h>
44 #ifdef HAVE_SYS_TIME_H
46 #endif /* HAVE_SYS_TIME_H */
47 #ifdef GLIB_HAVE_SYS_POLL_H
48 # include <sys/poll.h>
49 # undef events /* AIX 4.1.5 & 4.3.2 define this for SVR3,4 compatibility */
50 # undef revents /* AIX 4.1.5 & 4.3.2 define this for SVR3,4 compatibility */
52 /* The poll() emulation on OS/X doesn't handle fds=NULL, nfds=0,
53 * so we prefer our own poll emulation.
59 #endif /* GLIB_HAVE_SYS_POLL_H */
62 #endif /* HAVE_UNISTD_H */
68 #endif /* G_OS_WIN32 */
71 #include <sys/socket.h>
73 #endif /* G_OS_BEOS */
84 typedef struct _GTimeoutSource GTimeoutSource;
85 typedef struct _GChildWatchSource GChildWatchSource;
86 typedef struct _GPollRec GPollRec;
87 typedef struct _GSourceCallback GSourceCallback;
91 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
92 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
95 #ifdef G_THREADS_ENABLED
96 typedef struct _GMainWaiter GMainWaiter;
107 #ifdef G_THREADS_ENABLED
108 /* The following lock is used for both the list of sources
109 * and the list of poll records
120 GPtrArray *pending_dispatches;
121 gint timeout; /* Timeout for current iteration */
124 GSource *source_list;
125 gint in_check_or_prepare;
127 GPollRec *poll_records;
128 guint n_poll_records;
129 GPollFD *cached_poll_array;
130 guint cached_poll_array_size;
132 #ifdef G_THREADS_ENABLED
134 /* this pipe is used to wake up the main loop when a source is added.
136 gint wake_up_pipe[2];
137 #else /* G_OS_WIN32 */
138 HANDLE wake_up_semaphore;
139 #endif /* G_OS_WIN32 */
142 gboolean poll_waiting;
144 /* Flag indicating whether the set of fd's changed during a poll */
145 gboolean poll_changed;
146 #endif /* G_THREADS_ENABLED */
150 GTimeVal current_time;
151 gboolean time_is_current;
154 struct _GSourceCallback
159 GDestroyNotify notify;
164 GMainContext *context;
169 struct _GTimeoutSource
176 struct _GChildWatchSource
183 #else /* G_OS_WIN32 */
185 gboolean child_exited;
186 #endif /* G_OS_WIN32 */
196 #ifdef G_THREADS_ENABLED
197 #define LOCK_CONTEXT(context) g_static_mutex_lock (&context->mutex)
198 #define UNLOCK_CONTEXT(context) g_static_mutex_unlock (&context->mutex)
199 #define G_THREAD_SELF g_thread_self ()
201 #define LOCK_CONTEXT(context) (void)0
202 #define UNLOCK_CONTEXT(context) (void)0
203 #define G_THREAD_SELF NULL
206 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
207 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
208 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
210 #define SOURCE_UNREF(source, context) \
212 if ((source)->ref_count > 1) \
213 (source)->ref_count--; \
215 g_source_unref_internal ((source), (context), TRUE); \
219 /* Forward declarations */
221 static void g_source_unref_internal (GSource *source,
222 GMainContext *context,
224 static void g_source_destroy_internal (GSource *source,
225 GMainContext *context,
227 static void g_main_context_poll (GMainContext *context,
232 static void g_main_context_add_poll_unlocked (GMainContext *context,
235 static void g_main_context_remove_poll_unlocked (GMainContext *context,
237 static void g_main_context_wakeup_unlocked (GMainContext *context);
239 static gboolean g_timeout_prepare (GSource *source,
241 static gboolean g_timeout_check (GSource *source);
242 static gboolean g_timeout_dispatch (GSource *source,
243 GSourceFunc callback,
245 static gboolean g_child_watch_prepare (GSource *source,
247 static gboolean g_child_watch_check (GSource *source);
248 static gboolean g_child_watch_dispatch (GSource *source,
249 GSourceFunc callback,
251 static gboolean g_idle_prepare (GSource *source,
253 static gboolean g_idle_check (GSource *source);
254 static gboolean g_idle_dispatch (GSource *source,
255 GSourceFunc callback,
258 G_LOCK_DEFINE_STATIC (main_loop);
259 static GMainContext *default_main_context;
260 static GSList *main_contexts_without_pipe = NULL;
263 /* Child status monitoring code */
265 CHILD_WATCH_UNINITIALIZED,
266 CHILD_WATCH_INITIALIZED_SINGLE,
267 CHILD_WATCH_INITIALIZED_THREADED
269 static gint child_watch_init_state = CHILD_WATCH_UNINITIALIZED;
270 static gint child_watch_count = 1;
271 static gint child_watch_wake_up_pipe[2] = {0, 0};
272 #endif /* !G_OS_WIN32 */
273 G_LOCK_DEFINE_STATIC (main_context_list);
274 static GSList *main_context_list = NULL;
276 GSourceFuncs g_timeout_funcs =
284 GSourceFuncs g_child_watch_funcs =
286 g_child_watch_prepare,
288 g_child_watch_dispatch,
292 GSourceFuncs g_idle_funcs =
301 /* SunOS has poll, but doesn't provide a prototype. */
302 # if defined (sun) && !defined (__SVR4)
303 extern gint poll (GPollFD *ufds, guint nfsd, gint timeout);
305 #else /* !HAVE_POLL */
310 g_poll (GPollFD *fds,
314 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
315 gboolean poll_msgs = FALSE;
322 for (f = fds; f < &fds[nfds]; ++f)
325 if (f->fd == G_WIN32_MSG_HANDLE)
327 else if (nhandles == MAXIMUM_WAIT_OBJECTS)
329 g_warning (G_STRLOC ": Too many handles to wait for!\n");
334 #ifdef G_MAIN_POLL_DEBUG
335 g_print ("g_poll: waiting for %#x\n", f->fd);
337 handles[nhandles++] = (HANDLE) f->fd;
346 /* Waiting for messages, and maybe events
347 * -> First PeekMessage
349 #ifdef G_MAIN_POLL_DEBUG
350 g_print ("PeekMessage\n");
352 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
353 ready = WAIT_OBJECT_0 + nhandles;
358 /* Waiting just for messages */
359 if (timeout == INFINITE)
364 #ifdef G_MAIN_POLL_DEBUG
365 g_print ("WaitMessage\n");
369 gchar *emsg = g_win32_error_message (GetLastError ());
370 g_warning (G_STRLOC ": WaitMessage() failed: %s", emsg);
373 ready = WAIT_OBJECT_0 + nhandles;
375 else if (timeout == 0)
377 /* Waiting just for messages, zero timeout.
378 * If we got here, there was no message
380 ready = WAIT_TIMEOUT;
384 /* Waiting just for messages, some timeout
385 * -> Set a timer, wait for message,
386 * kill timer, use PeekMessage
388 timer = SetTimer (NULL, 0, timeout, NULL);
391 gchar *emsg = g_win32_error_message (GetLastError ());
392 g_warning (G_STRLOC ": SetTimer() failed: %s", emsg);
394 ready = WAIT_TIMEOUT;
398 #ifdef G_MAIN_POLL_DEBUG
399 g_print ("WaitMessage\n");
402 KillTimer (NULL, timer);
403 #ifdef G_MAIN_POLL_DEBUG
404 g_print ("PeekMessage\n");
406 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE)
407 && msg.message != WM_TIMER)
408 ready = WAIT_OBJECT_0;
410 ready = WAIT_TIMEOUT;
416 /* Wait for either message or event
417 * -> Use MsgWaitForMultipleObjects
419 #ifdef G_MAIN_POLL_DEBUG
420 g_print ("MsgWaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
422 ready = MsgWaitForMultipleObjects (nhandles, handles, FALSE,
423 timeout, QS_ALLINPUT);
425 if (ready == WAIT_FAILED)
427 gchar *emsg = g_win32_error_message (GetLastError ());
428 g_warning (G_STRLOC ": MsgWaitForMultipleObjects() failed: %s", emsg);
434 else if (nhandles == 0)
436 /* Wait for nothing (huh?) */
441 /* Wait for just events
442 * -> Use WaitForMultipleObjects
444 #ifdef G_MAIN_POLL_DEBUG
445 g_print ("WaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
447 ready = WaitForMultipleObjects (nhandles, handles, FALSE, timeout);
448 if (ready == WAIT_FAILED)
450 gchar *emsg = g_win32_error_message (GetLastError ());
451 g_warning (G_STRLOC ": WaitForMultipleObjects() failed: %s", emsg);
456 #ifdef G_MAIN_POLL_DEBUG
457 g_print ("wait returns %ld%s\n",
459 (ready == WAIT_FAILED ? " (WAIT_FAILED)" :
460 (ready == WAIT_TIMEOUT ? " (WAIT_TIMEOUT)" :
461 (poll_msgs && ready == WAIT_OBJECT_0 + nhandles ? " (msg)" : ""))));
463 for (f = fds; f < &fds[nfds]; ++f)
466 if (ready == WAIT_FAILED)
468 else if (ready == WAIT_TIMEOUT)
470 else if (poll_msgs && ready == WAIT_OBJECT_0 + nhandles)
472 for (f = fds; f < &fds[nfds]; ++f)
475 if (f->events & G_IO_IN)
476 if (f->fd == G_WIN32_MSG_HANDLE)
477 f->revents |= G_IO_IN;
480 else if (ready >= WAIT_OBJECT_0 && ready < WAIT_OBJECT_0 + nhandles)
481 for (f = fds; f < &fds[nfds]; ++f)
483 if (f->fd == (gint) handles[ready - WAIT_OBJECT_0])
485 f->revents = f->events;
486 #ifdef G_MAIN_POLL_DEBUG
487 g_print ("g_poll: got event %#x\n", f->fd);
495 #else /* !G_OS_WIN32 */
497 /* The following implementation of poll() comes from the GNU C Library.
498 * Copyright (C) 1994, 1996, 1997 Free Software Foundation, Inc.
501 #include <string.h> /* for bzero on BSD systems */
503 #ifdef HAVE_SYS_SELECT_H
504 #include <sys/select.h>
505 #endif /* HAVE_SYS_SELECT_H */
509 #endif /* G_OS_BEOS */
512 # define SELECT_MASK fd_set
513 #else /* !NO_FD_SET */
515 typedef long fd_mask;
518 # define SELECT_MASK void
520 # define SELECT_MASK int
521 # endif /* !_IBMR2 */
522 #endif /* !NO_FD_SET */
525 g_poll (GPollFD *fds,
530 SELECT_MASK rset, wset, xset;
539 for (f = fds; f < &fds[nfds]; ++f)
542 if (f->events & G_IO_IN)
543 FD_SET (f->fd, &rset);
544 if (f->events & G_IO_OUT)
545 FD_SET (f->fd, &wset);
546 if (f->events & G_IO_PRI)
547 FD_SET (f->fd, &xset);
548 if (f->fd > maxfd && (f->events & (G_IO_IN|G_IO_OUT|G_IO_PRI)))
552 tv.tv_sec = timeout / 1000;
553 tv.tv_usec = (timeout % 1000) * 1000;
555 ready = select (maxfd + 1, &rset, &wset, &xset,
556 timeout == -1 ? NULL : &tv);
558 for (f = fds; f < &fds[nfds]; ++f)
563 if (FD_ISSET (f->fd, &rset))
564 f->revents |= G_IO_IN;
565 if (FD_ISSET (f->fd, &wset))
566 f->revents |= G_IO_OUT;
567 if (FD_ISSET (f->fd, &xset))
568 f->revents |= G_IO_PRI;
575 #endif /* !G_OS_WIN32 */
577 #endif /* !HAVE_POLL */
580 * g_main_context_ref:
581 * @context: a #GMainContext
583 * Increases the reference count on a #GMainContext object by one.
585 * Returns: the @context that was passed in (since 2.6)
588 g_main_context_ref (GMainContext *context)
590 g_return_val_if_fail (context != NULL, NULL);
591 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
593 g_atomic_int_inc (&context->ref_count);
599 poll_rec_list_free (GMainContext *context,
602 g_slice_free_chain (GPollRec, list, next);
606 * g_main_context_unref:
607 * @context: a #GMainContext
609 * Decreases the reference count on a #GMainContext object by one. If
610 * the result is zero, free the context and free all associated memory.
613 g_main_context_unref (GMainContext *context)
616 g_return_if_fail (context != NULL);
617 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
619 if (!g_atomic_int_dec_and_test (&context->ref_count))
622 G_LOCK (main_context_list);
623 main_context_list = g_slist_remove (main_context_list, context);
624 G_UNLOCK (main_context_list);
626 source = context->source_list;
629 GSource *next = source->next;
630 g_source_destroy_internal (source, context, FALSE);
634 #ifdef G_THREADS_ENABLED
635 g_static_mutex_free (&context->mutex);
638 g_ptr_array_free (context->pending_dispatches, TRUE);
639 g_free (context->cached_poll_array);
641 poll_rec_list_free (context, context->poll_records);
643 #ifdef G_THREADS_ENABLED
644 if (g_thread_supported())
647 close (context->wake_up_pipe[0]);
648 close (context->wake_up_pipe[1]);
650 CloseHandle (context->wake_up_semaphore);
654 main_contexts_without_pipe = g_slist_remove (main_contexts_without_pipe,
661 #ifdef G_THREADS_ENABLED
663 g_main_context_init_pipe (GMainContext *context)
666 if (context->wake_up_pipe[0] != -1)
668 if (pipe (context->wake_up_pipe) < 0)
669 g_error ("Cannot create pipe main loop wake-up: %s\n",
672 context->wake_up_rec.fd = context->wake_up_pipe[0];
673 context->wake_up_rec.events = G_IO_IN;
675 if (context->wake_up_semaphore != NULL)
677 context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
678 if (context->wake_up_semaphore == NULL)
679 g_error ("Cannot create wake-up semaphore: %s",
680 g_win32_error_message (GetLastError ()));
681 context->wake_up_rec.fd = (gint) context->wake_up_semaphore;
682 context->wake_up_rec.events = G_IO_IN;
683 # ifdef G_MAIN_POLL_DEBUG
684 g_print ("wake-up semaphore: %#x\n", (guint) context->wake_up_semaphore);
687 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
691 _g_main_thread_init (void)
693 GSList *curr = main_contexts_without_pipe;
696 g_main_context_init_pipe ((GMainContext *)curr->data);
699 g_slist_free (main_contexts_without_pipe);
700 main_contexts_without_pipe = NULL;
702 #endif /* G_THREADS_ENABLED */
705 * g_main_context_new:
707 * Creates a new #GMainContext strcuture
709 * Return value: the new #GMainContext
712 g_main_context_new (void)
714 GMainContext *context = g_new0 (GMainContext, 1);
716 #ifdef G_THREADS_ENABLED
717 g_static_mutex_init (&context->mutex);
719 context->owner = NULL;
720 context->waiters = NULL;
723 context->wake_up_pipe[0] = -1;
724 context->wake_up_pipe[1] = -1;
726 context->wake_up_semaphore = NULL;
730 context->ref_count = 1;
732 context->next_id = 1;
734 context->source_list = NULL;
737 context->poll_func = (GPollFunc)poll;
739 context->poll_func = g_poll;
742 context->cached_poll_array = NULL;
743 context->cached_poll_array_size = 0;
745 context->pending_dispatches = g_ptr_array_new ();
747 context->time_is_current = FALSE;
749 #ifdef G_THREADS_ENABLED
750 if (g_thread_supported ())
751 g_main_context_init_pipe (context);
753 main_contexts_without_pipe = g_slist_prepend (main_contexts_without_pipe,
757 G_LOCK (main_context_list);
758 main_context_list = g_slist_append (main_context_list, context);
759 G_UNLOCK (main_context_list);
765 * g_main_context_default:
767 * Returns the default main context. This is the main context used
768 * for main loop functions when a main loop is not explicitly
771 * Return value: the default main context.
774 g_main_context_default (void)
780 if (!default_main_context)
781 default_main_context = g_main_context_new ();
783 G_UNLOCK (main_loop);
785 return default_main_context;
788 /* Hooks for adding to the main loop */
792 * @source_funcs: structure containing functions that implement
793 * the sources behavior.
794 * @struct_size: size of the #GSource structure to create.
796 * Creates a new #GSource structure. The size is specified to
797 * allow creating structures derived from #GSource that contain
798 * additional data. The size passed in must be at least
799 * <literal>sizeof (GSource)</literal>.
801 * The source will not initially be associated with any #GMainContext
802 * and must be added to one with g_source_attach() before it will be
805 * Return value: the newly-created #GSource.
808 g_source_new (GSourceFuncs *source_funcs,
813 g_return_val_if_fail (source_funcs != NULL, NULL);
814 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
816 source = (GSource*) g_malloc0 (struct_size);
818 source->source_funcs = source_funcs;
819 source->ref_count = 1;
821 source->priority = G_PRIORITY_DEFAULT;
823 source->flags = G_HOOK_FLAG_ACTIVE;
825 /* NULL/0 initialization for all other fields */
830 /* Holds context's lock
833 g_source_list_add (GSource *source,
834 GMainContext *context)
836 GSource *tmp_source, *last_source;
839 tmp_source = context->source_list;
840 while (tmp_source && tmp_source->priority <= source->priority)
842 last_source = tmp_source;
843 tmp_source = tmp_source->next;
846 source->next = tmp_source;
848 tmp_source->prev = source;
850 source->prev = last_source;
852 last_source->next = source;
854 context->source_list = source;
857 /* Holds context's lock
860 g_source_list_remove (GSource *source,
861 GMainContext *context)
864 source->prev->next = source->next;
866 context->source_list = source->next;
869 source->next->prev = source->prev;
877 * @source: a #GSource
878 * @context: a #GMainContext (if %NULL, the default context will be used)
880 * Adds a #GSource to a @context so that it will be executed within
883 * Return value: the ID (greater than 0) for the source within the
887 g_source_attach (GSource *source,
888 GMainContext *context)
893 g_return_val_if_fail (source->context == NULL, 0);
894 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
897 context = g_main_context_default ();
899 LOCK_CONTEXT (context);
901 source->context = context;
902 result = source->source_id = context->next_id++;
905 g_source_list_add (source, context);
907 tmp_list = source->poll_fds;
910 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
911 tmp_list = tmp_list->next;
914 #ifdef G_THREADS_ENABLED
915 /* Now wake up the main loop if it is waiting in the poll() */
916 g_main_context_wakeup_unlocked (context);
919 UNLOCK_CONTEXT (context);
925 g_source_destroy_internal (GSource *source,
926 GMainContext *context,
930 LOCK_CONTEXT (context);
932 if (!SOURCE_DESTROYED (source))
935 gpointer old_cb_data;
936 GSourceCallbackFuncs *old_cb_funcs;
938 source->flags &= ~G_HOOK_FLAG_ACTIVE;
940 old_cb_data = source->callback_data;
941 old_cb_funcs = source->callback_funcs;
943 source->callback_data = NULL;
944 source->callback_funcs = NULL;
948 UNLOCK_CONTEXT (context);
949 old_cb_funcs->unref (old_cb_data);
950 LOCK_CONTEXT (context);
953 if (!SOURCE_BLOCKED (source))
955 tmp_list = source->poll_fds;
958 g_main_context_remove_poll_unlocked (context, tmp_list->data);
959 tmp_list = tmp_list->next;
963 g_source_unref_internal (source, context, TRUE);
967 UNLOCK_CONTEXT (context);
972 * @source: a #GSource
974 * Removes a source from its #GMainContext, if any, and mark it as
975 * destroyed. The source cannot be subsequently added to another
979 g_source_destroy (GSource *source)
981 GMainContext *context;
983 g_return_if_fail (source != NULL);
985 context = source->context;
988 g_source_destroy_internal (source, context, FALSE);
990 source->flags &= ~G_HOOK_FLAG_ACTIVE;
995 * @source: a #GSource
997 * Returns the numeric ID for a particular source. The ID of a source
998 * is a positive integer which is unique within a particular main loop
999 * context. The reverse
1000 * mapping from ID to source is done by g_main_context_find_source_by_id().
1002 * Return value: the ID (greater than 0) for the source
1005 g_source_get_id (GSource *source)
1009 g_return_val_if_fail (source != NULL, 0);
1010 g_return_val_if_fail (source->context != NULL, 0);
1012 LOCK_CONTEXT (source->context);
1013 result = source->source_id;
1014 UNLOCK_CONTEXT (source->context);
1020 * g_source_get_context:
1021 * @source: a #GSource
1023 * Gets the #GMainContext with which the source is associated.
1024 * Calling this function on a destroyed source is an error.
1026 * Return value: the #GMainContext with which the source is associated,
1027 * or %NULL if the context has not yet been added
1031 g_source_get_context (GSource *source)
1033 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1035 return source->context;
1039 * g_source_add_poll:
1040 * @source:a #GSource
1041 * @fd: a #GPollFD structure holding information about a file
1042 * descriptor to watch.
1044 * Adds a file descriptor to the set of file descriptors polled for
1045 * this source. This is usually combined with g_source_new() to add an
1046 * event source. The event source's check function will typically test
1047 * the @revents field in the #GPollFD struct and return %TRUE if events need
1051 g_source_add_poll (GSource *source,
1054 GMainContext *context;
1056 g_return_if_fail (source != NULL);
1057 g_return_if_fail (fd != NULL);
1058 g_return_if_fail (!SOURCE_DESTROYED (source));
1060 context = source->context;
1063 LOCK_CONTEXT (context);
1065 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1069 if (!SOURCE_BLOCKED (source))
1070 g_main_context_add_poll_unlocked (context, source->priority, fd);
1071 UNLOCK_CONTEXT (context);
1076 * g_source_remove_poll:
1077 * @source:a #GSource
1078 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1080 * Removes a file descriptor from the set of file descriptors polled for
1084 g_source_remove_poll (GSource *source,
1087 GMainContext *context;
1089 g_return_if_fail (source != NULL);
1090 g_return_if_fail (fd != NULL);
1091 g_return_if_fail (!SOURCE_DESTROYED (source));
1093 context = source->context;
1096 LOCK_CONTEXT (context);
1098 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1102 if (!SOURCE_BLOCKED (source))
1103 g_main_context_remove_poll_unlocked (context, fd);
1104 UNLOCK_CONTEXT (context);
1109 * g_source_set_callback_indirect:
1110 * @source: the source
1111 * @callback_data: pointer to callback data "object"
1112 * @callback_funcs: functions for reference counting @callback_data
1113 * and getting the callback and data
1115 * Sets the callback function storing the data as a refcounted callback
1116 * "object". This is used internally. Note that calling
1117 * g_source_set_callback_indirect() assumes
1118 * an initial reference count on @callback_data, and thus
1119 * @callback_funcs->unref will eventually be called once more
1120 * than @callback_funcs->ref.
1123 g_source_set_callback_indirect (GSource *source,
1124 gpointer callback_data,
1125 GSourceCallbackFuncs *callback_funcs)
1127 GMainContext *context;
1128 gpointer old_cb_data;
1129 GSourceCallbackFuncs *old_cb_funcs;
1131 g_return_if_fail (source != NULL);
1132 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1134 context = source->context;
1137 LOCK_CONTEXT (context);
1139 old_cb_data = source->callback_data;
1140 old_cb_funcs = source->callback_funcs;
1142 source->callback_data = callback_data;
1143 source->callback_funcs = callback_funcs;
1146 UNLOCK_CONTEXT (context);
1149 old_cb_funcs->unref (old_cb_data);
1153 g_source_callback_ref (gpointer cb_data)
1155 GSourceCallback *callback = cb_data;
1157 callback->ref_count++;
1162 g_source_callback_unref (gpointer cb_data)
1164 GSourceCallback *callback = cb_data;
1166 callback->ref_count--;
1167 if (callback->ref_count == 0)
1169 if (callback->notify)
1170 callback->notify (callback->data);
1176 g_source_callback_get (gpointer cb_data,
1181 GSourceCallback *callback = cb_data;
1183 *func = callback->func;
1184 *data = callback->data;
1187 static GSourceCallbackFuncs g_source_callback_funcs = {
1188 g_source_callback_ref,
1189 g_source_callback_unref,
1190 g_source_callback_get,
1194 * g_source_set_callback:
1195 * @source: the source
1196 * @func: a callback function
1197 * @data: the data to pass to callback function
1198 * @notify: a function to call when @data is no longer in use, or %NULL.
1200 * Sets the callback function for a source. The callback for a source is
1201 * called from the source's dispatch function.
1203 * The exact type of @func depends on the type of source; ie. you
1204 * should not count on @func being called with @data as its first
1207 * Typically, you won't use this function. Instead use functions specific
1208 * to the type of source you are using.
1211 g_source_set_callback (GSource *source,
1214 GDestroyNotify notify)
1216 GSourceCallback *new_callback;
1218 g_return_if_fail (source != NULL);
1220 new_callback = g_new (GSourceCallback, 1);
1222 new_callback->ref_count = 1;
1223 new_callback->func = func;
1224 new_callback->data = data;
1225 new_callback->notify = notify;
1227 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1231 * g_source_set_priority:
1232 * @source: a #GSource
1233 * @priority: the new priority.
1235 * Sets the priority of a source. While the main loop is being
1236 * run, a source will be dispatched if it is ready to be dispatched and no sources
1237 * at a higher (numerically smaller) priority are ready to be dispatched.
1240 g_source_set_priority (GSource *source,
1244 GMainContext *context;
1246 g_return_if_fail (source != NULL);
1248 context = source->context;
1251 LOCK_CONTEXT (context);
1253 source->priority = priority;
1257 /* Remove the source from the context's source and then
1258 * add it back so it is sorted in the correct plcae
1260 g_source_list_remove (source, source->context);
1261 g_source_list_add (source, source->context);
1263 if (!SOURCE_BLOCKED (source))
1265 tmp_list = source->poll_fds;
1268 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1269 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1271 tmp_list = tmp_list->next;
1275 UNLOCK_CONTEXT (source->context);
1280 * g_source_get_priority:
1281 * @source: a #GSource
1283 * Gets the priority of a source.
1285 * Return value: the priority of the source
1288 g_source_get_priority (GSource *source)
1290 g_return_val_if_fail (source != NULL, 0);
1292 return source->priority;
1296 * g_source_set_can_recurse:
1297 * @source: a #GSource
1298 * @can_recurse: whether recursion is allowed for this source
1300 * Sets whether a source can be called recursively. If @can_recurse is
1301 * %TRUE, then while the source is being dispatched then this source
1302 * will be processed normally. Otherwise, all processing of this
1303 * source is blocked until the dispatch function returns.
1306 g_source_set_can_recurse (GSource *source,
1307 gboolean can_recurse)
1309 GMainContext *context;
1311 g_return_if_fail (source != NULL);
1313 context = source->context;
1316 LOCK_CONTEXT (context);
1319 source->flags |= G_SOURCE_CAN_RECURSE;
1321 source->flags &= ~G_SOURCE_CAN_RECURSE;
1324 UNLOCK_CONTEXT (context);
1328 * g_source_get_can_recurse:
1329 * @source: a #GSource
1331 * Checks whether a source is allowed to be called recursively.
1332 * see g_source_set_can_recurse().
1334 * Return value: whether recursion is allowed.
1337 g_source_get_can_recurse (GSource *source)
1339 g_return_val_if_fail (source != NULL, FALSE);
1341 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1346 * @source: a #GSource
1348 * Increases the reference count on a source by one.
1350 * Return value: @source
1353 g_source_ref (GSource *source)
1355 GMainContext *context;
1357 g_return_val_if_fail (source != NULL, NULL);
1359 context = source->context;
1362 LOCK_CONTEXT (context);
1364 source->ref_count++;
1367 UNLOCK_CONTEXT (context);
1372 /* g_source_unref() but possible to call within context lock
1375 g_source_unref_internal (GSource *source,
1376 GMainContext *context,
1379 gpointer old_cb_data = NULL;
1380 GSourceCallbackFuncs *old_cb_funcs = NULL;
1382 g_return_if_fail (source != NULL);
1384 if (!have_lock && context)
1385 LOCK_CONTEXT (context);
1387 source->ref_count--;
1388 if (source->ref_count == 0)
1390 old_cb_data = source->callback_data;
1391 old_cb_funcs = source->callback_funcs;
1393 source->callback_data = NULL;
1394 source->callback_funcs = NULL;
1396 if (context && !SOURCE_DESTROYED (source))
1398 g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1399 source->ref_count++;
1402 g_source_list_remove (source, context);
1404 if (source->source_funcs->finalize)
1405 source->source_funcs->finalize (source);
1407 g_slist_free (source->poll_fds);
1408 source->poll_fds = NULL;
1412 if (!have_lock && context)
1413 UNLOCK_CONTEXT (context);
1418 UNLOCK_CONTEXT (context);
1420 old_cb_funcs->unref (old_cb_data);
1423 LOCK_CONTEXT (context);
1429 * @source: a #GSource
1431 * Decreases the reference count of a source by one. If the
1432 * resulting reference count is zero the source and associated
1433 * memory will be destroyed.
1436 g_source_unref (GSource *source)
1438 g_return_if_fail (source != NULL);
1440 g_source_unref_internal (source, source->context, FALSE);
1444 * g_main_context_find_source_by_id:
1445 * @context: a #GMainContext (if %NULL, the default context will be used)
1446 * @source_id: the source ID, as returned by g_source_get_id().
1448 * Finds a #GSource given a pair of context and ID.
1450 * Return value: the #GSource if found, otherwise, %NULL
1453 g_main_context_find_source_by_id (GMainContext *context,
1458 g_return_val_if_fail (source_id > 0, NULL);
1460 if (context == NULL)
1461 context = g_main_context_default ();
1463 LOCK_CONTEXT (context);
1465 source = context->source_list;
1468 if (!SOURCE_DESTROYED (source) &&
1469 source->source_id == source_id)
1471 source = source->next;
1474 UNLOCK_CONTEXT (context);
1480 * g_main_context_find_source_by_funcs_user_data:
1481 * @context: a #GMainContext (if %NULL, the default context will be used).
1482 * @funcs: the @source_funcs passed to g_source_new().
1483 * @user_data: the user data from the callback.
1485 * Finds a source with the given source functions and user data. If
1486 * multiple sources exist with the same source function and user data,
1487 * the first one found will be returned.
1489 * Return value: the source, if one was found, otherwise %NULL
1492 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1493 GSourceFuncs *funcs,
1498 g_return_val_if_fail (funcs != NULL, NULL);
1500 if (context == NULL)
1501 context = g_main_context_default ();
1503 LOCK_CONTEXT (context);
1505 source = context->source_list;
1508 if (!SOURCE_DESTROYED (source) &&
1509 source->source_funcs == funcs &&
1510 source->callback_funcs)
1512 GSourceFunc callback;
1513 gpointer callback_data;
1515 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1517 if (callback_data == user_data)
1520 source = source->next;
1523 UNLOCK_CONTEXT (context);
1529 * g_main_context_find_source_by_user_data:
1530 * @context: a #GMainContext
1531 * @user_data: the user_data for the callback.
1533 * Finds a source with the given user data for the callback. If
1534 * multiple sources exist with the same user data, the first
1535 * one found will be returned.
1537 * Return value: the source, if one was found, otherwise %NULL
1540 g_main_context_find_source_by_user_data (GMainContext *context,
1545 if (context == NULL)
1546 context = g_main_context_default ();
1548 LOCK_CONTEXT (context);
1550 source = context->source_list;
1553 if (!SOURCE_DESTROYED (source) &&
1554 source->callback_funcs)
1556 GSourceFunc callback;
1557 gpointer callback_data = NULL;
1559 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1561 if (callback_data == user_data)
1564 source = source->next;
1567 UNLOCK_CONTEXT (context);
1574 * @tag: the ID of the source to remove.
1576 * Removes the source with the given id from the default main context.
1578 * a #GSource is given by g_source_get_id(), or will be returned by the
1579 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1580 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1581 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1583 * See also g_source_destroy().
1585 * Return value: %TRUE if the source was found and removed.
1588 g_source_remove (guint tag)
1592 g_return_val_if_fail (tag > 0, FALSE);
1594 source = g_main_context_find_source_by_id (NULL, tag);
1596 g_source_destroy (source);
1598 return source != NULL;
1602 * g_source_remove_by_user_data:
1603 * @user_data: the user_data for the callback.
1605 * Removes a source from the default main loop context given the user
1606 * data for the callback. If multiple sources exist with the same user
1607 * data, only one will be destroyed.
1609 * Return value: %TRUE if a source was found and removed.
1612 g_source_remove_by_user_data (gpointer user_data)
1616 source = g_main_context_find_source_by_user_data (NULL, user_data);
1619 g_source_destroy (source);
1627 * g_source_remove_by_funcs_user_data:
1628 * @funcs: The @source_funcs passed to g_source_new()
1629 * @user_data: the user data for the callback
1631 * Removes a source from the default main loop context given the
1632 * source functions and user data. If multiple sources exist with the
1633 * same source functions and user data, only one will be destroyed.
1635 * Return value: %TRUE if a source was found and removed.
1638 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1643 g_return_val_if_fail (funcs != NULL, FALSE);
1645 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1648 g_source_destroy (source);
1656 * g_get_current_time:
1657 * @result: #GTimeVal structure in which to store current time.
1659 * Equivalent to the UNIX gettimeofday() function, but portable.
1662 g_get_current_time (GTimeVal *result)
1667 g_return_if_fail (result != NULL);
1669 /*this is required on alpha, there the timeval structs are int's
1670 not longs and a cast only would fail horribly*/
1671 gettimeofday (&r, NULL);
1672 result->tv_sec = r.tv_sec;
1673 result->tv_usec = r.tv_usec;
1676 guint64 *time64 = (guint64 *) &ft;
1678 GetSystemTimeAsFileTime (&ft);
1680 /* Convert from 100s of nanoseconds since 1601-01-01
1681 * to Unix epoch. Yes, this is Y2038 unsafe.
1683 *time64 -= G_GINT64_CONSTANT (116444736000000000);
1686 result->tv_sec = *time64 / 1000000;
1687 result->tv_usec = *time64 % 1000000;
1691 /* Running the main loop */
1694 get_depth_pointer (void)
1696 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
1697 gint *depth_pointer = g_static_private_get (&depth_private);
1700 depth_pointer = g_new (gint, 1);
1702 g_static_private_set (&depth_private, depth_pointer, g_free);
1705 return depth_pointer;
1711 * Return value: The main loop recursion level in the current thread
1713 * Returns the depth of the stack of calls to
1714 * g_main_context_dispatch() on any #GMainContext in the current thread.
1715 * That is, when called from the toplevel, it gives 0. When
1716 * called from within a callback from g_main_context_iteration()
1717 * (or g_main_loop_run(), etc.) it returns 1. When called from within
1718 * a callback to a recursive call to g_main_context_iterate(),
1719 * it returns 2. And so forth.
1721 * This function is useful in a situation like the following:
1722 * Imagine an extremely simple "garbage collected" system.
1725 * static GList *free_list;
1728 * allocate_memory (gsize size)
1730 * gpointer result = g_malloc (size);
1731 * free_list = g_list_prepend (free_list, result);
1736 * free_allocated_memory (void)
1739 * for (l = free_list; l; l = l->next);
1741 * g_list_free (free_list);
1749 * g_main_context_iteration (NULL, TRUE);
1750 * free_allocated_memory();
1754 * This works from an application, however, if you want to do the same
1755 * thing from a library, it gets more difficult, since you no longer
1756 * control the main loop. You might think you can simply use an idle
1757 * function to make the call to free_allocated_memory(), but that
1758 * doesn't work, since the idle function could be called from a
1759 * recursive callback. This can be fixed by using g_main_depth()
1763 * allocate_memory (gsize size)
1765 * FreeListBlock *block = g_new (FreeListBlock, 1);\
1766 * block->mem = g_malloc (size);
1767 * block->depth = g_main_depth ();
1768 * free_list = g_list_prepend (free_list, block);
1769 * return block->mem;
1773 * free_allocated_memory (void)
1777 * int depth = g_main_depth ();
1778 * for (l = free_list; l; );
1780 * GList *next = l->next;
1781 * FreeListBlock *block = l->data;
1782 * if (block->depth > depth)
1784 * g_free (block->mem);
1786 * free_list = g_list_delete_link (free_list, l);
1794 * There is a temptation to use g_main_depth() to solve
1795 * problems with reentrancy. For instance, while waiting for data
1796 * to be received from the network in response to a menu item,
1797 * the menu item might be selected again. It might seem that
1798 * one could make the menu item's callback return immediately
1799 * and do nothing if g_main_depth() returns a value greater than 1.
1800 * However, this should be avoided since the user then sees selecting
1801 * the menu item do nothing. Furthermore, you'll find yourself adding
1802 * these checks all over your code, since there are doubtless many,
1803 * many things that the user could do. Instead, you can use the
1804 * following techniques:
1809 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
1810 * the user from interacting with elements while the main
1811 * loop is recursing.
1816 * Avoid main loop recursion in situations where you can't handle
1817 * arbitrary callbacks. Instead, structure your code so that you
1818 * simply return to the main loop and then get called again when
1819 * there is more work to do.
1827 gint *depth = get_depth_pointer ();
1831 /* Temporarily remove all this source's file descriptors from the
1832 * poll(), so that if data comes available for one of the file descriptors
1833 * we don't continually spin in the poll()
1835 /* HOLDS: source->context's lock */
1837 block_source (GSource *source)
1841 g_return_if_fail (!SOURCE_BLOCKED (source));
1843 tmp_list = source->poll_fds;
1846 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
1847 tmp_list = tmp_list->next;
1851 /* HOLDS: source->context's lock */
1853 unblock_source (GSource *source)
1857 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
1858 g_return_if_fail (!SOURCE_DESTROYED (source));
1860 tmp_list = source->poll_fds;
1863 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
1864 tmp_list = tmp_list->next;
1868 /* HOLDS: context's lock */
1870 g_main_dispatch (GMainContext *context)
1872 gint *depth = get_depth_pointer ();
1875 for (i = 0; i < context->pending_dispatches->len; i++)
1877 GSource *source = context->pending_dispatches->pdata[i];
1879 context->pending_dispatches->pdata[i] = NULL;
1882 source->flags &= ~G_SOURCE_READY;
1884 if (!SOURCE_DESTROYED (source))
1886 gboolean was_in_call;
1887 gpointer user_data = NULL;
1888 GSourceFunc callback = NULL;
1889 GSourceCallbackFuncs *cb_funcs;
1891 gboolean need_destroy;
1893 gboolean (*dispatch) (GSource *,
1897 dispatch = source->source_funcs->dispatch;
1898 cb_funcs = source->callback_funcs;
1899 cb_data = source->callback_data;
1902 cb_funcs->ref (cb_data);
1904 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
1905 block_source (source);
1907 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
1908 source->flags |= G_HOOK_FLAG_IN_CALL;
1911 cb_funcs->get (cb_data, source, &callback, &user_data);
1913 UNLOCK_CONTEXT (context);
1916 need_destroy = ! dispatch (source,
1922 cb_funcs->unref (cb_data);
1924 LOCK_CONTEXT (context);
1927 source->flags &= ~G_HOOK_FLAG_IN_CALL;
1929 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
1930 !SOURCE_DESTROYED (source))
1931 unblock_source (source);
1933 /* Note: this depends on the fact that we can't switch
1934 * sources from one main context to another
1936 if (need_destroy && !SOURCE_DESTROYED (source))
1938 g_assert (source->context == context);
1939 g_source_destroy_internal (source, context, TRUE);
1943 SOURCE_UNREF (source, context);
1946 g_ptr_array_set_size (context->pending_dispatches, 0);
1949 /* Holds context's lock */
1950 static inline GSource *
1951 next_valid_source (GMainContext *context,
1954 GSource *new_source = source ? source->next : context->source_list;
1958 if (!SOURCE_DESTROYED (new_source))
1960 new_source->ref_count++;
1964 new_source = new_source->next;
1968 SOURCE_UNREF (source, context);
1974 * g_main_context_acquire:
1975 * @context: a #GMainContext
1977 * Tries to become the owner of the specified context.
1978 * If some other context is the owner of the context,
1979 * returns %FALSE immediately. Ownership is properly
1980 * recursive: the owner can require ownership again
1981 * and will release ownership when g_main_context_release()
1982 * is called as many times as g_main_context_acquire().
1984 * You must be the owner of a context before you
1985 * can call g_main_context_prepare(), g_main_context_query(),
1986 * g_main_context_check(), g_main_context_dispatch().
1988 * Return value: %TRUE if the operation succeeded, and
1989 * this thread is now the owner of @context.
1992 g_main_context_acquire (GMainContext *context)
1994 #ifdef G_THREADS_ENABLED
1995 gboolean result = FALSE;
1996 GThread *self = G_THREAD_SELF;
1998 if (context == NULL)
1999 context = g_main_context_default ();
2001 LOCK_CONTEXT (context);
2003 if (!context->owner)
2005 context->owner = self;
2006 g_assert (context->owner_count == 0);
2009 if (context->owner == self)
2011 context->owner_count++;
2015 UNLOCK_CONTEXT (context);
2018 #else /* !G_THREADS_ENABLED */
2020 #endif /* G_THREADS_ENABLED */
2024 * g_main_context_release:
2025 * @context: a #GMainContext
2027 * Releases ownership of a context previously acquired by this thread
2028 * with g_main_context_acquire(). If the context was acquired multiple
2029 * times, the only release ownership when g_main_context_release()
2030 * is called as many times as it was acquired.
2033 g_main_context_release (GMainContext *context)
2035 #ifdef G_THREADS_ENABLED
2036 if (context == NULL)
2037 context = g_main_context_default ();
2039 LOCK_CONTEXT (context);
2041 context->owner_count--;
2042 if (context->owner_count == 0)
2044 context->owner = NULL;
2046 if (context->waiters)
2048 GMainWaiter *waiter = context->waiters->data;
2049 gboolean loop_internal_waiter =
2050 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
2051 context->waiters = g_slist_delete_link (context->waiters,
2053 if (!loop_internal_waiter)
2054 g_mutex_lock (waiter->mutex);
2056 g_cond_signal (waiter->cond);
2058 if (!loop_internal_waiter)
2059 g_mutex_unlock (waiter->mutex);
2063 UNLOCK_CONTEXT (context);
2064 #endif /* G_THREADS_ENABLED */
2068 * g_main_context_wait:
2069 * @context: a #GMainContext
2070 * @cond: a condition variable
2071 * @mutex: a mutex, currently held
2073 * Tries to become the owner of the specified context,
2074 * as with g_main_context_acquire(). But if another thread
2075 * is the owner, atomically drop @mutex and wait on @cond until
2076 * that owner releases ownership or until @cond is signaled, then
2077 * try again (once) to become the owner.
2079 * Return value: %TRUE if the operation succeeded, and
2080 * this thread is now the owner of @context.
2083 g_main_context_wait (GMainContext *context,
2087 #ifdef G_THREADS_ENABLED
2088 gboolean result = FALSE;
2089 GThread *self = G_THREAD_SELF;
2090 gboolean loop_internal_waiter;
2092 if (context == NULL)
2093 context = g_main_context_default ();
2095 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2097 if (!loop_internal_waiter)
2098 LOCK_CONTEXT (context);
2100 if (context->owner && context->owner != self)
2105 waiter.mutex = mutex;
2107 context->waiters = g_slist_append (context->waiters, &waiter);
2109 if (!loop_internal_waiter)
2110 UNLOCK_CONTEXT (context);
2111 g_cond_wait (cond, mutex);
2112 if (!loop_internal_waiter)
2113 LOCK_CONTEXT (context);
2115 context->waiters = g_slist_remove (context->waiters, &waiter);
2118 if (!context->owner)
2120 context->owner = self;
2121 g_assert (context->owner_count == 0);
2124 if (context->owner == self)
2126 context->owner_count++;
2130 if (!loop_internal_waiter)
2131 UNLOCK_CONTEXT (context);
2134 #else /* !G_THREADS_ENABLED */
2136 #endif /* G_THREADS_ENABLED */
2140 * g_main_context_prepare:
2141 * @context: a #GMainContext
2142 * @priority: location to store priority of highest priority
2143 * source already ready.
2145 * Prepares to poll sources within a main loop. The resulting information
2146 * for polling is determined by calling g_main_context_query ().
2148 * Return value: %TRUE if some source is ready to be dispatched
2152 g_main_context_prepare (GMainContext *context,
2157 gint current_priority = G_MAXINT;
2160 if (context == NULL)
2161 context = g_main_context_default ();
2163 LOCK_CONTEXT (context);
2165 context->time_is_current = FALSE;
2167 if (context->in_check_or_prepare)
2169 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2170 "prepare() member.");
2171 UNLOCK_CONTEXT (context);
2175 #ifdef G_THREADS_ENABLED
2176 if (context->poll_waiting)
2178 g_warning("g_main_context_prepare(): main loop already active in another thread");
2179 UNLOCK_CONTEXT (context);
2183 context->poll_waiting = TRUE;
2184 #endif /* G_THREADS_ENABLED */
2187 /* If recursing, finish up current dispatch, before starting over */
2188 if (context->pending_dispatches)
2191 g_main_dispatch (context, ¤t_time);
2193 UNLOCK_CONTEXT (context);
2198 /* If recursing, clear list of pending dispatches */
2200 for (i = 0; i < context->pending_dispatches->len; i++)
2202 if (context->pending_dispatches->pdata[i])
2203 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2205 g_ptr_array_set_size (context->pending_dispatches, 0);
2207 /* Prepare all sources */
2209 context->timeout = -1;
2211 source = next_valid_source (context, NULL);
2214 gint source_timeout = -1;
2216 if ((n_ready > 0) && (source->priority > current_priority))
2218 SOURCE_UNREF (source, context);
2221 if (SOURCE_BLOCKED (source))
2224 if (!(source->flags & G_SOURCE_READY))
2227 gboolean (*prepare) (GSource *source,
2230 prepare = source->source_funcs->prepare;
2231 context->in_check_or_prepare++;
2232 UNLOCK_CONTEXT (context);
2234 result = (*prepare) (source, &source_timeout);
2236 LOCK_CONTEXT (context);
2237 context->in_check_or_prepare--;
2240 source->flags |= G_SOURCE_READY;
2243 if (source->flags & G_SOURCE_READY)
2246 current_priority = source->priority;
2247 context->timeout = 0;
2250 if (source_timeout >= 0)
2252 if (context->timeout < 0)
2253 context->timeout = source_timeout;
2255 context->timeout = MIN (context->timeout, source_timeout);
2259 source = next_valid_source (context, source);
2262 UNLOCK_CONTEXT (context);
2265 *priority = current_priority;
2267 return (n_ready > 0);
2271 * g_main_context_query:
2272 * @context: a #GMainContext
2273 * @max_priority: maximum priority source to check
2274 * @timeout_: location to store timeout to be used in polling
2275 * @fds: location to store #GPollFD records that need to be polled.
2276 * @n_fds: length of @fds.
2278 * Determines information necessary to poll this main loop.
2280 * Return value: the number of records actually stored in @fds,
2281 * or, if more than @n_fds records need to be stored, the number
2282 * of records that need to be stored.
2285 g_main_context_query (GMainContext *context,
2294 LOCK_CONTEXT (context);
2296 pollrec = context->poll_records;
2298 while (pollrec && max_priority >= pollrec->priority)
2300 if (pollrec->fd->events)
2304 fds[n_poll].fd = pollrec->fd->fd;
2305 /* In direct contradiction to the Unix98 spec, IRIX runs into
2306 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2307 * flags in the events field of the pollfd while it should
2308 * just ignoring them. So we mask them out here.
2310 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2311 fds[n_poll].revents = 0;
2316 pollrec = pollrec->next;
2319 #ifdef G_THREADS_ENABLED
2320 context->poll_changed = FALSE;
2325 *timeout = context->timeout;
2327 context->time_is_current = FALSE;
2330 UNLOCK_CONTEXT (context);
2336 * g_main_context_check:
2337 * @context: a #GMainContext
2338 * @max_priority: the maximum numerical priority of sources to check
2339 * @fds: array of #GPollFD's that was passed to the last call to
2340 * g_main_context_query()
2341 * @n_fds: return value of g_main_context_query()
2343 * Passes the results of polling back to the main loop.
2345 * Return value: %TRUE if some sources are ready to be dispatched.
2348 g_main_context_check (GMainContext *context,
2358 LOCK_CONTEXT (context);
2360 if (context->in_check_or_prepare)
2362 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2363 "prepare() member.");
2364 UNLOCK_CONTEXT (context);
2368 #ifdef G_THREADS_ENABLED
2369 if (!context->poll_waiting)
2373 read (context->wake_up_pipe[0], &a, 1);
2377 context->poll_waiting = FALSE;
2379 /* If the set of poll file descriptors changed, bail out
2380 * and let the main loop rerun
2382 if (context->poll_changed)
2384 UNLOCK_CONTEXT (context);
2387 #endif /* G_THREADS_ENABLED */
2389 pollrec = context->poll_records;
2393 if (pollrec->fd->events)
2395 pollrec->fd->revents = fds[i].revents;
2398 pollrec = pollrec->next;
2401 source = next_valid_source (context, NULL);
2404 if ((n_ready > 0) && (source->priority > max_priority))
2406 SOURCE_UNREF (source, context);
2409 if (SOURCE_BLOCKED (source))
2412 if (!(source->flags & G_SOURCE_READY))
2415 gboolean (*check) (GSource *source);
2417 check = source->source_funcs->check;
2419 context->in_check_or_prepare++;
2420 UNLOCK_CONTEXT (context);
2422 result = (*check) (source);
2424 LOCK_CONTEXT (context);
2425 context->in_check_or_prepare--;
2428 source->flags |= G_SOURCE_READY;
2431 if (source->flags & G_SOURCE_READY)
2433 source->ref_count++;
2434 g_ptr_array_add (context->pending_dispatches, source);
2438 /* never dispatch sources with less priority than the first
2439 * one we choose to dispatch
2441 max_priority = source->priority;
2445 source = next_valid_source (context, source);
2448 UNLOCK_CONTEXT (context);
2454 * g_main_context_dispatch:
2455 * @context: a #GMainContext
2457 * Dispatches all pending sources.
2460 g_main_context_dispatch (GMainContext *context)
2462 LOCK_CONTEXT (context);
2464 if (context->pending_dispatches->len > 0)
2466 g_main_dispatch (context);
2469 UNLOCK_CONTEXT (context);
2472 /* HOLDS context lock */
2474 g_main_context_iterate (GMainContext *context,
2481 gboolean some_ready;
2482 gint nfds, allocated_nfds;
2483 GPollFD *fds = NULL;
2485 UNLOCK_CONTEXT (context);
2487 #ifdef G_THREADS_ENABLED
2488 if (!g_main_context_acquire (context))
2490 gboolean got_ownership;
2492 g_return_val_if_fail (g_thread_supported (), FALSE);
2497 LOCK_CONTEXT (context);
2500 context->cond = g_cond_new ();
2502 got_ownership = g_main_context_wait (context,
2504 g_static_mutex_get_mutex (&context->mutex));
2508 UNLOCK_CONTEXT (context);
2513 LOCK_CONTEXT (context);
2514 #endif /* G_THREADS_ENABLED */
2516 if (!context->cached_poll_array)
2518 context->cached_poll_array_size = context->n_poll_records;
2519 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2522 allocated_nfds = context->cached_poll_array_size;
2523 fds = context->cached_poll_array;
2525 UNLOCK_CONTEXT (context);
2527 g_main_context_prepare (context, &max_priority);
2529 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
2530 allocated_nfds)) > allocated_nfds)
2532 LOCK_CONTEXT (context);
2534 context->cached_poll_array_size = allocated_nfds = nfds;
2535 context->cached_poll_array = fds = g_new (GPollFD, nfds);
2536 UNLOCK_CONTEXT (context);
2542 g_main_context_poll (context, timeout, max_priority, fds, nfds);
2544 some_ready = g_main_context_check (context, max_priority, fds, nfds);
2547 g_main_context_dispatch (context);
2549 #ifdef G_THREADS_ENABLED
2550 g_main_context_release (context);
2551 #endif /* G_THREADS_ENABLED */
2553 LOCK_CONTEXT (context);
2559 * g_main_context_pending:
2560 * @context: a #GMainContext (if %NULL, the default context will be used)
2562 * Checks if any sources have pending events for the given context.
2564 * Return value: %TRUE if events are pending.
2567 g_main_context_pending (GMainContext *context)
2572 context = g_main_context_default();
2574 LOCK_CONTEXT (context);
2575 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
2576 UNLOCK_CONTEXT (context);
2582 * g_main_context_iteration:
2583 * @context: a #GMainContext (if %NULL, the default context will be used)
2584 * @may_block: whether the call may block.
2586 * Runs a single iteration for the given main loop. This involves
2587 * checking to see if any event sources are ready to be processed,
2588 * then if no events sources are ready and @may_block is %TRUE, waiting
2589 * for a source to become ready, then dispatching the highest priority
2590 * events sources that are ready. Note that even when @may_block is %TRUE,
2591 * it is still possible for g_main_context_iteration() to return
2592 * %FALSE, since the the wait may be interrupted for other
2593 * reasons than an event source becoming ready.
2595 * Return value: %TRUE if events were dispatched.
2598 g_main_context_iteration (GMainContext *context, gboolean may_block)
2603 context = g_main_context_default();
2605 LOCK_CONTEXT (context);
2606 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
2607 UNLOCK_CONTEXT (context);
2614 * @context: a #GMainContext (if %NULL, the default context will be used).
2615 * @is_running: set to %TRUE to indicate that the loop is running. This
2616 * is not very important since calling g_main_loop_run() will set this to
2619 * Creates a new #GMainLoop structure.
2621 * Return value: a new #GMainLoop.
2624 g_main_loop_new (GMainContext *context,
2625 gboolean is_running)
2630 context = g_main_context_default();
2632 g_main_context_ref (context);
2634 loop = g_new0 (GMainLoop, 1);
2635 loop->context = context;
2636 loop->is_running = is_running != FALSE;
2637 loop->ref_count = 1;
2644 * @loop: a #GMainLoop
2646 * Increases the reference count on a #GMainLoop object by one.
2648 * Return value: @loop
2651 g_main_loop_ref (GMainLoop *loop)
2653 g_return_val_if_fail (loop != NULL, NULL);
2654 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2656 g_atomic_int_inc (&loop->ref_count);
2662 * g_main_loop_unref:
2663 * @loop: a #GMainLoop
2665 * Decreases the reference count on a #GMainLoop object by one. If
2666 * the result is zero, free the loop and free all associated memory.
2669 g_main_loop_unref (GMainLoop *loop)
2671 g_return_if_fail (loop != NULL);
2672 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2674 if (!g_atomic_int_dec_and_test (&loop->ref_count))
2677 g_main_context_unref (loop->context);
2683 * @loop: a #GMainLoop
2685 * Runs a main loop until g_main_loop_quit() is called on the loop.
2686 * If this is called for the thread of the loop's #GMainContext,
2687 * it will process events from the loop, otherwise it will
2691 g_main_loop_run (GMainLoop *loop)
2693 GThread *self = G_THREAD_SELF;
2695 g_return_if_fail (loop != NULL);
2696 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2698 #ifdef G_THREADS_ENABLED
2699 if (!g_main_context_acquire (loop->context))
2701 gboolean got_ownership = FALSE;
2703 /* Another thread owns this context */
2704 if (!g_thread_supported ())
2706 g_warning ("g_main_loop_run() was called from second thread but "
2707 "g_thread_init() was never called.");
2711 LOCK_CONTEXT (loop->context);
2713 g_atomic_int_inc (&loop->ref_count);
2715 if (!loop->is_running)
2716 loop->is_running = TRUE;
2718 if (!loop->context->cond)
2719 loop->context->cond = g_cond_new ();
2721 while (loop->is_running && !got_ownership)
2722 got_ownership = g_main_context_wait (loop->context,
2723 loop->context->cond,
2724 g_static_mutex_get_mutex (&loop->context->mutex));
2726 if (!loop->is_running)
2728 UNLOCK_CONTEXT (loop->context);
2730 g_main_context_release (loop->context);
2731 g_main_loop_unref (loop);
2735 g_assert (got_ownership);
2738 LOCK_CONTEXT (loop->context);
2739 #endif /* G_THREADS_ENABLED */
2741 if (loop->context->in_check_or_prepare)
2743 g_warning ("g_main_loop_run(): called recursively from within a source's "
2744 "check() or prepare() member, iteration not possible.");
2748 g_atomic_int_inc (&loop->ref_count);
2749 loop->is_running = TRUE;
2750 while (loop->is_running)
2751 g_main_context_iterate (loop->context, TRUE, TRUE, self);
2753 UNLOCK_CONTEXT (loop->context);
2755 #ifdef G_THREADS_ENABLED
2756 g_main_context_release (loop->context);
2757 #endif /* G_THREADS_ENABLED */
2759 g_main_loop_unref (loop);
2764 * @loop: a #GMainLoop
2766 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
2767 * for the loop will return.
2770 g_main_loop_quit (GMainLoop *loop)
2772 g_return_if_fail (loop != NULL);
2773 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2775 LOCK_CONTEXT (loop->context);
2776 loop->is_running = FALSE;
2777 g_main_context_wakeup_unlocked (loop->context);
2779 #ifdef G_THREADS_ENABLED
2780 if (loop->context->cond)
2781 g_cond_broadcast (loop->context->cond);
2782 #endif /* G_THREADS_ENABLED */
2784 UNLOCK_CONTEXT (loop->context);
2788 * g_main_loop_is_running:
2789 * @loop: a #GMainLoop.
2791 * Checks to see if the main loop is currently being run via g_main_loop_run().
2793 * Return value: %TRUE if the mainloop is currently being run.
2796 g_main_loop_is_running (GMainLoop *loop)
2798 g_return_val_if_fail (loop != NULL, FALSE);
2799 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
2801 return loop->is_running;
2805 * g_main_loop_get_context:
2806 * @loop: a #GMainLoop.
2808 * Returns the #GMainContext of @loop.
2810 * Return value: the #GMainContext of @loop
2813 g_main_loop_get_context (GMainLoop *loop)
2815 g_return_val_if_fail (loop != NULL, NULL);
2816 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2818 return loop->context;
2821 /* HOLDS: context's lock */
2823 g_main_context_poll (GMainContext *context,
2829 #ifdef G_MAIN_POLL_DEBUG
2835 GPollFunc poll_func;
2837 if (n_fds || timeout != 0)
2839 #ifdef G_MAIN_POLL_DEBUG
2840 g_print ("g_main_poll(%d) timeout: %d\n", n_fds, timeout);
2841 poll_timer = g_timer_new ();
2844 LOCK_CONTEXT (context);
2846 poll_func = context->poll_func;
2848 UNLOCK_CONTEXT (context);
2849 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
2852 g_warning ("poll(2) failed due to: %s.",
2853 g_strerror (errno));
2855 /* If g_poll () returns -1, it has already called g_warning() */
2859 #ifdef G_MAIN_POLL_DEBUG
2860 LOCK_CONTEXT (context);
2862 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
2865 g_timer_elapsed (poll_timer, NULL));
2866 g_timer_destroy (poll_timer);
2867 pollrec = context->poll_records;
2871 if (pollrec->fd->events)
2875 g_print (" [%d:", fds[i].fd);
2876 if (fds[i].revents & G_IO_IN)
2878 if (fds[i].revents & G_IO_OUT)
2880 if (fds[i].revents & G_IO_PRI)
2882 if (fds[i].revents & G_IO_ERR)
2884 if (fds[i].revents & G_IO_HUP)
2886 if (fds[i].revents & G_IO_NVAL)
2892 pollrec = pollrec->next;
2896 UNLOCK_CONTEXT (context);
2898 } /* if (n_fds || timeout != 0) */
2902 * g_main_context_add_poll:
2903 * @context: a #GMainContext (or %NULL for the default context)
2904 * @fd: a #GPollFD structure holding information about a file
2905 * descriptor to watch.
2906 * @priority: the priority for this file descriptor which should be
2907 * the same as the priority used for g_source_attach() to ensure that the
2908 * file descriptor is polled whenever the results may be needed.
2910 * Adds a file descriptor to the set of file descriptors polled for
2911 * this context. This will very seldomly be used directly. Instead
2912 * a typical event source will use g_source_add_poll() instead.
2915 g_main_context_add_poll (GMainContext *context,
2920 context = g_main_context_default ();
2922 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
2923 g_return_if_fail (fd);
2925 LOCK_CONTEXT (context);
2926 g_main_context_add_poll_unlocked (context, priority, fd);
2927 UNLOCK_CONTEXT (context);
2930 /* HOLDS: main_loop_lock */
2932 g_main_context_add_poll_unlocked (GMainContext *context,
2936 GPollRec *lastrec, *pollrec;
2937 GPollRec *newrec = g_slice_new (GPollRec);
2939 /* This file descriptor may be checked before we ever poll */
2942 newrec->priority = priority;
2945 pollrec = context->poll_records;
2946 while (pollrec && priority >= pollrec->priority)
2949 pollrec = pollrec->next;
2953 lastrec->next = newrec;
2955 context->poll_records = newrec;
2957 newrec->next = pollrec;
2959 context->n_poll_records++;
2961 #ifdef G_THREADS_ENABLED
2962 context->poll_changed = TRUE;
2964 /* Now wake up the main loop if it is waiting in the poll() */
2965 g_main_context_wakeup_unlocked (context);
2970 * g_main_context_remove_poll:
2971 * @context:a #GMainContext
2972 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
2974 * Removes file descriptor from the set of file descriptors to be
2975 * polled for a particular context.
2978 g_main_context_remove_poll (GMainContext *context,
2982 context = g_main_context_default ();
2984 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
2985 g_return_if_fail (fd);
2987 LOCK_CONTEXT (context);
2988 g_main_context_remove_poll_unlocked (context, fd);
2989 UNLOCK_CONTEXT (context);
2993 g_main_context_remove_poll_unlocked (GMainContext *context,
2996 GPollRec *pollrec, *lastrec;
2999 pollrec = context->poll_records;
3003 if (pollrec->fd == fd)
3005 if (lastrec != NULL)
3006 lastrec->next = pollrec->next;
3008 context->poll_records = pollrec->next;
3010 g_slice_free (GPollRec, pollrec);
3012 context->n_poll_records--;
3016 pollrec = pollrec->next;
3019 #ifdef G_THREADS_ENABLED
3020 context->poll_changed = TRUE;
3022 /* Now wake up the main loop if it is waiting in the poll() */
3023 g_main_context_wakeup_unlocked (context);
3028 * g_source_get_current_time:
3029 * @source: a #GSource
3030 * @timeval: #GTimeVal structure in which to store current time.
3032 * Gets the "current time" to be used when checking
3033 * this source. The advantage of calling this function over
3034 * calling g_get_current_time() directly is that when
3035 * checking multiple sources, GLib can cache a single value
3036 * instead of having to repeatedly get the system time.
3039 g_source_get_current_time (GSource *source,
3042 GMainContext *context;
3044 g_return_if_fail (source->context != NULL);
3046 context = source->context;
3048 LOCK_CONTEXT (context);
3050 if (!context->time_is_current)
3052 g_get_current_time (&context->current_time);
3053 context->time_is_current = TRUE;
3056 *timeval = context->current_time;
3058 UNLOCK_CONTEXT (context);
3062 * g_main_context_set_poll_func:
3063 * @context: a #GMainContext
3064 * @func: the function to call to poll all file descriptors
3066 * Sets the function to use to handle polling of file descriptors. It
3067 * will be used instead of the poll() system call
3068 * (or GLib's replacement function, which is used where
3069 * poll() isn't available).
3071 * This function could possibly be used to integrate the GLib event
3072 * loop with an external event loop.
3075 g_main_context_set_poll_func (GMainContext *context,
3079 context = g_main_context_default ();
3081 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3083 LOCK_CONTEXT (context);
3086 context->poll_func = func;
3090 context->poll_func = (GPollFunc) poll;
3092 context->poll_func = (GPollFunc) g_poll;
3096 UNLOCK_CONTEXT (context);
3100 * g_main_context_get_poll_func:
3101 * @context: a #GMainContext
3103 * Gets the poll function set by g_main_context_set_poll_func().
3105 * Return value: the poll function
3108 g_main_context_get_poll_func (GMainContext *context)
3113 context = g_main_context_default ();
3115 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3117 LOCK_CONTEXT (context);
3118 result = context->poll_func;
3119 UNLOCK_CONTEXT (context);
3124 /* HOLDS: context's lock */
3125 /* Wake the main loop up from a poll() */
3127 g_main_context_wakeup_unlocked (GMainContext *context)
3129 #ifdef G_THREADS_ENABLED
3130 if (g_thread_supported() && context->poll_waiting)
3132 context->poll_waiting = FALSE;
3134 write (context->wake_up_pipe[1], "A", 1);
3136 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
3143 * g_main_context_wakeup:
3144 * @context: a #GMainContext
3146 * If @context is currently waiting in a poll(), interrupt
3147 * the poll(), and continue the iteration process.
3150 g_main_context_wakeup (GMainContext *context)
3153 context = g_main_context_default ();
3155 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3157 LOCK_CONTEXT (context);
3158 g_main_context_wakeup_unlocked (context);
3159 UNLOCK_CONTEXT (context);
3163 * g_main_context_is_owner:
3164 * @context: a #GMainContext
3166 * Determines whether this thread holds the (recursive)
3167 * ownership of this #GMaincontext. This is useful to
3168 * know before waiting on another thread that may be
3169 * blocking to get ownership of @context.
3171 * Returns: %TRUE if current thread is owner of @context.
3176 g_main_context_is_owner (GMainContext *context)
3181 context = g_main_context_default ();
3183 #ifdef G_THREADS_ENABLED
3184 LOCK_CONTEXT (context);
3185 is_owner = context->owner == G_THREAD_SELF;
3186 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 (greater than 0) of the 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 (greater than 0) of the 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,
3496 return check_for_child_exited (source);
3501 g_child_watch_check (GSource *source)
3503 return check_for_child_exited (source);
3506 #endif /* G_OS_WIN32 */
3509 g_child_watch_dispatch (GSource *source,
3510 GSourceFunc callback,
3513 GChildWatchSource *child_watch_source;
3514 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
3516 child_watch_source = (GChildWatchSource *) source;
3520 g_warning ("Child watch source dispatched without callback\n"
3521 "You must call g_source_set_callback().");
3525 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
3527 /* We never keep a child watch source around as the child is gone */
3534 g_child_watch_signal_handler (int signum)
3536 child_watch_count ++;
3538 if (child_watch_init_state == CHILD_WATCH_INITIALIZED_THREADED)
3540 write (child_watch_wake_up_pipe[1], "B", 1);
3544 /* We count on the signal interrupting the poll in the same thread.
3550 g_child_watch_source_init_single (void)
3552 struct sigaction action;
3554 g_assert (! g_thread_supported());
3555 g_assert (child_watch_init_state == CHILD_WATCH_UNINITIALIZED);
3557 child_watch_init_state = CHILD_WATCH_INITIALIZED_SINGLE;
3559 action.sa_handler = g_child_watch_signal_handler;
3560 sigemptyset (&action.sa_mask);
3561 action.sa_flags = SA_NOCLDSTOP;
3562 sigaction (SIGCHLD, &action, NULL);
3566 child_watch_helper_thread (gpointer data)
3573 read (child_watch_wake_up_pipe[0], b, 20);
3575 /* We were woken up. Wake up all other contexts in all other threads */
3576 G_LOCK (main_context_list);
3577 for (list = main_context_list; list; list = list->next)
3579 GMainContext *context;
3581 context = list->data;
3582 if (g_atomic_int_get (&context->ref_count) > 0)
3583 /* Due to racing conditions we can find ref_count == 0, in
3584 * that case, however, the context is still not destroyed
3585 * and no poll can be active, otherwise the ref_count
3587 g_main_context_wakeup (context);
3589 G_UNLOCK (main_context_list);
3594 g_child_watch_source_init_multi_threaded (void)
3596 GError *error = NULL;
3597 struct sigaction action;
3599 g_assert (g_thread_supported());
3601 if (pipe (child_watch_wake_up_pipe) < 0)
3602 g_error ("Cannot create wake up pipe: %s\n", g_strerror (errno));
3603 fcntl (child_watch_wake_up_pipe[1], F_SETFL, O_NONBLOCK | fcntl (child_watch_wake_up_pipe[1], F_GETFL));
3605 /* We create a helper thread that polls on the wakeup pipe indefinitely */
3606 /* FIXME: Think this through for races */
3607 if (g_thread_create (child_watch_helper_thread, NULL, FALSE, &error) == NULL)
3608 g_error ("Cannot create a thread to monitor child exit status: %s\n", error->message);
3609 child_watch_init_state = CHILD_WATCH_INITIALIZED_THREADED;
3611 action.sa_handler = g_child_watch_signal_handler;
3612 sigemptyset (&action.sa_mask);
3613 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
3614 sigaction (SIGCHLD, &action, NULL);
3618 g_child_watch_source_init_promote_single_to_threaded (void)
3620 g_child_watch_source_init_multi_threaded ();
3624 g_child_watch_source_init (void)
3626 if (g_thread_supported())
3628 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
3629 g_child_watch_source_init_multi_threaded ();
3630 else if (child_watch_init_state == CHILD_WATCH_INITIALIZED_SINGLE)
3631 g_child_watch_source_init_promote_single_to_threaded ();
3635 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
3636 g_child_watch_source_init_single ();
3640 #endif /* !G_OS_WIN32 */
3643 * g_child_watch_source_new:
3644 * @pid: process id of a child process to watch. On Windows, a HANDLE
3645 * for the process to watch (which actually doesn't have to be a child).
3647 * Creates a new child_watch source.
3649 * The source will not initially be associated with any #GMainContext
3650 * and must be added to one with g_source_attach() before it will be
3653 * Note that child watch sources can only be used in conjunction with
3654 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
3657 * Note that on platforms where #GPid must be explicitely closed
3658 * (see g_spawn_close_pid()) @pid must not be closed while the
3659 * source is still active. Typically, you will want to call
3660 * g_spawn_close_pid() in the callback function for the source.
3662 * Note further that using g_child_watch_source_new() is not
3663 * compatible with calling <literal>waitpid(-1)</literal> in
3664 * the application. Calling waitpid() for individual pids will
3667 * Return value: the newly-created child watch source
3672 g_child_watch_source_new (GPid pid)
3674 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
3675 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
3678 child_watch_source->poll.fd = (int)pid;
3679 child_watch_source->poll.events = G_IO_IN;
3681 g_source_add_poll (source, &child_watch_source->poll);
3682 #else /* G_OS_WIN32 */
3683 g_child_watch_source_init ();
3684 #endif /* G_OS_WIN32 */
3686 child_watch_source->pid = pid;
3692 * g_child_watch_add_full:
3693 * @priority: the priority of the idle source. Typically this will be in the
3694 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3695 * @pid: process id of a child process to watch
3696 * @function: function to call
3697 * @data: data to pass to @function
3698 * @notify: function to call when the idle is removed, or %NULL
3700 * Sets a function to be called when the child indicated by @pid exits, at a
3701 * default priority, #G_PRIORITY_DEFAULT.
3703 * Note that on platforms where #GPid must be explicitely closed
3704 * (see g_spawn_close_pid()) @pid must not be closed while the
3705 * source is still active. Typically, you will want to call
3706 * g_spawn_close_pid() in the callback function for the source.
3708 * GLib supports only a single callback per process id.
3710 * Return value: the ID (greater than 0) of the event source.
3715 g_child_watch_add_full (gint priority,
3717 GChildWatchFunc function,
3719 GDestroyNotify notify)
3724 g_return_val_if_fail (function != NULL, 0);
3726 source = g_child_watch_source_new (pid);
3728 if (priority != G_PRIORITY_DEFAULT)
3729 g_source_set_priority (source, priority);
3731 g_source_set_callback (source, (GSourceFunc) function, data, notify);
3732 id = g_source_attach (source, NULL);
3733 g_source_unref (source);
3739 * g_child_watch_add:
3740 * @pid: process id of a child process to watch
3741 * @function: function to call
3742 * @data: data to pass to @function
3744 * Sets a function to be called when the child indicated by @pid exits, at a
3745 * default priority, #G_PRIORITY_DEFAULT.
3747 * Note that on platforms where #GPid must be explicitely closed
3748 * (see g_spawn_close_pid()) @pid must not be closed while the
3749 * source is still active. Typically, you will want to call
3750 * g_spawn_close_pid() in the callback function for the source.
3752 * GLib supports only a single callback per process id.
3754 * Return value: the ID (greater than 0) of the event source.
3759 g_child_watch_add (GPid pid,
3760 GChildWatchFunc function,
3763 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
3767 /* Idle functions */
3770 g_idle_prepare (GSource *source,
3779 g_idle_check (GSource *source)
3785 g_idle_dispatch (GSource *source,
3786 GSourceFunc callback,
3791 g_warning ("Idle source dispatched without callback\n"
3792 "You must call g_source_set_callback().");
3796 return callback (user_data);
3800 * g_idle_source_new:
3802 * Creates a new idle source.
3804 * The source will not initially be associated with any #GMainContext
3805 * and must be added to one with g_source_attach() before it will be
3806 * executed. Note that the default priority for idle sources is
3807 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
3808 * have a default priority of %G_PRIORITY_DEFAULT.
3810 * Return value: the newly-created idle source
3813 g_idle_source_new (void)
3817 source = g_source_new (&g_idle_funcs, sizeof (GSource));
3818 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
3825 * @priority: the priority of the idle source. Typically this will be in the
3826 * range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3827 * @function: function to call
3828 * @data: data to pass to @function
3829 * @notify: function to call when the idle is removed, or %NULL
3831 * Adds a function to be called whenever there are no higher priority
3832 * events pending. If the function returns %FALSE it is automatically
3833 * removed from the list of event sources and will not be called again.
3835 * Return value: the ID (greater than 0) of the event source.
3838 g_idle_add_full (gint priority,
3839 GSourceFunc function,
3841 GDestroyNotify notify)
3846 g_return_val_if_fail (function != NULL, 0);
3848 source = g_idle_source_new ();
3850 if (priority != G_PRIORITY_DEFAULT_IDLE)
3851 g_source_set_priority (source, priority);
3853 g_source_set_callback (source, function, data, notify);
3854 id = g_source_attach (source, NULL);
3855 g_source_unref (source);
3862 * @function: function to call
3863 * @data: data to pass to @function.
3865 * Adds a function to be called whenever there are no higher priority
3866 * events pending to the default main loop. The function is given the
3867 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
3868 * returns %FALSE it is automatically removed from the list of event
3869 * sources and will not be called again.
3871 * Return value: the ID (greater than 0) of the event source.
3874 g_idle_add (GSourceFunc function,
3877 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
3881 * g_idle_remove_by_data:
3882 * @data: the data for the idle source's callback.
3884 * Removes the idle function with the given data.
3886 * Return value: %TRUE if an idle source was found and removed.
3889 g_idle_remove_by_data (gpointer data)
3891 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
3894 #define __G_MAIN_C__
3895 #include "galiasdef.c"