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 */
41 #include "gthreadinit.h"
43 #include <sys/types.h>
45 #ifdef HAVE_SYS_TIME_H
47 #endif /* HAVE_SYS_TIME_H */
48 #ifdef GLIB_HAVE_SYS_POLL_H
49 # include <sys/poll.h>
50 # undef events /* AIX 4.1.5 & 4.3.2 define this for SVR3,4 compatibility */
51 # undef revents /* AIX 4.1.5 & 4.3.2 define this for SVR3,4 compatibility */
53 /* The poll() emulation on OS/X doesn't handle fds=NULL, nfds=0,
54 * so we prefer our own poll emulation.
60 #endif /* GLIB_HAVE_SYS_POLL_H */
63 #endif /* HAVE_UNISTD_H */
69 #endif /* G_OS_WIN32 */
72 #include <net/socket.h>
73 #endif /* G_OS_BEOS */
81 typedef struct _GTimeoutSource GTimeoutSource;
82 typedef struct _GChildWatchSource GChildWatchSource;
83 typedef struct _GPollRec GPollRec;
84 typedef struct _GSourceCallback GSourceCallback;
88 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
89 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
92 #ifdef G_THREADS_ENABLED
93 typedef struct _GMainWaiter GMainWaiter;
104 #ifdef G_THREADS_ENABLED
105 /* The following lock is used for both the list of sources
106 * and the list of poll records
117 GPtrArray *pending_dispatches;
118 gint timeout; /* Timeout for current iteration */
121 GSource *source_list;
122 gint in_check_or_prepare;
124 GPollRec *poll_records;
125 GPollRec *poll_free_list;
126 GMemChunk *poll_chunk;
127 guint n_poll_records;
128 GPollFD *cached_poll_array;
129 guint cached_poll_array_size;
131 #ifdef G_THREADS_ENABLED
133 /* this pipe is used to wake up the main loop when a source is added.
135 gint wake_up_pipe[2];
136 #else /* G_OS_WIN32 */
137 HANDLE wake_up_semaphore;
138 #endif /* G_OS_WIN32 */
141 gboolean poll_waiting;
143 /* Flag indicating whether the set of fd's changed during a poll */
144 gboolean poll_changed;
145 #endif /* G_THREADS_ENABLED */
149 GTimeVal current_time;
150 gboolean time_is_current;
153 struct _GSourceCallback
158 GDestroyNotify notify;
163 GMainContext *context;
168 struct _GTimeoutSource
175 struct _GChildWatchSource
182 #else /* G_OS_WIN32 */
184 gboolean child_exited;
185 #endif /* G_OS_WIN32 */
195 #ifdef G_THREADS_ENABLED
196 #define LOCK_CONTEXT(context) g_static_mutex_lock (&context->mutex)
197 #define UNLOCK_CONTEXT(context) g_static_mutex_unlock (&context->mutex)
198 #define G_THREAD_SELF g_thread_self ()
200 #define LOCK_CONTEXT(context) (void)0
201 #define UNLOCK_CONTEXT(context) (void)0
202 #define G_THREAD_SELF NULL
205 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
206 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
207 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
209 #define SOURCE_UNREF(source, context) \
211 if ((source)->ref_count > 1) \
212 (source)->ref_count--; \
214 g_source_unref_internal ((source), (context), TRUE); \
218 /* Forward declarations */
220 static void g_source_unref_internal (GSource *source,
221 GMainContext *context,
223 static void g_source_destroy_internal (GSource *source,
224 GMainContext *context,
226 static void g_main_context_poll (GMainContext *context,
231 static void g_main_context_add_poll_unlocked (GMainContext *context,
234 static void g_main_context_remove_poll_unlocked (GMainContext *context,
236 static void g_main_context_wakeup_unlocked (GMainContext *context);
238 static gboolean g_timeout_prepare (GSource *source,
240 static gboolean g_timeout_check (GSource *source);
241 static gboolean g_timeout_dispatch (GSource *source,
242 GSourceFunc callback,
244 static gboolean g_child_watch_prepare (GSource *source,
246 static gboolean g_child_watch_check (GSource *source);
247 static gboolean g_child_watch_dispatch (GSource *source,
248 GSourceFunc callback,
250 static gboolean g_idle_prepare (GSource *source,
252 static gboolean g_idle_check (GSource *source);
253 static gboolean g_idle_dispatch (GSource *source,
254 GSourceFunc callback,
257 G_LOCK_DEFINE_STATIC (main_loop);
258 static GMainContext *default_main_context;
259 static GSList *main_contexts_without_pipe = NULL;
262 /* Child status monitoring code */
264 CHILD_WATCH_UNINITIALIZED,
265 CHILD_WATCH_INITIALIZED_SINGLE,
266 CHILD_WATCH_INITIALIZED_THREADED
268 static gint child_watch_init_state = CHILD_WATCH_UNINITIALIZED;
269 static gint child_watch_count = 0;
270 static gint child_watch_wake_up_pipe[2] = {0, 0};
271 #endif /* !G_OS_WIN32 */
272 G_LOCK_DEFINE_STATIC (main_context_list);
273 static GSList *main_context_list = NULL;
275 GSourceFuncs g_timeout_funcs =
283 GSourceFuncs g_child_watch_funcs =
285 g_child_watch_prepare,
287 g_child_watch_dispatch,
291 GSourceFuncs g_idle_funcs =
300 /* SunOS has poll, but doesn't provide a prototype. */
301 # if defined (sun) && !defined (__SVR4)
302 extern gint poll (GPollFD *ufds, guint nfsd, gint timeout);
304 #else /* !HAVE_POLL */
309 g_poll (GPollFD *fds,
313 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
314 gboolean poll_msgs = FALSE;
321 for (f = fds; f < &fds[nfds]; ++f)
324 if (f->fd == G_WIN32_MSG_HANDLE)
326 else if (nhandles == MAXIMUM_WAIT_OBJECTS)
328 g_warning (G_STRLOC ": Too many handles to wait for!\n");
333 #ifdef G_MAIN_POLL_DEBUG
334 g_print ("g_poll: waiting for %#x\n", f->fd);
336 handles[nhandles++] = (HANDLE) f->fd;
345 /* Waiting for messages, and maybe events
346 * -> First PeekMessage
348 #ifdef G_MAIN_POLL_DEBUG
349 g_print ("PeekMessage\n");
351 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
352 ready = WAIT_OBJECT_0 + nhandles;
357 /* Waiting just for messages */
358 if (timeout == INFINITE)
363 #ifdef G_MAIN_POLL_DEBUG
364 g_print ("WaitMessage\n");
368 gchar *emsg = g_win32_error_message (GetLastError ());
369 g_warning (G_STRLOC ": WaitMessage() failed: %s", emsg);
372 ready = WAIT_OBJECT_0 + nhandles;
374 else if (timeout == 0)
376 /* Waiting just for messages, zero timeout.
377 * If we got here, there was no message
379 ready = WAIT_TIMEOUT;
383 /* Waiting just for messages, some timeout
384 * -> Set a timer, wait for message,
385 * kill timer, use PeekMessage
387 timer = SetTimer (NULL, 0, timeout, NULL);
390 gchar *emsg = g_win32_error_message (GetLastError ());
391 g_warning (G_STRLOC ": SetTimer() failed: %s", emsg);
393 ready = WAIT_TIMEOUT;
397 #ifdef G_MAIN_POLL_DEBUG
398 g_print ("WaitMessage\n");
401 KillTimer (NULL, timer);
402 #ifdef G_MAIN_POLL_DEBUG
403 g_print ("PeekMessage\n");
405 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE)
406 && msg.message != WM_TIMER)
407 ready = WAIT_OBJECT_0;
409 ready = WAIT_TIMEOUT;
415 /* Wait for either message or event
416 * -> Use MsgWaitForMultipleObjects
418 #ifdef G_MAIN_POLL_DEBUG
419 g_print ("MsgWaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
421 ready = MsgWaitForMultipleObjects (nhandles, handles, FALSE,
422 timeout, QS_ALLINPUT);
424 if (ready == WAIT_FAILED)
426 gchar *emsg = g_win32_error_message (GetLastError ());
427 g_warning (G_STRLOC ": MsgWaitForMultipleObjects() failed: %s", emsg);
433 else if (nhandles == 0)
435 /* Wait for nothing (huh?) */
440 /* Wait for just events
441 * -> Use WaitForMultipleObjects
443 #ifdef G_MAIN_POLL_DEBUG
444 g_print ("WaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
446 ready = WaitForMultipleObjects (nhandles, handles, FALSE, timeout);
447 if (ready == WAIT_FAILED)
449 gchar *emsg = g_win32_error_message (GetLastError ());
450 g_warning (G_STRLOC ": WaitForMultipleObjects() failed: %s", emsg);
455 #ifdef G_MAIN_POLL_DEBUG
456 g_print ("wait returns %ld%s\n",
458 (ready == WAIT_FAILED ? " (WAIT_FAILED)" :
459 (ready == WAIT_TIMEOUT ? " (WAIT_TIMEOUT)" :
460 (poll_msgs && ready == WAIT_OBJECT_0 + nhandles ? " (msg)" : ""))));
462 for (f = fds; f < &fds[nfds]; ++f)
465 if (ready == WAIT_FAILED)
467 else if (ready == WAIT_TIMEOUT)
469 else if (poll_msgs && ready == WAIT_OBJECT_0 + nhandles)
471 for (f = fds; f < &fds[nfds]; ++f)
474 if (f->events & G_IO_IN)
475 if (f->fd == G_WIN32_MSG_HANDLE)
476 f->revents |= G_IO_IN;
479 #if 1 /* TEST_WITHOUT_THIS */
480 else if (ready >= WAIT_OBJECT_0 && ready < WAIT_OBJECT_0 + nhandles)
481 for (f = fds; f < &fds[nfds]; ++f)
483 if ((f->events & (G_IO_IN | G_IO_OUT))
484 && f->fd == (gint) handles[ready - WAIT_OBJECT_0])
486 if (f->events & G_IO_IN)
487 f->revents |= G_IO_IN;
489 f->revents |= G_IO_OUT;
490 #ifdef G_MAIN_POLL_DEBUG
491 g_print ("g_poll: got event %#x\n", f->fd);
494 ResetEvent ((HANDLE) f->fd);
503 #else /* !G_OS_WIN32 */
505 /* The following implementation of poll() comes from the GNU C Library.
506 * Copyright (C) 1994, 1996, 1997 Free Software Foundation, Inc.
509 #include <string.h> /* for bzero on BSD systems */
511 #ifdef HAVE_SYS_SELECT_H
512 #include <sys/select.h>
513 #endif /* HAVE_SYS_SELECT_H */
517 #endif /* G_OS_BEOS */
520 # define SELECT_MASK fd_set
521 #else /* !NO_FD_SET */
523 typedef long fd_mask;
526 # define SELECT_MASK void
528 # define SELECT_MASK int
529 # endif /* !_IBMR2 */
530 #endif /* !NO_FD_SET */
533 g_poll (GPollFD *fds,
538 SELECT_MASK rset, wset, xset;
547 for (f = fds; f < &fds[nfds]; ++f)
550 if (f->events & G_IO_IN)
551 FD_SET (f->fd, &rset);
552 if (f->events & G_IO_OUT)
553 FD_SET (f->fd, &wset);
554 if (f->events & G_IO_PRI)
555 FD_SET (f->fd, &xset);
556 if (f->fd > maxfd && (f->events & (G_IO_IN|G_IO_OUT|G_IO_PRI)))
560 tv.tv_sec = timeout / 1000;
561 tv.tv_usec = (timeout % 1000) * 1000;
563 ready = select (maxfd + 1, &rset, &wset, &xset,
564 timeout == -1 ? NULL : &tv);
566 for (f = fds; f < &fds[nfds]; ++f)
571 if (FD_ISSET (f->fd, &rset))
572 f->revents |= G_IO_IN;
573 if (FD_ISSET (f->fd, &wset))
574 f->revents |= G_IO_OUT;
575 if (FD_ISSET (f->fd, &xset))
576 f->revents |= G_IO_PRI;
583 #endif /* !G_OS_WIN32 */
585 #endif /* !HAVE_POLL */
588 * g_main_context_ref:
589 * @context: a #GMainContext
591 * Increases the reference count on a #GMainContext object by one.
594 g_main_context_ref (GMainContext *context)
596 g_return_if_fail (context != NULL);
597 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
599 g_atomic_int_inc (&context->ref_count);
602 /* If DISABLE_MEM_POOLS is defined, then freeing the
603 * mem chunk won't free the records, so we have to
604 * do it manually. The conditionalization here is
605 * an optimization; g_mem_chunk_free() is a no-op
606 * when DISABLE_MEM_POOLS is set.
608 #ifdef DISABLE_MEM_POOLS
610 poll_rec_list_free (GMainContext *context,
615 GPollRec *tmp_rec = list;
617 g_chunk_free (tmp_rec, context->poll_chunk);
620 #endif /* DISABLE_MEM_POOLS */
623 * g_main_context_unref:
624 * @context: a #GMainContext
626 * Decreases the reference count on a #GMainContext object by one. If
627 * the result is zero, free the context and free all associated memory.
630 g_main_context_unref (GMainContext *context)
633 g_return_if_fail (context != NULL);
634 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
636 if (!g_atomic_int_dec_and_test (&context->ref_count))
639 G_LOCK (main_context_list);
640 main_context_list = g_slist_remove (main_context_list, context);
641 G_UNLOCK (main_context_list);
643 source = context->source_list;
646 GSource *next = source->next;
647 g_source_destroy_internal (source, context, TRUE);
651 #ifdef G_THREADS_ENABLED
652 g_static_mutex_free (&context->mutex);
655 g_ptr_array_free (context->pending_dispatches, TRUE);
656 g_free (context->cached_poll_array);
658 #ifdef DISABLE_MEM_POLLS
659 poll_rec_list_free (context, context->poll_records);
660 poll_rec_list_free (context, context->poll_free_list);
661 #endif /* DISABLE_MEM_POOLS */
663 if (context->poll_chunk)
664 g_mem_chunk_destroy (context->poll_chunk);
666 #ifdef G_THREADS_ENABLED
667 if (g_thread_supported())
670 close (context->wake_up_pipe[0]);
671 close (context->wake_up_pipe[1]);
673 CloseHandle (context->wake_up_semaphore);
677 main_contexts_without_pipe = g_slist_remove (main_contexts_without_pipe,
684 #ifdef G_THREADS_ENABLED
686 g_main_context_init_pipe (GMainContext *context)
689 if (context->wake_up_pipe[0] != -1)
691 if (pipe (context->wake_up_pipe) < 0)
692 g_error ("Cannot create pipe main loop wake-up: %s\n",
695 context->wake_up_rec.fd = context->wake_up_pipe[0];
696 context->wake_up_rec.events = G_IO_IN;
698 if (context->wake_up_semaphore != NULL)
700 context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
701 if (context->wake_up_semaphore == NULL)
702 g_error ("Cannot create wake-up semaphore: %s",
703 g_win32_error_message (GetLastError ()));
704 context->wake_up_rec.fd = (gint) context->wake_up_semaphore;
705 context->wake_up_rec.events = G_IO_IN;
706 # ifdef G_MAIN_POLL_DEBUG
707 g_print ("wake-up semaphore: %#x\n", (guint) context->wake_up_semaphore);
710 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
714 _g_main_thread_init (void)
716 GSList *curr = main_contexts_without_pipe;
719 g_main_context_init_pipe ((GMainContext *)curr->data);
722 g_slist_free (main_contexts_without_pipe);
723 main_contexts_without_pipe = NULL;
725 #endif /* G_THREADS_ENABLED */
728 * g_main_context_new:
730 * Creates a new #GMainContext strcuture
732 * Return value: the new #GMainContext
735 g_main_context_new (void)
737 GMainContext *context = g_new0 (GMainContext, 1);
739 #ifdef G_THREADS_ENABLED
740 g_static_mutex_init (&context->mutex);
742 context->owner = NULL;
743 context->waiters = NULL;
746 context->wake_up_pipe[0] = -1;
747 context->wake_up_pipe[1] = -1;
749 context->wake_up_semaphore = NULL;
753 context->ref_count = 1;
755 context->next_id = 1;
757 context->source_list = NULL;
760 context->poll_func = (GPollFunc)poll;
762 context->poll_func = g_poll;
765 context->cached_poll_array = NULL;
766 context->cached_poll_array_size = 0;
768 context->pending_dispatches = g_ptr_array_new ();
770 context->time_is_current = FALSE;
772 #ifdef G_THREADS_ENABLED
773 if (g_thread_supported ())
774 g_main_context_init_pipe (context);
776 main_contexts_without_pipe = g_slist_prepend (main_contexts_without_pipe,
780 G_LOCK (main_context_list);
781 main_context_list = g_slist_append (main_context_list, context);
782 G_UNLOCK (main_context_list);
788 * g_main_context_default:
790 * Returns the default main context. This is the main context used
791 * for main loop functions when a main loop is not explicitly
794 * Return value: the default main context.
797 g_main_context_default (void)
803 if (!default_main_context)
804 default_main_context = g_main_context_new ();
806 G_UNLOCK (main_loop);
808 return default_main_context;
811 /* Hooks for adding to the main loop */
815 * @source_funcs: structure containing functions that implement
816 * the sources behavior.
817 * @struct_size: size of the #GSource structure to create.
819 * Creates a new #GSource structure. The size is specified to
820 * allow creating structures derived from #GSource that contain
821 * additional data. The size passed in must be at least
822 * <literal>sizeof (GSource)</literal>.
824 * The source will not initially be associated with any #GMainContext
825 * and must be added to one with g_source_attach() before it will be
828 * Return value: the newly-created #GSource.
831 g_source_new (GSourceFuncs *source_funcs,
836 g_return_val_if_fail (source_funcs != NULL, NULL);
837 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
839 source = (GSource*) g_malloc0 (struct_size);
841 source->source_funcs = source_funcs;
842 source->ref_count = 1;
844 source->priority = G_PRIORITY_DEFAULT;
846 source->flags = G_HOOK_FLAG_ACTIVE;
848 /* NULL/0 initialization for all other fields */
853 /* Holds context's lock
856 g_source_list_add (GSource *source,
857 GMainContext *context)
859 GSource *tmp_source, *last_source;
862 tmp_source = context->source_list;
863 while (tmp_source && tmp_source->priority <= source->priority)
865 last_source = tmp_source;
866 tmp_source = tmp_source->next;
869 source->next = tmp_source;
871 tmp_source->prev = source;
873 source->prev = last_source;
875 last_source->next = source;
877 context->source_list = source;
880 /* Holds context's lock
883 g_source_list_remove (GSource *source,
884 GMainContext *context)
887 source->prev->next = source->next;
889 context->source_list = source->next;
892 source->next->prev = source->prev;
900 * @source: a #GSource
901 * @context: a #GMainContext (if %NULL, the default context will be used)
903 * Adds a #GSource to a @context so that it will be executed within
906 * Return value: the ID for the source within the #GMainContext
909 g_source_attach (GSource *source,
910 GMainContext *context)
915 g_return_val_if_fail (source->context == NULL, 0);
916 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
919 context = g_main_context_default ();
921 LOCK_CONTEXT (context);
923 source->context = context;
924 result = source->source_id = context->next_id++;
927 g_source_list_add (source, context);
929 tmp_list = source->poll_fds;
932 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
933 tmp_list = tmp_list->next;
936 #ifdef G_THREADS_ENABLED
937 /* Now wake up the main loop if it is waiting in the poll() */
938 g_main_context_wakeup_unlocked (context);
941 UNLOCK_CONTEXT (context);
947 g_source_destroy_internal (GSource *source,
948 GMainContext *context,
952 LOCK_CONTEXT (context);
954 if (!SOURCE_DESTROYED (source))
957 gpointer old_cb_data;
958 GSourceCallbackFuncs *old_cb_funcs;
960 source->flags &= ~G_HOOK_FLAG_ACTIVE;
962 old_cb_data = source->callback_data;
963 old_cb_funcs = source->callback_funcs;
965 source->callback_data = NULL;
966 source->callback_funcs = NULL;
970 UNLOCK_CONTEXT (context);
971 old_cb_funcs->unref (old_cb_data);
972 LOCK_CONTEXT (context);
975 if (!SOURCE_BLOCKED (source))
977 tmp_list = source->poll_fds;
980 g_main_context_remove_poll_unlocked (context, tmp_list->data);
981 tmp_list = tmp_list->next;
985 g_source_unref_internal (source, context, TRUE);
989 UNLOCK_CONTEXT (context);
994 * @source: a #GSource
996 * Removes a source from its #GMainContext, if any, and mark it as
997 * destroyed. The source cannot be subsequently added to another
1001 g_source_destroy (GSource *source)
1003 GMainContext *context;
1005 g_return_if_fail (source != NULL);
1007 context = source->context;
1010 g_source_destroy_internal (source, context, FALSE);
1012 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1017 * @source: a #GSource
1019 * Returns the numeric ID for a particular source. The ID of a source
1020 * is unique within a particular main loop context. The reverse
1021 * mapping from ID to source is done by g_main_context_find_source_by_id().
1023 * Return value: the ID for the source
1026 g_source_get_id (GSource *source)
1030 g_return_val_if_fail (source != NULL, 0);
1031 g_return_val_if_fail (source->context != NULL, 0);
1033 LOCK_CONTEXT (source->context);
1034 result = source->source_id;
1035 UNLOCK_CONTEXT (source->context);
1041 * g_source_get_context:
1042 * @source: a #GSource
1044 * Gets the #GMainContext with which the source is associated.
1045 * Calling this function on a destroyed source is an error.
1047 * Return value: the #GMainContext with which the source is associated,
1048 * or %NULL if the context has not yet been added
1052 g_source_get_context (GSource *source)
1054 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1056 return source->context;
1060 * g_source_add_poll:
1061 * @source:a #GSource
1062 * @fd: a #GPollFD structure holding information about a file
1063 * descriptor to watch.
1065 * Adds a file descriptor to the set of file descriptors polled for
1066 * this source. This is usually combined with g_source_new() to add an
1067 * event source. The event source's check function will typically test
1068 * the @revents field in the #GPollFD struct and return %TRUE if events need
1072 g_source_add_poll (GSource *source,
1075 GMainContext *context;
1077 g_return_if_fail (source != NULL);
1078 g_return_if_fail (fd != NULL);
1079 g_return_if_fail (!SOURCE_DESTROYED (source));
1081 context = source->context;
1084 LOCK_CONTEXT (context);
1086 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1090 if (!SOURCE_BLOCKED (source))
1091 g_main_context_add_poll_unlocked (context, source->priority, fd);
1092 UNLOCK_CONTEXT (context);
1097 * g_source_remove_poll:
1098 * @source:a #GSource
1099 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1101 * Removes a file descriptor from the set of file descriptors polled for
1105 g_source_remove_poll (GSource *source,
1108 GMainContext *context;
1110 g_return_if_fail (source != NULL);
1111 g_return_if_fail (fd != NULL);
1112 g_return_if_fail (!SOURCE_DESTROYED (source));
1114 context = source->context;
1117 LOCK_CONTEXT (context);
1119 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1123 if (!SOURCE_BLOCKED (source))
1124 g_main_context_remove_poll_unlocked (context, fd);
1125 UNLOCK_CONTEXT (context);
1130 * g_source_set_callback_indirect:
1131 * @source: the source
1132 * @callback_data: pointer to callback data "object"
1133 * @callback_funcs: functions for reference counting @callback_data
1134 * and getting the callback and data
1136 * Sets the callback function storing the data as a refcounted callback
1137 * "object". This is used internally. Note that calling
1138 * g_source_set_callback_indirect() assumes
1139 * an initial reference count on @callback_data, and thus
1140 * @callback_funcs->unref will eventually be called once more
1141 * than @callback_funcs->ref.
1144 g_source_set_callback_indirect (GSource *source,
1145 gpointer callback_data,
1146 GSourceCallbackFuncs *callback_funcs)
1148 GMainContext *context;
1149 gpointer old_cb_data;
1150 GSourceCallbackFuncs *old_cb_funcs;
1152 g_return_if_fail (source != NULL);
1153 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1155 context = source->context;
1158 LOCK_CONTEXT (context);
1160 old_cb_data = source->callback_data;
1161 old_cb_funcs = source->callback_funcs;
1163 source->callback_data = callback_data;
1164 source->callback_funcs = callback_funcs;
1167 UNLOCK_CONTEXT (context);
1170 old_cb_funcs->unref (old_cb_data);
1174 g_source_callback_ref (gpointer cb_data)
1176 GSourceCallback *callback = cb_data;
1178 callback->ref_count++;
1183 g_source_callback_unref (gpointer cb_data)
1185 GSourceCallback *callback = cb_data;
1187 callback->ref_count--;
1188 if (callback->ref_count == 0)
1190 if (callback->notify)
1191 callback->notify (callback->data);
1197 g_source_callback_get (gpointer cb_data,
1202 GSourceCallback *callback = cb_data;
1204 *func = callback->func;
1205 *data = callback->data;
1208 static GSourceCallbackFuncs g_source_callback_funcs = {
1209 g_source_callback_ref,
1210 g_source_callback_unref,
1211 g_source_callback_get,
1215 * g_source_set_callback:
1216 * @source: the source
1217 * @func: a callback function
1218 * @data: the data to pass to callback function
1219 * @notify: a function to call when @data is no longer in use, or %NULL.
1221 * Sets the callback function for a source. The callback for a source is
1222 * called from the source's dispatch function.
1224 * The exact type of @func depends on the type of source; ie. you
1225 * should not count on @func being called with @data as its first
1228 * Typically, you won't use this function. Instead use functions specific
1229 * to the type of source you are using.
1232 g_source_set_callback (GSource *source,
1235 GDestroyNotify notify)
1237 GSourceCallback *new_callback;
1239 g_return_if_fail (source != NULL);
1241 new_callback = g_new (GSourceCallback, 1);
1243 new_callback->ref_count = 1;
1244 new_callback->func = func;
1245 new_callback->data = data;
1246 new_callback->notify = notify;
1248 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1252 * g_source_set_priority:
1253 * @source: a #GSource
1254 * @priority: the new priority.
1256 * Sets the priority of a source. While the main loop is being
1257 * run, a source will be dispatched if it is ready to be dispatched and no sources
1258 * at a higher (numerically smaller) priority are ready to be dispatched.
1261 g_source_set_priority (GSource *source,
1265 GMainContext *context;
1267 g_return_if_fail (source != NULL);
1269 context = source->context;
1272 LOCK_CONTEXT (context);
1274 source->priority = priority;
1278 /* Remove the source from the context's source and then
1279 * add it back so it is sorted in the correct plcae
1281 g_source_list_remove (source, source->context);
1282 g_source_list_add (source, source->context);
1284 if (!SOURCE_BLOCKED (source))
1286 tmp_list = source->poll_fds;
1289 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1290 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1292 tmp_list = tmp_list->next;
1296 UNLOCK_CONTEXT (source->context);
1301 * g_source_get_priority:
1302 * @source: a #GSource
1304 * Gets the priority of a source.
1306 * Return value: the priority of the source
1309 g_source_get_priority (GSource *source)
1311 g_return_val_if_fail (source != NULL, 0);
1313 return source->priority;
1317 * g_source_set_can_recurse:
1318 * @source: a #GSource
1319 * @can_recurse: whether recursion is allowed for this source
1321 * Sets whether a source can be called recursively. If @can_recurse is
1322 * %TRUE, then while the source is being dispatched then this source
1323 * will be processed normally. Otherwise, all processing of this
1324 * source is blocked until the dispatch function returns.
1327 g_source_set_can_recurse (GSource *source,
1328 gboolean can_recurse)
1330 GMainContext *context;
1332 g_return_if_fail (source != NULL);
1334 context = source->context;
1337 LOCK_CONTEXT (context);
1340 source->flags |= G_SOURCE_CAN_RECURSE;
1342 source->flags &= ~G_SOURCE_CAN_RECURSE;
1345 UNLOCK_CONTEXT (context);
1349 * g_source_get_can_recurse:
1350 * @source: a #GSource
1352 * Checks whether a source is allowed to be called recursively.
1353 * see g_source_set_can_recurse().
1355 * Return value: whether recursion is allowed.
1358 g_source_get_can_recurse (GSource *source)
1360 g_return_val_if_fail (source != NULL, FALSE);
1362 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1367 * @source: a #GSource
1369 * Increases the reference count on a source by one.
1371 * Return value: @source
1374 g_source_ref (GSource *source)
1376 GMainContext *context;
1378 g_return_val_if_fail (source != NULL, NULL);
1380 context = source->context;
1383 LOCK_CONTEXT (context);
1385 source->ref_count++;
1388 UNLOCK_CONTEXT (context);
1393 /* g_source_unref() but possible to call within context lock
1396 g_source_unref_internal (GSource *source,
1397 GMainContext *context,
1400 gpointer old_cb_data = NULL;
1401 GSourceCallbackFuncs *old_cb_funcs = NULL;
1403 g_return_if_fail (source != NULL);
1405 if (!have_lock && context)
1406 LOCK_CONTEXT (context);
1408 source->ref_count--;
1409 if (source->ref_count == 0)
1411 old_cb_data = source->callback_data;
1412 old_cb_funcs = source->callback_funcs;
1414 source->callback_data = NULL;
1415 source->callback_funcs = NULL;
1417 if (context && !SOURCE_DESTROYED (source))
1419 g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1420 source->ref_count++;
1423 g_source_list_remove (source, context);
1425 if (source->source_funcs->finalize)
1426 source->source_funcs->finalize (source);
1428 g_slist_free (source->poll_fds);
1429 source->poll_fds = NULL;
1433 if (!have_lock && context)
1434 UNLOCK_CONTEXT (context);
1439 UNLOCK_CONTEXT (context);
1441 old_cb_funcs->unref (old_cb_data);
1444 LOCK_CONTEXT (context);
1450 * @source: a #GSource
1452 * Decreases the reference count of a source by one. If the
1453 * resulting reference count is zero the source and associated
1454 * memory will be destroyed.
1457 g_source_unref (GSource *source)
1459 g_return_if_fail (source != NULL);
1461 g_source_unref_internal (source, source->context, FALSE);
1465 * g_main_context_find_source_by_id:
1466 * @context: a #GMainContext (if %NULL, the default context will be used)
1467 * @source_id: the source ID, as returned by g_source_get_id()
1469 * Finds a #GSource given a pair of context and ID
1471 * Return value: the #GSource if found, otherwise, %NULL
1474 g_main_context_find_source_by_id (GMainContext *context,
1479 g_return_val_if_fail (source_id > 0, NULL);
1481 if (context == NULL)
1482 context = g_main_context_default ();
1484 LOCK_CONTEXT (context);
1486 source = context->source_list;
1489 if (!SOURCE_DESTROYED (source) &&
1490 source->source_id == source_id)
1492 source = source->next;
1495 UNLOCK_CONTEXT (context);
1501 * g_main_context_find_source_by_funcs_user_data:
1502 * @context: a #GMainContext (if %NULL, the default context will be used).
1503 * @funcs: the @source_funcs passed to g_source_new().
1504 * @user_data: the user data from the callback.
1506 * Finds a source with the given source functions and user data. If
1507 * multiple sources exist with the same source function and user data,
1508 * the first one found will be returned.
1510 * Return value: the source, if one was found, otherwise %NULL
1513 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1514 GSourceFuncs *funcs,
1519 g_return_val_if_fail (funcs != NULL, NULL);
1521 if (context == NULL)
1522 context = g_main_context_default ();
1524 LOCK_CONTEXT (context);
1526 source = context->source_list;
1529 if (!SOURCE_DESTROYED (source) &&
1530 source->source_funcs == funcs &&
1531 source->callback_funcs)
1533 GSourceFunc callback;
1534 gpointer callback_data;
1536 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1538 if (callback_data == user_data)
1541 source = source->next;
1544 UNLOCK_CONTEXT (context);
1550 * g_main_context_find_source_by_user_data:
1551 * @context: a #GMainContext
1552 * @user_data: the user_data for the callback.
1554 * Finds a source with the given user data for the callback. If
1555 * multiple sources exist with the same user data, the first
1556 * one found will be returned.
1558 * Return value: the source, if one was found, otherwise %NULL
1561 g_main_context_find_source_by_user_data (GMainContext *context,
1566 if (context == NULL)
1567 context = g_main_context_default ();
1569 LOCK_CONTEXT (context);
1571 source = context->source_list;
1574 if (!SOURCE_DESTROYED (source) &&
1575 source->callback_funcs)
1577 GSourceFunc callback;
1578 gpointer callback_data = NULL;
1580 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1582 if (callback_data == user_data)
1585 source = source->next;
1588 UNLOCK_CONTEXT (context);
1595 * @tag: the id of the source to remove.
1597 * Removes the source with the given id from the default main context. The id of
1598 * a #GSource is given by g_source_get_id(), or will be returned by the
1599 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1600 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1601 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1603 * See also g_source_destroy().
1605 * Return value: %TRUE if the source was found and removed.
1608 g_source_remove (guint tag)
1612 g_return_val_if_fail (tag > 0, FALSE);
1614 source = g_main_context_find_source_by_id (NULL, tag);
1616 g_source_destroy (source);
1618 return source != NULL;
1622 * g_source_remove_by_user_data:
1623 * @user_data: the user_data for the callback.
1625 * Removes a source from the default main loop context given the user
1626 * data for the callback. If multiple sources exist with the same user
1627 * data, only one will be destroyed.
1629 * Return value: %TRUE if a source was found and removed.
1632 g_source_remove_by_user_data (gpointer user_data)
1636 source = g_main_context_find_source_by_user_data (NULL, user_data);
1639 g_source_destroy (source);
1647 * g_source_remove_by_funcs_user_data:
1648 * @funcs: The @source_funcs passed to g_source_new()
1649 * @user_data: the user data for the callback
1651 * Removes a source from the default main loop context given the
1652 * source functions and user data. If multiple sources exist with the
1653 * same source functions and user data, only one will be destroyed.
1655 * Return value: %TRUE if a source was found and removed.
1658 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1663 g_return_val_if_fail (funcs != NULL, FALSE);
1665 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1668 g_source_destroy (source);
1676 * g_get_current_time:
1677 * @result: #GTimeVal structure in which to store current time.
1679 * Equivalent to the UNIX gettimeofday() function, but portable.
1682 g_get_current_time (GTimeVal *result)
1687 g_return_if_fail (result != NULL);
1689 /*this is required on alpha, there the timeval structs are int's
1690 not longs and a cast only would fail horribly*/
1691 gettimeofday (&r, NULL);
1692 result->tv_sec = r.tv_sec;
1693 result->tv_usec = r.tv_usec;
1695 /* Avoid calling time() except for the first time.
1696 * GetTickCount() should be pretty fast and low-level?
1697 * I could also use ftime() but it seems unnecessarily overheady.
1699 static DWORD start_tick = 0;
1700 static time_t start_time;
1703 g_return_if_fail (result != NULL);
1705 if (start_tick == 0)
1707 start_tick = GetTickCount ();
1711 tick = GetTickCount ();
1713 result->tv_sec = (tick - start_tick) / 1000 + start_time;
1714 result->tv_usec = ((tick - start_tick) % 1000) * 1000;
1718 /* Running the main loop */
1721 get_depth_pointer (void)
1723 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
1724 gint *depth_pointer = g_static_private_get (&depth_private);
1727 depth_pointer = g_new (gint, 1);
1729 g_static_private_set (&depth_private, depth_pointer, g_free);
1732 return depth_pointer;
1738 * Return value: The main loop recursion level in the current thread
1740 * Returns the depth of the stack of calls to
1741 * g_main_context_dispatch() on any #GMainContext in the current thread.
1742 * That is, when called from the toplevel, it gives 0. When
1743 * called from within a callback from g_main_context_iteration()
1744 * (or g_main_loop_run(), etc.) it returns 1. When called from within
1745 * a callback to a recursive call to g_main_context_iterate(),
1746 * it returns 2. And so forth.
1748 * This function is useful in a situation like the following:
1749 * Imagine an extremely simple "garbage collected" system.
1752 * static GList *free_list;
1755 * allocate_memory (gsize size)
1757 * gpointer result = g_malloc (size);
1758 * free_list = g_list_prepend (free_list, result);
1763 * free_allocated_memory (void)
1766 * for (l = free_list; l; l = l->next);
1768 * g_list_free (free_list);
1776 * g_main_context_iteration (NULL, TRUE);
1777 * free_allocated_memory();
1781 * This works from an application, however, if you want to do the same
1782 * thing from a library, it gets more difficult, since you no longer
1783 * control the main loop. You might think you can simply use an idle
1784 * function to make the call to free_allocated_memory(), but that
1785 * doesn't work, since the idle function could be called from a
1786 * recursive callback. This can be fixed by using g_main_depth()
1790 * allocate_memory (gsize size)
1792 * FreeListBlock *block = g_new (FreeListBlock, 1);\
1793 * block->mem = g_malloc (size);
1794 * block->depth = g_main_depth ();
1795 * free_list = g_list_prepend (free_list, block);
1796 * return block->mem;
1800 * free_allocated_memory (void)
1804 * int depth = g_main_depth ();
1805 * for (l = free_list; l; );
1807 * GList *next = l->next;
1808 * FreeListBlock *block = l->data;
1809 * if (block->depth > depth)
1811 * g_free (block->mem);
1813 * free_list = g_list_delete_link (free_list, l);
1821 * There is a temptation to use g_main_depth() to solve
1822 * problems with reentrancy. For instance, while waiting for data
1823 * to be received from the network in response to a menu item,
1824 * the menu item might be selected again. It might seem that
1825 * one could make the menu item's callback return immediately
1826 * and do nothing if g_main_depth() returns a value greater than 1.
1827 * However, this should be avoided since the user then sees selecting
1828 * the menu item do nothing. Furthermore, you'll find yourself adding
1829 * these checks all over your code, since there are doubtless many,
1830 * many things that the user could do. Instead, you can use the
1831 * following techniques:
1836 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
1837 * the user from interacting with elements while the main
1838 * loop is recursing.
1843 * Avoid main loop recursion in situations where you can't handle
1844 * arbitrary callbacks. Instead, structure your code so that you
1845 * simply return to the main loop and then get called again when
1846 * there is more work to do.
1854 gint *depth = get_depth_pointer ();
1858 /* Temporarily remove all this source's file descriptors from the
1859 * poll(), so that if data comes available for one of the file descriptors
1860 * we don't continually spin in the poll()
1862 /* HOLDS: source->context's lock */
1864 block_source (GSource *source)
1868 g_return_if_fail (!SOURCE_BLOCKED (source));
1870 tmp_list = source->poll_fds;
1873 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
1874 tmp_list = tmp_list->next;
1878 /* HOLDS: source->context's lock */
1880 unblock_source (GSource *source)
1884 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
1885 g_return_if_fail (!SOURCE_DESTROYED (source));
1887 tmp_list = source->poll_fds;
1890 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
1891 tmp_list = tmp_list->next;
1895 /* HOLDS: context's lock */
1897 g_main_dispatch (GMainContext *context)
1899 gint *depth = get_depth_pointer ();
1902 for (i = 0; i < context->pending_dispatches->len; i++)
1904 GSource *source = context->pending_dispatches->pdata[i];
1906 context->pending_dispatches->pdata[i] = NULL;
1909 source->flags &= ~G_SOURCE_READY;
1911 if (!SOURCE_DESTROYED (source))
1913 gboolean was_in_call;
1914 gpointer user_data = NULL;
1915 GSourceFunc callback = NULL;
1916 GSourceCallbackFuncs *cb_funcs;
1918 gboolean need_destroy;
1920 gboolean (*dispatch) (GSource *,
1924 dispatch = source->source_funcs->dispatch;
1925 cb_funcs = source->callback_funcs;
1926 cb_data = source->callback_data;
1929 cb_funcs->ref (cb_data);
1931 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
1932 block_source (source);
1934 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
1935 source->flags |= G_HOOK_FLAG_IN_CALL;
1938 cb_funcs->get (cb_data, source, &callback, &user_data);
1940 UNLOCK_CONTEXT (context);
1943 need_destroy = ! dispatch (source,
1948 LOCK_CONTEXT (context);
1951 cb_funcs->unref (cb_data);
1954 source->flags &= ~G_HOOK_FLAG_IN_CALL;
1956 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
1957 !SOURCE_DESTROYED (source))
1958 unblock_source (source);
1960 /* Note: this depends on the fact that we can't switch
1961 * sources from one main context to another
1963 if (need_destroy && !SOURCE_DESTROYED (source))
1965 g_assert (source->context == context);
1966 g_source_destroy_internal (source, context, TRUE);
1970 SOURCE_UNREF (source, context);
1973 g_ptr_array_set_size (context->pending_dispatches, 0);
1976 /* Holds context's lock */
1977 static inline GSource *
1978 next_valid_source (GMainContext *context,
1981 GSource *new_source = source ? source->next : context->source_list;
1985 if (!SOURCE_DESTROYED (new_source))
1987 new_source->ref_count++;
1991 new_source = new_source->next;
1995 SOURCE_UNREF (source, context);
2001 * g_main_context_acquire:
2002 * @context: a #GMainContext
2004 * Tries to become the owner of the specified context.
2005 * If some other context is the owner of the context,
2006 * returns %FALSE immediately. Ownership is properly
2007 * recursive: the owner can require ownership again
2008 * and will release ownership when g_main_context_release()
2009 * is called as many times as g_main_context_acquire().
2011 * You must be the owner of a context before you
2012 * can call g_main_context_prepare(), g_main_context_query(),
2013 * g_main_context_check(), g_main_context_dispatch().
2015 * Return value: %TRUE if the operation succeeded, and
2016 * this thread is now the owner of @context.
2019 g_main_context_acquire (GMainContext *context)
2021 #ifdef G_THREADS_ENABLED
2022 gboolean result = FALSE;
2023 GThread *self = G_THREAD_SELF;
2025 if (context == NULL)
2026 context = g_main_context_default ();
2028 LOCK_CONTEXT (context);
2030 if (!context->owner)
2032 context->owner = self;
2033 g_assert (context->owner_count == 0);
2036 if (context->owner == self)
2038 context->owner_count++;
2042 UNLOCK_CONTEXT (context);
2045 #else /* !G_THREADS_ENABLED */
2047 #endif /* G_THREADS_ENABLED */
2051 * g_main_context_release:
2052 * @context: a #GMainContext
2054 * Releases ownership of a context previously acquired by this thread
2055 * with g_main_context_acquire(). If the context was acquired multiple
2056 * times, the only release ownership when g_main_context_release()
2057 * is called as many times as it was acquired.
2060 g_main_context_release (GMainContext *context)
2062 #ifdef G_THREADS_ENABLED
2063 if (context == NULL)
2064 context = g_main_context_default ();
2066 LOCK_CONTEXT (context);
2068 context->owner_count--;
2069 if (context->owner_count == 0)
2071 context->owner = NULL;
2073 if (context->waiters)
2075 GMainWaiter *waiter = context->waiters->data;
2076 gboolean loop_internal_waiter =
2077 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
2078 context->waiters = g_slist_delete_link (context->waiters,
2080 if (!loop_internal_waiter)
2081 g_mutex_lock (waiter->mutex);
2083 g_cond_signal (waiter->cond);
2085 if (!loop_internal_waiter)
2086 g_mutex_unlock (waiter->mutex);
2090 UNLOCK_CONTEXT (context);
2091 #endif /* G_THREADS_ENABLED */
2095 * g_main_context_wait:
2096 * @context: a #GMainContext
2097 * @cond: a condition variable
2098 * @mutex: a mutex, currently held
2100 * Tries to become the owner of the specified context,
2101 * as with g_main_context_acquire(). But if another thread
2102 * is the owner, atomically drop @mutex and wait on @cond until
2103 * that owner releases ownership or until @cond is signaled, then
2104 * try again (once) to become the owner.
2106 * Return value: %TRUE if the operation succeeded, and
2107 * this thread is now the owner of @context.
2110 g_main_context_wait (GMainContext *context,
2114 #ifdef G_THREADS_ENABLED
2115 gboolean result = FALSE;
2116 GThread *self = G_THREAD_SELF;
2117 gboolean loop_internal_waiter;
2119 if (context == NULL)
2120 context = g_main_context_default ();
2122 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2124 if (!loop_internal_waiter)
2125 LOCK_CONTEXT (context);
2127 if (context->owner && context->owner != self)
2132 waiter.mutex = mutex;
2134 context->waiters = g_slist_append (context->waiters, &waiter);
2136 if (!loop_internal_waiter)
2137 UNLOCK_CONTEXT (context);
2138 g_cond_wait (cond, mutex);
2139 if (!loop_internal_waiter)
2140 LOCK_CONTEXT (context);
2142 context->waiters = g_slist_remove (context->waiters, &waiter);
2145 if (!context->owner)
2147 context->owner = self;
2148 g_assert (context->owner_count == 0);
2151 if (context->owner == self)
2153 context->owner_count++;
2157 if (!loop_internal_waiter)
2158 UNLOCK_CONTEXT (context);
2161 #else /* !G_THREADS_ENABLED */
2163 #endif /* G_THREADS_ENABLED */
2167 * g_main_context_prepare:
2168 * @context: a #GMainContext
2169 * @priority: location to store priority of highest priority
2170 * source already ready.
2172 * Prepares to poll sources within a main loop. The resulting information
2173 * for polling is determined by calling g_main_context_query ().
2175 * Return value: %TRUE if some source is ready to be dispatched
2179 g_main_context_prepare (GMainContext *context,
2184 gint current_priority = G_MAXINT;
2187 if (context == NULL)
2188 context = g_main_context_default ();
2190 LOCK_CONTEXT (context);
2192 context->time_is_current = FALSE;
2194 if (context->in_check_or_prepare)
2196 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2197 "prepare() member.");
2198 UNLOCK_CONTEXT (context);
2202 #ifdef G_THREADS_ENABLED
2203 if (context->poll_waiting)
2205 g_warning("g_main_context_prepare(): main loop already active in another thread");
2206 UNLOCK_CONTEXT (context);
2210 context->poll_waiting = TRUE;
2211 #endif /* G_THREADS_ENABLED */
2214 /* If recursing, finish up current dispatch, before starting over */
2215 if (context->pending_dispatches)
2218 g_main_dispatch (context, ¤t_time);
2220 UNLOCK_CONTEXT (context);
2225 /* If recursing, clear list of pending dispatches */
2227 for (i = 0; i < context->pending_dispatches->len; i++)
2229 if (context->pending_dispatches->pdata[i])
2230 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2232 g_ptr_array_set_size (context->pending_dispatches, 0);
2234 /* Prepare all sources */
2236 context->timeout = -1;
2238 source = next_valid_source (context, NULL);
2241 gint source_timeout = -1;
2243 if ((n_ready > 0) && (source->priority > current_priority))
2245 SOURCE_UNREF (source, context);
2248 if (SOURCE_BLOCKED (source))
2251 if (!(source->flags & G_SOURCE_READY))
2254 gboolean (*prepare) (GSource *source,
2257 prepare = source->source_funcs->prepare;
2258 context->in_check_or_prepare++;
2259 UNLOCK_CONTEXT (context);
2261 result = (*prepare) (source, &source_timeout);
2263 LOCK_CONTEXT (context);
2264 context->in_check_or_prepare--;
2267 source->flags |= G_SOURCE_READY;
2270 if (source->flags & G_SOURCE_READY)
2273 current_priority = source->priority;
2274 context->timeout = 0;
2277 if (source_timeout >= 0)
2279 if (context->timeout < 0)
2280 context->timeout = source_timeout;
2282 context->timeout = MIN (context->timeout, source_timeout);
2286 source = next_valid_source (context, source);
2289 UNLOCK_CONTEXT (context);
2292 *priority = current_priority;
2294 return (n_ready > 0);
2298 * g_main_context_query:
2299 * @context: a #GMainContext
2300 * @max_priority: maximum priority source to check
2301 * @timeout_: location to store timeout to be used in polling
2302 * @fds: location to store #GPollFD records that need to be polled.
2303 * @n_fds: length of @fds.
2305 * Determines information necessary to poll this main loop.
2307 * Return value: the number of records actually stored in @fds,
2308 * or, if more than @n_fds records need to be stored, the number
2309 * of records that need to be stored.
2312 g_main_context_query (GMainContext *context,
2321 LOCK_CONTEXT (context);
2323 pollrec = context->poll_records;
2325 while (pollrec && max_priority >= pollrec->priority)
2327 if (pollrec->fd->events)
2331 fds[n_poll].fd = pollrec->fd->fd;
2332 /* In direct contradiction to the Unix98 spec, IRIX runs into
2333 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2334 * flags in the events field of the pollfd while it should
2335 * just ignoring them. So we mask them out here.
2337 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2338 fds[n_poll].revents = 0;
2343 pollrec = pollrec->next;
2346 #ifdef G_THREADS_ENABLED
2347 context->poll_changed = FALSE;
2352 *timeout = context->timeout;
2354 context->time_is_current = FALSE;
2357 UNLOCK_CONTEXT (context);
2363 * g_main_context_check:
2364 * @context: a #GMainContext
2365 * @max_priority: the maximum numerical priority of sources to check
2366 * @fds: array of #GPollFD's that was passed to the last call to
2367 * g_main_context_query()
2368 * @n_fds: return value of g_main_context_query()
2370 * Passes the results of polling back to the main loop.
2372 * Return value: %TRUE if some sources are ready to be dispatched.
2375 g_main_context_check (GMainContext *context,
2385 LOCK_CONTEXT (context);
2387 if (context->in_check_or_prepare)
2389 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2390 "prepare() member.");
2391 UNLOCK_CONTEXT (context);
2395 #ifdef G_THREADS_ENABLED
2396 if (!context->poll_waiting)
2400 read (context->wake_up_pipe[0], &a, 1);
2404 context->poll_waiting = FALSE;
2406 /* If the set of poll file descriptors changed, bail out
2407 * and let the main loop rerun
2409 if (context->poll_changed)
2411 UNLOCK_CONTEXT (context);
2414 #endif /* G_THREADS_ENABLED */
2416 pollrec = context->poll_records;
2420 if (pollrec->fd->events)
2422 pollrec->fd->revents = fds[i].revents;
2425 pollrec = pollrec->next;
2428 source = next_valid_source (context, NULL);
2431 if ((n_ready > 0) && (source->priority > max_priority))
2433 SOURCE_UNREF (source, context);
2436 if (SOURCE_BLOCKED (source))
2439 if (!(source->flags & G_SOURCE_READY))
2442 gboolean (*check) (GSource *source);
2444 check = source->source_funcs->check;
2446 context->in_check_or_prepare++;
2447 UNLOCK_CONTEXT (context);
2449 result = (*check) (source);
2451 LOCK_CONTEXT (context);
2452 context->in_check_or_prepare--;
2455 source->flags |= G_SOURCE_READY;
2458 if (source->flags & G_SOURCE_READY)
2460 source->ref_count++;
2461 g_ptr_array_add (context->pending_dispatches, source);
2465 /* never dispatch sources with less priority than the first
2466 * one we choose to dispatch
2468 max_priority = source->priority;
2472 source = next_valid_source (context, source);
2475 UNLOCK_CONTEXT (context);
2481 * g_main_context_dispatch:
2482 * @context: a #GMainContext
2484 * Dispatches all pending sources.
2487 g_main_context_dispatch (GMainContext *context)
2489 LOCK_CONTEXT (context);
2491 if (context->pending_dispatches->len > 0)
2493 g_main_dispatch (context);
2496 UNLOCK_CONTEXT (context);
2499 /* HOLDS context lock */
2501 g_main_context_iterate (GMainContext *context,
2508 gboolean some_ready;
2509 gint nfds, allocated_nfds;
2510 GPollFD *fds = NULL;
2512 UNLOCK_CONTEXT (context);
2514 #ifdef G_THREADS_ENABLED
2515 if (!g_main_context_acquire (context))
2517 gboolean got_ownership;
2519 g_return_val_if_fail (g_thread_supported (), FALSE);
2524 LOCK_CONTEXT (context);
2527 context->cond = g_cond_new ();
2529 got_ownership = g_main_context_wait (context,
2531 g_static_mutex_get_mutex (&context->mutex));
2535 UNLOCK_CONTEXT (context);
2540 LOCK_CONTEXT (context);
2541 #endif /* G_THREADS_ENABLED */
2543 if (!context->cached_poll_array)
2545 context->cached_poll_array_size = context->n_poll_records;
2546 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2549 allocated_nfds = context->cached_poll_array_size;
2550 fds = context->cached_poll_array;
2552 UNLOCK_CONTEXT (context);
2554 g_main_context_prepare (context, &max_priority);
2556 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
2557 allocated_nfds)) > allocated_nfds)
2559 LOCK_CONTEXT (context);
2561 context->cached_poll_array_size = allocated_nfds = nfds;
2562 context->cached_poll_array = fds = g_new (GPollFD, nfds);
2563 UNLOCK_CONTEXT (context);
2569 g_main_context_poll (context, timeout, max_priority, fds, nfds);
2571 some_ready = g_main_context_check (context, max_priority, fds, nfds);
2574 g_main_context_dispatch (context);
2576 #ifdef G_THREADS_ENABLED
2577 g_main_context_release (context);
2578 #endif /* G_THREADS_ENABLED */
2580 LOCK_CONTEXT (context);
2586 * g_main_context_pending:
2587 * @context: a #GMainContext (if %NULL, the default context will be used)
2589 * Checks if any sources have pending events for the given context.
2591 * Return value: %TRUE if events are pending.
2594 g_main_context_pending (GMainContext *context)
2599 context = g_main_context_default();
2601 LOCK_CONTEXT (context);
2602 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
2603 UNLOCK_CONTEXT (context);
2609 * g_main_context_iteration:
2610 * @context: a #GMainContext (if %NULL, the default context will be used)
2611 * @may_block: whether the call may block.
2613 * Runs a single iteration for the given main loop. This involves
2614 * checking to see if any event sources are ready to be processed,
2615 * then if no events sources are ready and @may_block is %TRUE, waiting
2616 * for a source to become ready, then dispatching the highest priority
2617 * events sources that are ready. Note that even when @may_block is %TRUE,
2618 * it is still possible for g_main_context_iteration() to return
2619 * %FALSE, since the the wait may be interrupted for other
2620 * reasons than an event source becoming ready.
2622 * Return value: %TRUE if events were dispatched.
2625 g_main_context_iteration (GMainContext *context, gboolean may_block)
2630 context = g_main_context_default();
2632 LOCK_CONTEXT (context);
2633 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
2634 UNLOCK_CONTEXT (context);
2641 * @context: a #GMainContext (if %NULL, the default context will be used).
2642 * @is_running: set to %TRUE to indicate that the loop is running. This
2643 * is not very important since calling g_main_loop_run() will set this to
2646 * Creates a new #GMainLoop structure.
2648 * Return value: a new #GMainLoop.
2651 g_main_loop_new (GMainContext *context,
2652 gboolean is_running)
2657 context = g_main_context_default();
2659 g_main_context_ref (context);
2661 loop = g_new0 (GMainLoop, 1);
2662 loop->context = context;
2663 loop->is_running = is_running != FALSE;
2664 loop->ref_count = 1;
2671 * @loop: a #GMainLoop
2673 * Increases the reference count on a #GMainLoop object by one.
2675 * Return value: @loop
2678 g_main_loop_ref (GMainLoop *loop)
2680 g_return_val_if_fail (loop != NULL, NULL);
2681 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2683 g_atomic_int_inc (&loop->ref_count);
2689 * g_main_loop_unref:
2690 * @loop: a #GMainLoop
2692 * Decreases the reference count on a #GMainLoop object by one. If
2693 * the result is zero, free the loop and free all associated memory.
2696 g_main_loop_unref (GMainLoop *loop)
2698 g_return_if_fail (loop != NULL);
2699 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2701 if (!g_atomic_int_dec_and_test (&loop->ref_count))
2704 g_main_context_unref (loop->context);
2710 * @loop: a #GMainLoop
2712 * Runs a main loop until g_main_loop_quit() is called on the loop.
2713 * If this is called for the thread of the loop's #GMainContext,
2714 * it will process events from the loop, otherwise it will
2718 g_main_loop_run (GMainLoop *loop)
2720 GThread *self = G_THREAD_SELF;
2722 g_return_if_fail (loop != NULL);
2723 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2725 #ifdef G_THREADS_ENABLED
2726 if (!g_main_context_acquire (loop->context))
2728 gboolean got_ownership = FALSE;
2730 /* Another thread owns this context */
2731 if (!g_thread_supported ())
2733 g_warning ("g_main_loop_run() was called from second thread but "
2734 "g_thread_init() was never called.");
2738 LOCK_CONTEXT (loop->context);
2740 g_atomic_int_inc (&loop->ref_count);
2742 if (!loop->is_running)
2743 loop->is_running = TRUE;
2745 if (!loop->context->cond)
2746 loop->context->cond = g_cond_new ();
2748 while (loop->is_running && !got_ownership)
2749 got_ownership = g_main_context_wait (loop->context,
2750 loop->context->cond,
2751 g_static_mutex_get_mutex (&loop->context->mutex));
2753 if (!loop->is_running)
2755 UNLOCK_CONTEXT (loop->context);
2757 g_main_context_release (loop->context);
2758 g_main_loop_unref (loop);
2762 g_assert (got_ownership);
2765 LOCK_CONTEXT (loop->context);
2766 #endif /* G_THREADS_ENABLED */
2768 if (loop->context->in_check_or_prepare)
2770 g_warning ("g_main_loop_run(): called recursively from within a source's "
2771 "check() or prepare() member, iteration not possible.");
2775 g_atomic_int_inc (&loop->ref_count);
2776 loop->is_running = TRUE;
2777 while (loop->is_running)
2778 g_main_context_iterate (loop->context, TRUE, TRUE, self);
2780 UNLOCK_CONTEXT (loop->context);
2782 #ifdef G_THREADS_ENABLED
2783 g_main_context_release (loop->context);
2784 #endif /* G_THREADS_ENABLED */
2786 g_main_loop_unref (loop);
2791 * @loop: a #GMainLoop
2793 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
2794 * for the loop will return.
2797 g_main_loop_quit (GMainLoop *loop)
2799 g_return_if_fail (loop != NULL);
2800 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2802 LOCK_CONTEXT (loop->context);
2803 loop->is_running = FALSE;
2804 g_main_context_wakeup_unlocked (loop->context);
2806 #ifdef G_THREADS_ENABLED
2807 if (loop->context->cond)
2808 g_cond_broadcast (loop->context->cond);
2809 #endif /* G_THREADS_ENABLED */
2811 UNLOCK_CONTEXT (loop->context);
2815 * g_main_loop_is_running:
2816 * @loop: a #GMainLoop.
2818 * Checks to see if the main loop is currently being run via g_main_loop_run().
2820 * Return value: %TRUE if the mainloop is currently being run.
2823 g_main_loop_is_running (GMainLoop *loop)
2825 g_return_val_if_fail (loop != NULL, FALSE);
2826 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
2828 return loop->is_running;
2832 * g_main_loop_get_context:
2833 * @loop: a #GMainLoop.
2835 * Returns the #GMainContext of @loop.
2837 * Return value: the #GMainContext of @loop
2840 g_main_loop_get_context (GMainLoop *loop)
2842 g_return_val_if_fail (loop != NULL, NULL);
2843 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2845 return loop->context;
2848 /* HOLDS: context's lock */
2850 g_main_context_poll (GMainContext *context,
2856 #ifdef G_MAIN_POLL_DEBUG
2862 GPollFunc poll_func;
2864 if (n_fds || timeout != 0)
2866 #ifdef G_MAIN_POLL_DEBUG
2867 g_print ("g_main_poll(%d) timeout: %d\n", n_fds, timeout);
2868 poll_timer = g_timer_new ();
2871 LOCK_CONTEXT (context);
2873 poll_func = context->poll_func;
2875 UNLOCK_CONTEXT (context);
2876 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
2879 g_warning ("poll(2) failed due to: %s.",
2880 g_strerror (errno));
2882 /* If g_poll () returns -1, it has already called g_warning() */
2886 #ifdef G_MAIN_POLL_DEBUG
2887 LOCK_CONTEXT (context);
2889 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
2892 g_timer_elapsed (poll_timer, NULL));
2893 g_timer_destroy (poll_timer);
2894 pollrec = context->poll_records;
2898 if (pollrec->fd->events)
2902 g_print (" [%d:", fds[i].fd);
2903 if (fds[i].revents & G_IO_IN)
2905 if (fds[i].revents & G_IO_OUT)
2907 if (fds[i].revents & G_IO_PRI)
2909 if (fds[i].revents & G_IO_ERR)
2911 if (fds[i].revents & G_IO_HUP)
2913 if (fds[i].revents & G_IO_NVAL)
2919 pollrec = pollrec->next;
2923 UNLOCK_CONTEXT (context);
2925 } /* if (n_fds || timeout != 0) */
2929 * g_main_context_add_poll:
2930 * @context: a #GMainContext (or %NULL for the default context)
2931 * @fd: a #GPollFD structure holding information about a file
2932 * descriptor to watch.
2933 * @priority: the priority for this file descriptor which should be
2934 * the same as the priority used for g_source_attach() to ensure that the
2935 * file descriptor is polled whenever the results may be needed.
2937 * Adds a file descriptor to the set of file descriptors polled for
2938 * this context. This will very seldomly be used directly. Instead
2939 * a typical event source will use g_source_add_poll() instead.
2942 g_main_context_add_poll (GMainContext *context,
2947 context = g_main_context_default ();
2949 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
2950 g_return_if_fail (fd);
2952 LOCK_CONTEXT (context);
2953 g_main_context_add_poll_unlocked (context, priority, fd);
2954 UNLOCK_CONTEXT (context);
2957 /* HOLDS: main_loop_lock */
2959 g_main_context_add_poll_unlocked (GMainContext *context,
2963 GPollRec *lastrec, *pollrec, *newrec;
2965 if (!context->poll_chunk)
2966 context->poll_chunk = g_mem_chunk_create (GPollRec, 32, G_ALLOC_ONLY);
2968 if (context->poll_free_list)
2970 newrec = context->poll_free_list;
2971 context->poll_free_list = newrec->next;
2974 newrec = g_chunk_new (GPollRec, context->poll_chunk);
2976 /* This file descriptor may be checked before we ever poll */
2979 newrec->priority = priority;
2982 pollrec = context->poll_records;
2983 while (pollrec && priority >= pollrec->priority)
2986 pollrec = pollrec->next;
2990 lastrec->next = newrec;
2992 context->poll_records = newrec;
2994 newrec->next = pollrec;
2996 context->n_poll_records++;
2998 #ifdef G_THREADS_ENABLED
2999 context->poll_changed = TRUE;
3001 /* Now wake up the main loop if it is waiting in the poll() */
3002 g_main_context_wakeup_unlocked (context);
3007 * g_main_context_remove_poll:
3008 * @context:a #GMainContext
3009 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3011 * Removes file descriptor from the set of file descriptors to be
3012 * polled for a particular context.
3015 g_main_context_remove_poll (GMainContext *context,
3019 context = g_main_context_default ();
3021 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3022 g_return_if_fail (fd);
3024 LOCK_CONTEXT (context);
3025 g_main_context_remove_poll_unlocked (context, fd);
3026 UNLOCK_CONTEXT (context);
3030 g_main_context_remove_poll_unlocked (GMainContext *context,
3033 GPollRec *pollrec, *lastrec;
3036 pollrec = context->poll_records;
3040 if (pollrec->fd == fd)
3042 if (lastrec != NULL)
3043 lastrec->next = pollrec->next;
3045 context->poll_records = pollrec->next;
3047 #ifdef ENABLE_GC_FRIENDLY
3049 #endif /* ENABLE_GC_FRIENDLY */
3051 pollrec->next = context->poll_free_list;
3052 context->poll_free_list = pollrec;
3054 context->n_poll_records--;
3058 pollrec = pollrec->next;
3061 #ifdef G_THREADS_ENABLED
3062 context->poll_changed = TRUE;
3064 /* Now wake up the main loop if it is waiting in the poll() */
3065 g_main_context_wakeup_unlocked (context);
3070 * g_source_get_current_time:
3071 * @source: a #GSource
3072 * @timeval: #GTimeVal structure in which to store current time.
3074 * Gets the "current time" to be used when checking
3075 * this source. The advantage of calling this function over
3076 * calling g_get_current_time() directly is that when
3077 * checking multiple sources, GLib can cache a single value
3078 * instead of having to repeatedly get the system time.
3081 g_source_get_current_time (GSource *source,
3084 GMainContext *context;
3086 g_return_if_fail (source->context != NULL);
3088 context = source->context;
3090 LOCK_CONTEXT (context);
3092 if (!context->time_is_current)
3094 g_get_current_time (&context->current_time);
3095 context->time_is_current = TRUE;
3098 *timeval = context->current_time;
3100 UNLOCK_CONTEXT (context);
3104 * g_main_context_set_poll_func:
3105 * @context: a #GMainContext
3106 * @func: the function to call to poll all file descriptors
3108 * Sets the function to use to handle polling of file descriptors. It
3109 * will be used instead of the poll() system call
3110 * (or GLib's replacement function, which is used where
3111 * poll() isn't available).
3113 * This function could possibly be used to integrate the GLib event
3114 * loop with an external event loop.
3117 g_main_context_set_poll_func (GMainContext *context,
3121 context = g_main_context_default ();
3123 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3125 LOCK_CONTEXT (context);
3128 context->poll_func = func;
3132 context->poll_func = (GPollFunc) poll;
3134 context->poll_func = (GPollFunc) g_poll;
3138 UNLOCK_CONTEXT (context);
3142 * g_main_context_get_poll_func:
3143 * @context: a #GMainContext
3145 * Gets the poll function set by g_main_context_set_poll_func().
3147 * Return value: the poll function
3150 g_main_context_get_poll_func (GMainContext *context)
3155 context = g_main_context_default ();
3157 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3159 LOCK_CONTEXT (context);
3160 result = context->poll_func;
3161 UNLOCK_CONTEXT (context);
3166 /* HOLDS: context's lock */
3167 /* Wake the main loop up from a poll() */
3169 g_main_context_wakeup_unlocked (GMainContext *context)
3171 #ifdef G_THREADS_ENABLED
3172 if (g_thread_supported() && context->poll_waiting)
3174 context->poll_waiting = FALSE;
3176 write (context->wake_up_pipe[1], "A", 1);
3178 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
3185 * g_main_context_wakeup:
3186 * @context: a #GMainContext
3188 * If @context is currently waiting in a poll(), interrupt
3189 * the poll(), and continue the iteration process.
3192 g_main_context_wakeup (GMainContext *context)
3195 context = g_main_context_default ();
3197 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3199 LOCK_CONTEXT (context);
3200 g_main_context_wakeup_unlocked (context);
3201 UNLOCK_CONTEXT (context);
3207 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3208 GTimeVal *current_time)
3210 guint seconds = timeout_source->interval / 1000;
3211 guint msecs = timeout_source->interval - seconds * 1000;
3213 timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
3214 timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
3215 if (timeout_source->expiration.tv_usec >= 1000000)
3217 timeout_source->expiration.tv_usec -= 1000000;
3218 timeout_source->expiration.tv_sec++;
3223 g_timeout_prepare (GSource *source,
3228 GTimeVal current_time;
3230 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3232 g_source_get_current_time (source, ¤t_time);
3234 sec = timeout_source->expiration.tv_sec - current_time.tv_sec;
3235 msec = (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000;
3237 /* We do the following in a rather convoluted fashion to deal with
3238 * the fact that we don't have an integral type big enough to hold
3239 * the difference of two timevals in millseconds.
3241 if (sec < 0 || (sec == 0 && msec < 0))
3245 glong interval_sec = timeout_source->interval / 1000;
3246 glong interval_msec = timeout_source->interval % 1000;
3254 if (sec > interval_sec ||
3255 (sec == interval_sec && msec > interval_msec))
3257 /* The system time has been set backwards, so we
3258 * reset the expiration time to now + timeout_source->interval;
3259 * this at least avoids hanging for long periods of time.
3261 g_timeout_set_expiration (timeout_source, ¤t_time);
3262 msec = MIN (G_MAXINT, timeout_source->interval);
3266 msec = MIN (G_MAXINT, (guint)msec + 1000 * (guint)sec);
3270 *timeout = (gint)msec;
3276 g_timeout_check (GSource *source)
3278 GTimeVal current_time;
3279 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3281 g_source_get_current_time (source, ¤t_time);
3283 return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
3284 ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
3285 (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
3289 g_timeout_dispatch (GSource *source,
3290 GSourceFunc callback,
3293 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3297 g_warning ("Timeout source dispatched without callback\n"
3298 "You must call g_source_set_callback().");
3302 if (callback (user_data))
3304 GTimeVal current_time;
3306 g_source_get_current_time (source, ¤t_time);
3307 g_timeout_set_expiration (timeout_source, ¤t_time);
3316 * g_timeout_source_new:
3317 * @interval: the timeout interval in milliseconds.
3319 * Creates a new timeout source.
3321 * The source will not initially be associated with any #GMainContext
3322 * and must be added to one with g_source_attach() before it will be
3325 * Return value: the newly-created timeout source
3328 g_timeout_source_new (guint interval)
3330 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3331 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3332 GTimeVal current_time;
3334 timeout_source->interval = interval;
3336 g_get_current_time (¤t_time);
3337 g_timeout_set_expiration (timeout_source, ¤t_time);
3343 * g_timeout_add_full:
3344 * @priority: the priority of the idle source. Typically this will be in the
3345 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3346 * @interval: the time between calls to the function, in milliseconds
3347 * (1/1000ths of a second)
3348 * @function: function to call
3349 * @data: data to pass to @function
3350 * @notify: function to call when the idle is removed, or %NULL
3352 * Sets a function to be called at regular intervals, with the given
3353 * priority. The function is called repeatedly until it returns
3354 * %FALSE, at which point the timeout is automatically destroyed and
3355 * the function will not be called again. The @notify function is
3356 * called when the timeout is destroyed. The first call to the
3357 * function will be at the end of the first @interval.
3359 * Note that timeout functions may be delayed, due to the processing of other
3360 * event sources. Thus they should not be relied on for precise timing.
3361 * After each call to the timeout function, the time of the next
3362 * timeout is recalculated based on the current time and the given interval
3363 * (it does not try to 'catch up' time lost in delays).
3365 * Return value: the id of event source.
3368 g_timeout_add_full (gint priority,
3370 GSourceFunc function,
3372 GDestroyNotify notify)
3377 g_return_val_if_fail (function != NULL, 0);
3379 source = g_timeout_source_new (interval);
3381 if (priority != G_PRIORITY_DEFAULT)
3382 g_source_set_priority (source, priority);
3384 g_source_set_callback (source, function, data, notify);
3385 id = g_source_attach (source, NULL);
3386 g_source_unref (source);
3393 * @interval: the time between calls to the function, in milliseconds
3394 * (1/1000ths of a second)
3395 * @function: function to call
3396 * @data: data to pass to @function
3398 * Sets a function to be called at regular intervals, with the default
3399 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
3400 * until it returns %FALSE, at which point the timeout is automatically
3401 * destroyed and the function will not be called again. The first call
3402 * to the function will be at the end of the first @interval.
3404 * Note that timeout functions may be delayed, due to the processing of other
3405 * event sources. Thus they should not be relied on for precise timing.
3406 * After each call to the timeout function, the time of the next
3407 * timeout is recalculated based on the current time and the given interval
3408 * (it does not try to 'catch up' time lost in delays).
3410 * Return value: the id of event source.
3413 g_timeout_add (guint32 interval,
3414 GSourceFunc function,
3417 return g_timeout_add_full (G_PRIORITY_DEFAULT,
3418 interval, function, data, NULL);
3421 /* Child watch functions */
3426 g_child_watch_prepare (GSource *source,
3435 g_child_watch_check (GSource *source)
3437 GChildWatchSource *child_watch_source;
3438 gboolean child_exited;
3440 child_watch_source = (GChildWatchSource *) source;
3442 child_exited = child_watch_source->poll.revents & G_IO_IN;
3449 * Note: We do _not_ check for the special value of STILL_ACTIVE
3450 * since we know that the process has exited and doing so runs into
3451 * problems if the child process "happens to return STILL_ACTIVE(259)"
3452 * as Microsoft's Platform SDK puts it.
3454 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
3456 gchar *emsg = g_win32_error_message (GetLastError ());
3457 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
3460 child_watch_source->child_status = -1;
3463 child_watch_source->child_status = child_status;
3466 return child_exited;
3469 #else /* G_OS_WIN32 */
3472 check_for_child_exited (GSource *source)
3474 GChildWatchSource *child_watch_source;
3477 /* protect against another SIGCHLD in the middle of this call */
3478 count = child_watch_count;
3480 child_watch_source = (GChildWatchSource *) source;
3482 if (child_watch_source->child_exited)
3485 if (child_watch_source->count < count)
3489 if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
3491 child_watch_source->child_status = child_status;
3492 child_watch_source->child_exited = TRUE;
3494 child_watch_source->count = count;
3497 return child_watch_source->child_exited;
3501 g_child_watch_prepare (GSource *source,
3504 GChildWatchSource *child_watch_source;
3507 child_watch_source = (GChildWatchSource *) source;
3509 return check_for_child_exited (source);
3514 g_child_watch_check (GSource *source)
3516 GChildWatchSource *child_watch_source;
3518 child_watch_source = (GChildWatchSource *) source;
3520 return check_for_child_exited (source);
3523 #endif /* G_OS_WIN32 */
3526 g_child_watch_dispatch (GSource *source,
3527 GSourceFunc callback,
3530 GChildWatchSource *child_watch_source;
3531 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
3533 child_watch_source = (GChildWatchSource *) source;
3537 g_warning ("Child watch source dispatched without callback\n"
3538 "You must call g_source_set_callback().");
3542 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
3544 /* We never keep a child watch source around as the child is gone */
3551 g_child_watch_signal_handler (int signum)
3553 child_watch_count ++;
3555 if (child_watch_init_state == CHILD_WATCH_INITIALIZED_THREADED)
3557 write (child_watch_wake_up_pipe[1], "B", 1);
3561 /* We count on the signal interrupting the poll in the same thread.
3567 g_child_watch_source_init_single (void)
3569 g_assert (! g_thread_supported());
3570 g_assert (child_watch_init_state == CHILD_WATCH_UNINITIALIZED);
3572 child_watch_init_state = CHILD_WATCH_INITIALIZED_SINGLE;
3574 signal (SIGCHLD, g_child_watch_signal_handler);
3578 child_watch_helper_thread (gpointer data)
3581 GPollFunc poll_func;
3584 poll_func = (GPollFunc)poll;
3589 fds.fd = child_watch_wake_up_pipe[0];
3590 fds.events = G_IO_IN;
3597 read (child_watch_wake_up_pipe[0], b, 20);
3599 /* We were woken up. Wake up all other contexts in all other threads */
3600 G_LOCK (main_context_list);
3601 for (list = main_context_list; list; list = list->next)
3603 GMainContext *context;
3605 context = list->data;
3606 if (g_atomic_int_get (&context->ref_count) > 0)
3607 /* Due to racing conditions we can find ref_count == 0, in
3608 * that case, however, the context is still not destroyed
3609 * and no poll can be active, otherwise the ref_count
3611 g_main_context_wakeup (context);
3613 G_UNLOCK (main_context_list);
3619 g_child_watch_source_init_multi_threaded (void)
3621 GError *error = NULL;
3623 g_assert (g_thread_supported());
3625 if (pipe (child_watch_wake_up_pipe) < 0)
3626 g_error ("Cannot create wake up pipe: %s\n", g_strerror (errno));
3627 fcntl (child_watch_wake_up_pipe[1], F_SETFL, O_NONBLOCK | fcntl (child_watch_wake_up_pipe[1], F_GETFL));
3629 /* We create a helper thread that polls on the wakeup pipe indefinitely */
3630 /* FIXME: Think this through for races */
3631 if (g_thread_create (child_watch_helper_thread, NULL, FALSE, &error) == NULL)
3632 g_error ("Cannot create a thread to monitor child exit status: %s\n", error->message);
3633 child_watch_init_state = CHILD_WATCH_INITIALIZED_THREADED;
3634 signal (SIGCHLD, g_child_watch_signal_handler);
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);