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 "gthreadprivate.h"
42 #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.
56 #if defined(_POLL_EMUL_H_) || defined(BROKEN_POLL)
60 #endif /* GLIB_HAVE_SYS_POLL_H */
63 #endif /* HAVE_UNISTD_H */
69 #endif /* G_OS_WIN32 */
72 #include <sys/socket.h>
74 #endif /* G_OS_BEOS */
85 typedef struct _GTimeoutSource GTimeoutSource;
86 typedef struct _GChildWatchSource GChildWatchSource;
87 typedef struct _GPollRec GPollRec;
88 typedef struct _GSourceCallback GSourceCallback;
92 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
93 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
96 #ifdef G_THREADS_ENABLED
97 typedef struct _GMainWaiter GMainWaiter;
106 typedef struct _GMainDispatch GMainDispatch;
108 struct _GMainDispatch
111 GSList *source; /* stack of current sources */
116 #ifdef G_THREADS_ENABLED
117 /* The following lock is used for both the list of sources
118 * and the list of poll records
129 GPtrArray *pending_dispatches;
130 gint timeout; /* Timeout for current iteration */
133 GSource *source_list;
134 gint in_check_or_prepare;
136 GPollRec *poll_records;
137 guint n_poll_records;
138 GPollFD *cached_poll_array;
139 guint cached_poll_array_size;
141 #ifdef G_THREADS_ENABLED
143 /* this pipe is used to wake up the main loop when a source is added.
145 gint wake_up_pipe[2];
146 #else /* G_OS_WIN32 */
147 HANDLE wake_up_semaphore;
148 #endif /* G_OS_WIN32 */
151 gboolean poll_waiting;
153 /* Flag indicating whether the set of fd's changed during a poll */
154 gboolean poll_changed;
155 #endif /* G_THREADS_ENABLED */
159 GTimeVal current_time;
160 gboolean time_is_current;
163 struct _GSourceCallback
168 GDestroyNotify notify;
173 GMainContext *context;
178 struct _GTimeoutSource
186 struct _GChildWatchSource
193 #else /* G_OS_WIN32 */
195 gboolean child_exited;
196 #endif /* G_OS_WIN32 */
206 #ifdef G_THREADS_ENABLED
207 #define LOCK_CONTEXT(context) g_static_mutex_lock (&context->mutex)
208 #define UNLOCK_CONTEXT(context) g_static_mutex_unlock (&context->mutex)
209 #define G_THREAD_SELF g_thread_self ()
211 #define LOCK_CONTEXT(context) (void)0
212 #define UNLOCK_CONTEXT(context) (void)0
213 #define G_THREAD_SELF NULL
216 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
217 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
218 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
220 #define SOURCE_UNREF(source, context) \
222 if ((source)->ref_count > 1) \
223 (source)->ref_count--; \
225 g_source_unref_internal ((source), (context), TRUE); \
229 /* Forward declarations */
231 static void g_source_unref_internal (GSource *source,
232 GMainContext *context,
234 static void g_source_destroy_internal (GSource *source,
235 GMainContext *context,
237 static void g_main_context_poll (GMainContext *context,
242 static void g_main_context_add_poll_unlocked (GMainContext *context,
245 static void g_main_context_remove_poll_unlocked (GMainContext *context,
247 static void g_main_context_wakeup_unlocked (GMainContext *context);
249 static gboolean g_timeout_prepare (GSource *source,
251 static gboolean g_timeout_check (GSource *source);
252 static gboolean g_timeout_dispatch (GSource *source,
253 GSourceFunc callback,
255 static gboolean g_child_watch_prepare (GSource *source,
257 static gboolean g_child_watch_check (GSource *source);
258 static gboolean g_child_watch_dispatch (GSource *source,
259 GSourceFunc callback,
261 static gboolean g_idle_prepare (GSource *source,
263 static gboolean g_idle_check (GSource *source);
264 static gboolean g_idle_dispatch (GSource *source,
265 GSourceFunc callback,
268 G_LOCK_DEFINE_STATIC (main_loop);
269 static GMainContext *default_main_context;
270 static GSList *main_contexts_without_pipe = NULL;
273 /* Child status monitoring code */
275 CHILD_WATCH_UNINITIALIZED,
276 CHILD_WATCH_INITIALIZED_SINGLE,
277 CHILD_WATCH_INITIALIZED_THREADED
279 static gint child_watch_init_state = CHILD_WATCH_UNINITIALIZED;
280 static gint child_watch_count = 1;
281 static gint child_watch_wake_up_pipe[2] = {0, 0};
282 #endif /* !G_OS_WIN32 */
283 G_LOCK_DEFINE_STATIC (main_context_list);
284 static GSList *main_context_list = NULL;
286 static gint timer_perturb = -1;
288 GSourceFuncs g_timeout_funcs =
296 GSourceFuncs g_child_watch_funcs =
298 g_child_watch_prepare,
300 g_child_watch_dispatch,
304 GSourceFuncs g_idle_funcs =
313 /* SunOS has poll, but doesn't provide a prototype. */
314 # if defined (sun) && !defined (__SVR4)
315 extern gint poll (GPollFD *ufds, guint nfsd, gint timeout);
317 #else /* !HAVE_POLL */
322 g_poll (GPollFD *fds,
326 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
327 gboolean poll_msgs = FALSE;
334 for (f = fds; f < &fds[nfds]; ++f)
337 if (f->fd == G_WIN32_MSG_HANDLE)
339 else if (nhandles == MAXIMUM_WAIT_OBJECTS)
341 g_warning (G_STRLOC ": Too many handles to wait for!\n");
346 #ifdef G_MAIN_POLL_DEBUG
347 g_print ("g_poll: waiting for %#x\n", f->fd);
349 handles[nhandles++] = (HANDLE) f->fd;
358 /* Waiting for messages, and maybe events
359 * -> First PeekMessage
361 #ifdef G_MAIN_POLL_DEBUG
362 g_print ("PeekMessage\n");
364 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
365 ready = WAIT_OBJECT_0 + nhandles;
370 /* Waiting just for messages */
371 if (timeout == INFINITE)
376 #ifdef G_MAIN_POLL_DEBUG
377 g_print ("WaitMessage\n");
381 gchar *emsg = g_win32_error_message (GetLastError ());
382 g_warning (G_STRLOC ": WaitMessage() failed: %s", emsg);
385 ready = WAIT_OBJECT_0 + nhandles;
387 else if (timeout == 0)
389 /* Waiting just for messages, zero timeout.
390 * If we got here, there was no message
392 ready = WAIT_TIMEOUT;
396 /* Waiting just for messages, some timeout
397 * -> Set a timer, wait for message,
398 * kill timer, use PeekMessage
400 timer = SetTimer (NULL, 0, timeout, NULL);
403 gchar *emsg = g_win32_error_message (GetLastError ());
404 g_warning (G_STRLOC ": SetTimer() failed: %s", emsg);
406 ready = WAIT_TIMEOUT;
410 #ifdef G_MAIN_POLL_DEBUG
411 g_print ("WaitMessage\n");
414 KillTimer (NULL, timer);
415 #ifdef G_MAIN_POLL_DEBUG
416 g_print ("PeekMessage\n");
418 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE)
419 && msg.message != WM_TIMER)
420 ready = WAIT_OBJECT_0;
422 ready = WAIT_TIMEOUT;
428 /* Wait for either message or event
429 * -> Use MsgWaitForMultipleObjects
431 #ifdef G_MAIN_POLL_DEBUG
432 g_print ("MsgWaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
434 ready = MsgWaitForMultipleObjects (nhandles, handles, FALSE,
435 timeout, QS_ALLINPUT);
437 if (ready == WAIT_FAILED)
439 gchar *emsg = g_win32_error_message (GetLastError ());
440 g_warning (G_STRLOC ": MsgWaitForMultipleObjects() failed: %s", emsg);
446 else if (nhandles == 0)
448 /* Wait for nothing (huh?) */
453 /* Wait for just events
454 * -> Use WaitForMultipleObjects
456 #ifdef G_MAIN_POLL_DEBUG
457 g_print ("WaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
459 ready = WaitForMultipleObjects (nhandles, handles, FALSE, timeout);
460 if (ready == WAIT_FAILED)
462 gchar *emsg = g_win32_error_message (GetLastError ());
463 g_warning (G_STRLOC ": WaitForMultipleObjects() failed: %s", emsg);
468 #ifdef G_MAIN_POLL_DEBUG
469 g_print ("wait returns %ld%s\n",
471 (ready == WAIT_FAILED ? " (WAIT_FAILED)" :
472 (ready == WAIT_TIMEOUT ? " (WAIT_TIMEOUT)" :
473 (poll_msgs && ready == WAIT_OBJECT_0 + nhandles ? " (msg)" : ""))));
475 for (f = fds; f < &fds[nfds]; ++f)
478 if (ready == WAIT_FAILED)
480 else if (ready == WAIT_TIMEOUT)
482 else if (poll_msgs && ready == WAIT_OBJECT_0 + nhandles)
484 for (f = fds; f < &fds[nfds]; ++f)
487 if (f->events & G_IO_IN)
488 if (f->fd == G_WIN32_MSG_HANDLE)
489 f->revents |= G_IO_IN;
492 else if (ready >= WAIT_OBJECT_0 && ready < WAIT_OBJECT_0 + nhandles)
493 for (f = fds; f < &fds[nfds]; ++f)
495 if (f->fd == (gint) handles[ready - WAIT_OBJECT_0])
497 f->revents = f->events;
498 #ifdef G_MAIN_POLL_DEBUG
499 g_print ("g_poll: got event %#x\n", f->fd);
507 #else /* !G_OS_WIN32 */
509 /* The following implementation of poll() comes from the GNU C Library.
510 * Copyright (C) 1994, 1996, 1997 Free Software Foundation, Inc.
513 #include <string.h> /* for bzero on BSD systems */
515 #ifdef HAVE_SYS_SELECT_H
516 #include <sys/select.h>
517 #endif /* HAVE_SYS_SELECT_H */
521 #endif /* G_OS_BEOS */
524 # define SELECT_MASK fd_set
525 #else /* !NO_FD_SET */
527 typedef long fd_mask;
530 # define SELECT_MASK void
532 # define SELECT_MASK int
533 # endif /* !_IBMR2 */
534 #endif /* !NO_FD_SET */
537 g_poll (GPollFD *fds,
542 SELECT_MASK rset, wset, xset;
551 for (f = fds; f < &fds[nfds]; ++f)
554 if (f->events & G_IO_IN)
555 FD_SET (f->fd, &rset);
556 if (f->events & G_IO_OUT)
557 FD_SET (f->fd, &wset);
558 if (f->events & G_IO_PRI)
559 FD_SET (f->fd, &xset);
560 if (f->fd > maxfd && (f->events & (G_IO_IN|G_IO_OUT|G_IO_PRI)))
564 tv.tv_sec = timeout / 1000;
565 tv.tv_usec = (timeout % 1000) * 1000;
567 ready = select (maxfd + 1, &rset, &wset, &xset,
568 timeout == -1 ? NULL : &tv);
570 for (f = fds; f < &fds[nfds]; ++f)
575 if (FD_ISSET (f->fd, &rset))
576 f->revents |= G_IO_IN;
577 if (FD_ISSET (f->fd, &wset))
578 f->revents |= G_IO_OUT;
579 if (FD_ISSET (f->fd, &xset))
580 f->revents |= G_IO_PRI;
587 #endif /* !G_OS_WIN32 */
589 #endif /* !HAVE_POLL */
592 * g_main_context_ref:
593 * @context: a #GMainContext
595 * Increases the reference count on a #GMainContext object by one.
597 * Returns: the @context that was passed in (since 2.6)
600 g_main_context_ref (GMainContext *context)
602 g_return_val_if_fail (context != NULL, NULL);
603 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
605 g_atomic_int_inc (&context->ref_count);
611 poll_rec_list_free (GMainContext *context,
614 g_slice_free_chain (GPollRec, list, next);
618 * g_main_context_unref:
619 * @context: a #GMainContext
621 * Decreases the reference count on a #GMainContext object by one. If
622 * the result is zero, free the context and free all associated memory.
625 g_main_context_unref (GMainContext *context)
628 g_return_if_fail (context != NULL);
629 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
631 if (!g_atomic_int_dec_and_test (&context->ref_count))
634 G_LOCK (main_context_list);
635 main_context_list = g_slist_remove (main_context_list, context);
636 G_UNLOCK (main_context_list);
638 source = context->source_list;
641 GSource *next = source->next;
642 g_source_destroy_internal (source, context, FALSE);
646 #ifdef G_THREADS_ENABLED
647 g_static_mutex_free (&context->mutex);
650 g_ptr_array_free (context->pending_dispatches, TRUE);
651 g_free (context->cached_poll_array);
653 poll_rec_list_free (context, context->poll_records);
655 #ifdef G_THREADS_ENABLED
656 if (g_thread_supported())
659 close (context->wake_up_pipe[0]);
660 close (context->wake_up_pipe[1]);
662 CloseHandle (context->wake_up_semaphore);
666 main_contexts_without_pipe = g_slist_remove (main_contexts_without_pipe,
673 #ifdef G_THREADS_ENABLED
675 g_main_context_init_pipe (GMainContext *context)
678 if (context->wake_up_pipe[0] != -1)
680 if (pipe (context->wake_up_pipe) < 0)
681 g_error ("Cannot create pipe main loop wake-up: %s\n",
684 context->wake_up_rec.fd = context->wake_up_pipe[0];
685 context->wake_up_rec.events = G_IO_IN;
687 if (context->wake_up_semaphore != NULL)
689 context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
690 if (context->wake_up_semaphore == NULL)
691 g_error ("Cannot create wake-up semaphore: %s",
692 g_win32_error_message (GetLastError ()));
693 context->wake_up_rec.fd = (gint) context->wake_up_semaphore;
694 context->wake_up_rec.events = G_IO_IN;
695 # ifdef G_MAIN_POLL_DEBUG
696 g_print ("wake-up semaphore: %#x\n", (guint) context->wake_up_semaphore);
699 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
703 _g_main_thread_init (void)
705 GSList *curr = main_contexts_without_pipe;
708 g_main_context_init_pipe ((GMainContext *)curr->data);
711 g_slist_free (main_contexts_without_pipe);
712 main_contexts_without_pipe = NULL;
714 #endif /* G_THREADS_ENABLED */
717 * g_main_context_new:
719 * Creates a new #GMainContext strcuture
721 * Return value: the new #GMainContext
724 g_main_context_new (void)
726 GMainContext *context = g_new0 (GMainContext, 1);
728 #ifdef G_THREADS_ENABLED
729 g_static_mutex_init (&context->mutex);
731 context->owner = NULL;
732 context->waiters = NULL;
735 context->wake_up_pipe[0] = -1;
736 context->wake_up_pipe[1] = -1;
738 context->wake_up_semaphore = NULL;
742 context->ref_count = 1;
744 context->next_id = 1;
746 context->source_list = NULL;
749 context->poll_func = (GPollFunc)poll;
751 context->poll_func = g_poll;
754 context->cached_poll_array = NULL;
755 context->cached_poll_array_size = 0;
757 context->pending_dispatches = g_ptr_array_new ();
759 context->time_is_current = FALSE;
761 #ifdef G_THREADS_ENABLED
762 if (g_thread_supported ())
763 g_main_context_init_pipe (context);
765 main_contexts_without_pipe = g_slist_prepend (main_contexts_without_pipe,
769 G_LOCK (main_context_list);
770 main_context_list = g_slist_append (main_context_list, context);
771 G_UNLOCK (main_context_list);
777 * g_main_context_default:
779 * Returns the default main context. This is the main context used
780 * for main loop functions when a main loop is not explicitly
783 * Return value: the default main context.
786 g_main_context_default (void)
792 if (!default_main_context)
793 default_main_context = g_main_context_new ();
795 G_UNLOCK (main_loop);
797 return default_main_context;
800 /* Hooks for adding to the main loop */
804 * @source_funcs: structure containing functions that implement
805 * the sources behavior.
806 * @struct_size: size of the #GSource structure to create.
808 * Creates a new #GSource structure. The size is specified to
809 * allow creating structures derived from #GSource that contain
810 * additional data. The size passed in must be at least
811 * <literal>sizeof (GSource)</literal>.
813 * The source will not initially be associated with any #GMainContext
814 * and must be added to one with g_source_attach() before it will be
817 * Return value: the newly-created #GSource.
820 g_source_new (GSourceFuncs *source_funcs,
825 g_return_val_if_fail (source_funcs != NULL, NULL);
826 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
828 source = (GSource*) g_malloc0 (struct_size);
830 source->source_funcs = source_funcs;
831 source->ref_count = 1;
833 source->priority = G_PRIORITY_DEFAULT;
835 source->flags = G_HOOK_FLAG_ACTIVE;
837 /* NULL/0 initialization for all other fields */
842 /* Holds context's lock
845 g_source_list_add (GSource *source,
846 GMainContext *context)
848 GSource *tmp_source, *last_source;
851 tmp_source = context->source_list;
852 while (tmp_source && tmp_source->priority <= source->priority)
854 last_source = tmp_source;
855 tmp_source = tmp_source->next;
858 source->next = tmp_source;
860 tmp_source->prev = source;
862 source->prev = last_source;
864 last_source->next = source;
866 context->source_list = source;
869 /* Holds context's lock
872 g_source_list_remove (GSource *source,
873 GMainContext *context)
876 source->prev->next = source->next;
878 context->source_list = source->next;
881 source->next->prev = source->prev;
889 * @source: a #GSource
890 * @context: a #GMainContext (if %NULL, the default context will be used)
892 * Adds a #GSource to a @context so that it will be executed within
895 * Return value: the ID (greater than 0) for the source within the
899 g_source_attach (GSource *source,
900 GMainContext *context)
905 g_return_val_if_fail (source->context == NULL, 0);
906 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
909 context = g_main_context_default ();
911 LOCK_CONTEXT (context);
913 source->context = context;
914 result = source->source_id = context->next_id++;
917 g_source_list_add (source, context);
919 tmp_list = source->poll_fds;
922 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
923 tmp_list = tmp_list->next;
926 #ifdef G_THREADS_ENABLED
927 /* Now wake up the main loop if it is waiting in the poll() */
928 g_main_context_wakeup_unlocked (context);
931 UNLOCK_CONTEXT (context);
937 g_source_destroy_internal (GSource *source,
938 GMainContext *context,
942 LOCK_CONTEXT (context);
944 if (!SOURCE_DESTROYED (source))
947 gpointer old_cb_data;
948 GSourceCallbackFuncs *old_cb_funcs;
950 source->flags &= ~G_HOOK_FLAG_ACTIVE;
952 old_cb_data = source->callback_data;
953 old_cb_funcs = source->callback_funcs;
955 source->callback_data = NULL;
956 source->callback_funcs = NULL;
960 UNLOCK_CONTEXT (context);
961 old_cb_funcs->unref (old_cb_data);
962 LOCK_CONTEXT (context);
965 if (!SOURCE_BLOCKED (source))
967 tmp_list = source->poll_fds;
970 g_main_context_remove_poll_unlocked (context, tmp_list->data);
971 tmp_list = tmp_list->next;
975 g_source_unref_internal (source, context, TRUE);
979 UNLOCK_CONTEXT (context);
984 * @source: a #GSource
986 * Removes a source from its #GMainContext, if any, and mark it as
987 * destroyed. The source cannot be subsequently added to another
991 g_source_destroy (GSource *source)
993 GMainContext *context;
995 g_return_if_fail (source != NULL);
997 context = source->context;
1000 g_source_destroy_internal (source, context, FALSE);
1002 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1007 * @source: a #GSource
1009 * Returns the numeric ID for a particular source. The ID of a source
1010 * is a positive integer which is unique within a particular main loop
1011 * context. The reverse
1012 * mapping from ID to source is done by g_main_context_find_source_by_id().
1014 * Return value: the ID (greater than 0) for the source
1017 g_source_get_id (GSource *source)
1021 g_return_val_if_fail (source != NULL, 0);
1022 g_return_val_if_fail (source->context != NULL, 0);
1024 LOCK_CONTEXT (source->context);
1025 result = source->source_id;
1026 UNLOCK_CONTEXT (source->context);
1032 * g_source_get_context:
1033 * @source: a #GSource
1035 * Gets the #GMainContext with which the source is associated.
1036 * Calling this function on a destroyed source is an error.
1038 * Return value: the #GMainContext with which the source is associated,
1039 * or %NULL if the context has not yet been added
1043 g_source_get_context (GSource *source)
1045 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1047 return source->context;
1051 * g_source_add_poll:
1052 * @source:a #GSource
1053 * @fd: a #GPollFD structure holding information about a file
1054 * descriptor to watch.
1056 * Adds a file descriptor to the set of file descriptors polled for
1057 * this source. This is usually combined with g_source_new() to add an
1058 * event source. The event source's check function will typically test
1059 * the @revents field in the #GPollFD struct and return %TRUE if events need
1063 g_source_add_poll (GSource *source,
1066 GMainContext *context;
1068 g_return_if_fail (source != NULL);
1069 g_return_if_fail (fd != NULL);
1070 g_return_if_fail (!SOURCE_DESTROYED (source));
1072 context = source->context;
1075 LOCK_CONTEXT (context);
1077 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1081 if (!SOURCE_BLOCKED (source))
1082 g_main_context_add_poll_unlocked (context, source->priority, fd);
1083 UNLOCK_CONTEXT (context);
1088 * g_source_remove_poll:
1089 * @source:a #GSource
1090 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1092 * Removes a file descriptor from the set of file descriptors polled for
1096 g_source_remove_poll (GSource *source,
1099 GMainContext *context;
1101 g_return_if_fail (source != NULL);
1102 g_return_if_fail (fd != NULL);
1103 g_return_if_fail (!SOURCE_DESTROYED (source));
1105 context = source->context;
1108 LOCK_CONTEXT (context);
1110 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1114 if (!SOURCE_BLOCKED (source))
1115 g_main_context_remove_poll_unlocked (context, fd);
1116 UNLOCK_CONTEXT (context);
1121 * g_source_set_callback_indirect:
1122 * @source: the source
1123 * @callback_data: pointer to callback data "object"
1124 * @callback_funcs: functions for reference counting @callback_data
1125 * and getting the callback and data
1127 * Sets the callback function storing the data as a refcounted callback
1128 * "object". This is used internally. Note that calling
1129 * g_source_set_callback_indirect() assumes
1130 * an initial reference count on @callback_data, and thus
1131 * @callback_funcs->unref will eventually be called once more
1132 * than @callback_funcs->ref.
1135 g_source_set_callback_indirect (GSource *source,
1136 gpointer callback_data,
1137 GSourceCallbackFuncs *callback_funcs)
1139 GMainContext *context;
1140 gpointer old_cb_data;
1141 GSourceCallbackFuncs *old_cb_funcs;
1143 g_return_if_fail (source != NULL);
1144 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1146 context = source->context;
1149 LOCK_CONTEXT (context);
1151 old_cb_data = source->callback_data;
1152 old_cb_funcs = source->callback_funcs;
1154 source->callback_data = callback_data;
1155 source->callback_funcs = callback_funcs;
1158 UNLOCK_CONTEXT (context);
1161 old_cb_funcs->unref (old_cb_data);
1165 g_source_callback_ref (gpointer cb_data)
1167 GSourceCallback *callback = cb_data;
1169 callback->ref_count++;
1174 g_source_callback_unref (gpointer cb_data)
1176 GSourceCallback *callback = cb_data;
1178 callback->ref_count--;
1179 if (callback->ref_count == 0)
1181 if (callback->notify)
1182 callback->notify (callback->data);
1188 g_source_callback_get (gpointer cb_data,
1193 GSourceCallback *callback = cb_data;
1195 *func = callback->func;
1196 *data = callback->data;
1199 static GSourceCallbackFuncs g_source_callback_funcs = {
1200 g_source_callback_ref,
1201 g_source_callback_unref,
1202 g_source_callback_get,
1206 * g_source_set_callback:
1207 * @source: the source
1208 * @func: a callback function
1209 * @data: the data to pass to callback function
1210 * @notify: a function to call when @data is no longer in use, or %NULL.
1212 * Sets the callback function for a source. The callback for a source is
1213 * called from the source's dispatch function.
1215 * The exact type of @func depends on the type of source; ie. you
1216 * should not count on @func being called with @data as its first
1219 * Typically, you won't use this function. Instead use functions specific
1220 * to the type of source you are using.
1223 g_source_set_callback (GSource *source,
1226 GDestroyNotify notify)
1228 GSourceCallback *new_callback;
1230 g_return_if_fail (source != NULL);
1232 new_callback = g_new (GSourceCallback, 1);
1234 new_callback->ref_count = 1;
1235 new_callback->func = func;
1236 new_callback->data = data;
1237 new_callback->notify = notify;
1239 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1244 * g_source_set_funcs:
1245 * @source: a #GSource
1246 * @funcs: the new #GSourceFuncs
1248 * Sets the source functions (can be used to override
1249 * default implementations) of an unattached source.
1254 g_source_set_funcs (GSource *source,
1255 GSourceFuncs *funcs)
1257 g_return_if_fail (source != NULL);
1258 g_return_if_fail (source->context == NULL);
1259 g_return_if_fail (source->ref_count > 0);
1260 g_return_if_fail (funcs != NULL);
1262 source->source_funcs = funcs;
1266 * g_source_set_priority:
1267 * @source: a #GSource
1268 * @priority: the new priority.
1270 * Sets the priority of a source. While the main loop is being
1271 * run, a source will be dispatched if it is ready to be dispatched and no sources
1272 * at a higher (numerically smaller) priority are ready to be dispatched.
1275 g_source_set_priority (GSource *source,
1279 GMainContext *context;
1281 g_return_if_fail (source != NULL);
1283 context = source->context;
1286 LOCK_CONTEXT (context);
1288 source->priority = priority;
1292 /* Remove the source from the context's source and then
1293 * add it back so it is sorted in the correct plcae
1295 g_source_list_remove (source, source->context);
1296 g_source_list_add (source, source->context);
1298 if (!SOURCE_BLOCKED (source))
1300 tmp_list = source->poll_fds;
1303 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1304 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1306 tmp_list = tmp_list->next;
1310 UNLOCK_CONTEXT (source->context);
1315 * g_source_get_priority:
1316 * @source: a #GSource
1318 * Gets the priority of a source.
1320 * Return value: the priority of the source
1323 g_source_get_priority (GSource *source)
1325 g_return_val_if_fail (source != NULL, 0);
1327 return source->priority;
1331 * g_source_set_can_recurse:
1332 * @source: a #GSource
1333 * @can_recurse: whether recursion is allowed for this source
1335 * Sets whether a source can be called recursively. If @can_recurse is
1336 * %TRUE, then while the source is being dispatched then this source
1337 * will be processed normally. Otherwise, all processing of this
1338 * source is blocked until the dispatch function returns.
1341 g_source_set_can_recurse (GSource *source,
1342 gboolean can_recurse)
1344 GMainContext *context;
1346 g_return_if_fail (source != NULL);
1348 context = source->context;
1351 LOCK_CONTEXT (context);
1354 source->flags |= G_SOURCE_CAN_RECURSE;
1356 source->flags &= ~G_SOURCE_CAN_RECURSE;
1359 UNLOCK_CONTEXT (context);
1363 * g_source_get_can_recurse:
1364 * @source: a #GSource
1366 * Checks whether a source is allowed to be called recursively.
1367 * see g_source_set_can_recurse().
1369 * Return value: whether recursion is allowed.
1372 g_source_get_can_recurse (GSource *source)
1374 g_return_val_if_fail (source != NULL, FALSE);
1376 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1381 * @source: a #GSource
1383 * Increases the reference count on a source by one.
1385 * Return value: @source
1388 g_source_ref (GSource *source)
1390 GMainContext *context;
1392 g_return_val_if_fail (source != NULL, NULL);
1394 context = source->context;
1397 LOCK_CONTEXT (context);
1399 source->ref_count++;
1402 UNLOCK_CONTEXT (context);
1407 /* g_source_unref() but possible to call within context lock
1410 g_source_unref_internal (GSource *source,
1411 GMainContext *context,
1414 gpointer old_cb_data = NULL;
1415 GSourceCallbackFuncs *old_cb_funcs = NULL;
1417 g_return_if_fail (source != NULL);
1419 if (!have_lock && context)
1420 LOCK_CONTEXT (context);
1422 source->ref_count--;
1423 if (source->ref_count == 0)
1425 old_cb_data = source->callback_data;
1426 old_cb_funcs = source->callback_funcs;
1428 source->callback_data = NULL;
1429 source->callback_funcs = NULL;
1431 if (context && !SOURCE_DESTROYED (source))
1433 g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1434 source->ref_count++;
1437 g_source_list_remove (source, context);
1439 if (source->source_funcs->finalize)
1440 source->source_funcs->finalize (source);
1442 g_slist_free (source->poll_fds);
1443 source->poll_fds = NULL;
1447 if (!have_lock && context)
1448 UNLOCK_CONTEXT (context);
1453 UNLOCK_CONTEXT (context);
1455 old_cb_funcs->unref (old_cb_data);
1458 LOCK_CONTEXT (context);
1464 * @source: a #GSource
1466 * Decreases the reference count of a source by one. If the
1467 * resulting reference count is zero the source and associated
1468 * memory will be destroyed.
1471 g_source_unref (GSource *source)
1473 g_return_if_fail (source != NULL);
1475 g_source_unref_internal (source, source->context, FALSE);
1479 * g_main_context_find_source_by_id:
1480 * @context: a #GMainContext (if %NULL, the default context will be used)
1481 * @source_id: the source ID, as returned by g_source_get_id().
1483 * Finds a #GSource given a pair of context and ID.
1485 * Return value: the #GSource if found, otherwise, %NULL
1488 g_main_context_find_source_by_id (GMainContext *context,
1493 g_return_val_if_fail (source_id > 0, NULL);
1495 if (context == NULL)
1496 context = g_main_context_default ();
1498 LOCK_CONTEXT (context);
1500 source = context->source_list;
1503 if (!SOURCE_DESTROYED (source) &&
1504 source->source_id == source_id)
1506 source = source->next;
1509 UNLOCK_CONTEXT (context);
1515 * g_main_context_find_source_by_funcs_user_data:
1516 * @context: a #GMainContext (if %NULL, the default context will be used).
1517 * @funcs: the @source_funcs passed to g_source_new().
1518 * @user_data: the user data from the callback.
1520 * Finds a source with the given source functions and user data. If
1521 * multiple sources exist with the same source function and user data,
1522 * the first one found will be returned.
1524 * Return value: the source, if one was found, otherwise %NULL
1527 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1528 GSourceFuncs *funcs,
1533 g_return_val_if_fail (funcs != NULL, NULL);
1535 if (context == NULL)
1536 context = g_main_context_default ();
1538 LOCK_CONTEXT (context);
1540 source = context->source_list;
1543 if (!SOURCE_DESTROYED (source) &&
1544 source->source_funcs == funcs &&
1545 source->callback_funcs)
1547 GSourceFunc callback;
1548 gpointer callback_data;
1550 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1552 if (callback_data == user_data)
1555 source = source->next;
1558 UNLOCK_CONTEXT (context);
1564 * g_main_context_find_source_by_user_data:
1565 * @context: a #GMainContext
1566 * @user_data: the user_data for the callback.
1568 * Finds a source with the given user data for the callback. If
1569 * multiple sources exist with the same user data, the first
1570 * one found will be returned.
1572 * Return value: the source, if one was found, otherwise %NULL
1575 g_main_context_find_source_by_user_data (GMainContext *context,
1580 if (context == NULL)
1581 context = g_main_context_default ();
1583 LOCK_CONTEXT (context);
1585 source = context->source_list;
1588 if (!SOURCE_DESTROYED (source) &&
1589 source->callback_funcs)
1591 GSourceFunc callback;
1592 gpointer callback_data = NULL;
1594 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1596 if (callback_data == user_data)
1599 source = source->next;
1602 UNLOCK_CONTEXT (context);
1609 * @tag: the ID of the source to remove.
1611 * Removes the source with the given id from the default main context.
1613 * a #GSource is given by g_source_get_id(), or will be returned by the
1614 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1615 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1616 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1618 * See also g_source_destroy().
1620 * Return value: %TRUE if the source was found and removed.
1623 g_source_remove (guint tag)
1627 g_return_val_if_fail (tag > 0, FALSE);
1629 source = g_main_context_find_source_by_id (NULL, tag);
1631 g_source_destroy (source);
1633 return source != NULL;
1637 * g_source_remove_by_user_data:
1638 * @user_data: the user_data for the callback.
1640 * Removes a source from the default main loop context given the user
1641 * data for the callback. If multiple sources exist with the same user
1642 * data, only one will be destroyed.
1644 * Return value: %TRUE if a source was found and removed.
1647 g_source_remove_by_user_data (gpointer user_data)
1651 source = g_main_context_find_source_by_user_data (NULL, user_data);
1654 g_source_destroy (source);
1662 * g_source_remove_by_funcs_user_data:
1663 * @funcs: The @source_funcs passed to g_source_new()
1664 * @user_data: the user data for the callback
1666 * Removes a source from the default main loop context given the
1667 * source functions and user data. If multiple sources exist with the
1668 * same source functions and user data, only one will be destroyed.
1670 * Return value: %TRUE if a source was found and removed.
1673 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1678 g_return_val_if_fail (funcs != NULL, FALSE);
1680 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1683 g_source_destroy (source);
1691 * g_get_current_time:
1692 * @result: #GTimeVal structure in which to store current time.
1694 * Equivalent to the UNIX gettimeofday() function, but portable.
1697 g_get_current_time (GTimeVal *result)
1702 g_return_if_fail (result != NULL);
1704 /*this is required on alpha, there the timeval structs are int's
1705 not longs and a cast only would fail horribly*/
1706 gettimeofday (&r, NULL);
1707 result->tv_sec = r.tv_sec;
1708 result->tv_usec = r.tv_usec;
1711 guint64 *time64 = (guint64 *) &ft;
1713 GetSystemTimeAsFileTime (&ft);
1715 /* Convert from 100s of nanoseconds since 1601-01-01
1716 * to Unix epoch. Yes, this is Y2038 unsafe.
1718 *time64 -= G_GINT64_CONSTANT (116444736000000000);
1721 result->tv_sec = *time64 / 1000000;
1722 result->tv_usec = *time64 % 1000000;
1727 g_main_dispatch_free (gpointer dispatch)
1729 g_slice_free (GMainDispatch, dispatch);
1732 /* Running the main loop */
1734 static GMainDispatch *
1737 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
1738 GMainDispatch *dispatch = g_static_private_get (&depth_private);
1741 dispatch = g_slice_new0 (GMainDispatch);
1742 g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
1751 * Return value: The main loop recursion level in the current thread
1753 * Returns the depth of the stack of calls to
1754 * g_main_context_dispatch() on any #GMainContext in the current thread.
1755 * That is, when called from the toplevel, it gives 0. When
1756 * called from within a callback from g_main_context_iteration()
1757 * (or g_main_loop_run(), etc.) it returns 1. When called from within
1758 * a callback to a recursive call to g_main_context_iterate(),
1759 * it returns 2. And so forth.
1761 * This function is useful in a situation like the following:
1762 * Imagine an extremely simple "garbage collected" system.
1765 * static GList *free_list;
1768 * allocate_memory (gsize size)
1770 * gpointer result = g_malloc (size);
1771 * free_list = g_list_prepend (free_list, result);
1776 * free_allocated_memory (void)
1779 * for (l = free_list; l; l = l->next);
1781 * g_list_free (free_list);
1789 * g_main_context_iteration (NULL, TRUE);
1790 * free_allocated_memory();
1794 * This works from an application, however, if you want to do the same
1795 * thing from a library, it gets more difficult, since you no longer
1796 * control the main loop. You might think you can simply use an idle
1797 * function to make the call to free_allocated_memory(), but that
1798 * doesn't work, since the idle function could be called from a
1799 * recursive callback. This can be fixed by using g_main_depth()
1803 * allocate_memory (gsize size)
1805 * FreeListBlock *block = g_new (FreeListBlock, 1);\
1806 * block->mem = g_malloc (size);
1807 * block->depth = g_main_depth ();
1808 * free_list = g_list_prepend (free_list, block);
1809 * return block->mem;
1813 * free_allocated_memory (void)
1817 * int depth = g_main_depth ();
1818 * for (l = free_list; l; );
1820 * GList *next = l->next;
1821 * FreeListBlock *block = l->data;
1822 * if (block->depth > depth)
1824 * g_free (block->mem);
1826 * free_list = g_list_delete_link (free_list, l);
1834 * There is a temptation to use g_main_depth() to solve
1835 * problems with reentrancy. For instance, while waiting for data
1836 * to be received from the network in response to a menu item,
1837 * the menu item might be selected again. It might seem that
1838 * one could make the menu item's callback return immediately
1839 * and do nothing if g_main_depth() returns a value greater than 1.
1840 * However, this should be avoided since the user then sees selecting
1841 * the menu item do nothing. Furthermore, you'll find yourself adding
1842 * these checks all over your code, since there are doubtless many,
1843 * many things that the user could do. Instead, you can use the
1844 * following techniques:
1849 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
1850 * the user from interacting with elements while the main
1851 * loop is recursing.
1856 * Avoid main loop recursion in situations where you can't handle
1857 * arbitrary callbacks. Instead, structure your code so that you
1858 * simply return to the main loop and then get called again when
1859 * there is more work to do.
1867 GMainDispatch *dispatch = get_dispatch ();
1868 return dispatch->depth;
1872 * g_main_current_source:
1874 * Returns the currently firing source for this thread.
1876 * Return value: The currently firing source or %NULL.
1881 g_main_current_source (void)
1883 GMainDispatch *dispatch = get_dispatch ();
1884 return dispatch->source ? dispatch->source->data : NULL;
1888 * g_source_is_destroyed:
1889 * @source: a #GSource
1891 * Returns whether @source has been destroyed.
1893 * This is important when you operate upon your objects
1894 * from within idle handlers, but may have freed the object
1895 * before the dispatch of your idle handler.
1897 * <informalexample><programlisting>
1899 * idle_callback (gpointer data)
1901 * SomeWidget *self = data;
1903 * GDK_THREADS_ENTER (<!-- -->);
1904 * /<!-- -->* do stuff with self *<!-- -->/
1905 * self->idle_id = 0;
1906 * GDK_THREADS_LEAVE (<!-- -->);
1912 * some_widget_do_stuff_later (SomeWidget *self)
1914 * self->idle_id = g_idle_add (idle_callback, self);
1918 * some_widget_finalize (GObject *object)
1920 * SomeWidget *self = SOME_WIDGET (object);
1922 * if (self->idle_id)
1923 * g_source_remove (self->idle_id);
1925 * G_OBJECT_CLASS (parent_class)->finalize (object);
1927 * </programlisting></informalexample>
1929 * This will fail in a multi-threaded application if the
1930 * widget is destroyed before the idle handler fires due
1931 * to the use after free in the callback. A solution, to
1932 * this particular problem, is to check to if the source
1933 * has already been destroy within the callback.
1935 * <informalexample><programlisting>
1937 * idle_callback (gpointer data)
1939 * SomeWidget *self = data;
1941 * GDK_THREADS_ENTER ();
1942 * if (!g_source_is_destroyed (g_main_current_source ()))
1944 * /<!-- -->* do stuff with self *<!-- -->/
1946 * GDK_THREADS_LEAVE ();
1950 * </programlisting></informalexample>
1952 * Return value: %TRUE if the source has been destroyed
1957 g_source_is_destroyed (GSource *source)
1959 return SOURCE_DESTROYED (source);
1963 /* Temporarily remove all this source's file descriptors from the
1964 * poll(), so that if data comes available for one of the file descriptors
1965 * we don't continually spin in the poll()
1967 /* HOLDS: source->context's lock */
1969 block_source (GSource *source)
1973 g_return_if_fail (!SOURCE_BLOCKED (source));
1975 tmp_list = source->poll_fds;
1978 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
1979 tmp_list = tmp_list->next;
1983 /* HOLDS: source->context's lock */
1985 unblock_source (GSource *source)
1989 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
1990 g_return_if_fail (!SOURCE_DESTROYED (source));
1992 tmp_list = source->poll_fds;
1995 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
1996 tmp_list = tmp_list->next;
2000 /* HOLDS: context's lock */
2002 g_main_dispatch (GMainContext *context)
2004 GMainDispatch *current = get_dispatch ();
2007 for (i = 0; i < context->pending_dispatches->len; i++)
2009 GSource *source = context->pending_dispatches->pdata[i];
2011 context->pending_dispatches->pdata[i] = NULL;
2014 source->flags &= ~G_SOURCE_READY;
2016 if (!SOURCE_DESTROYED (source))
2018 gboolean was_in_call;
2019 gpointer user_data = NULL;
2020 GSourceFunc callback = NULL;
2021 GSourceCallbackFuncs *cb_funcs;
2023 gboolean need_destroy;
2025 gboolean (*dispatch) (GSource *,
2029 dispatch = source->source_funcs->dispatch;
2030 cb_funcs = source->callback_funcs;
2031 cb_data = source->callback_data;
2034 cb_funcs->ref (cb_data);
2036 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2037 block_source (source);
2039 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2040 source->flags |= G_HOOK_FLAG_IN_CALL;
2043 cb_funcs->get (cb_data, source, &callback, &user_data);
2045 UNLOCK_CONTEXT (context);
2048 current->source = g_slist_prepend (current->source, source);
2049 need_destroy = ! dispatch (source,
2052 current->source = g_slist_remove (current->source, source);
2056 cb_funcs->unref (cb_data);
2058 LOCK_CONTEXT (context);
2061 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2063 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2064 !SOURCE_DESTROYED (source))
2065 unblock_source (source);
2067 /* Note: this depends on the fact that we can't switch
2068 * sources from one main context to another
2070 if (need_destroy && !SOURCE_DESTROYED (source))
2072 g_assert (source->context == context);
2073 g_source_destroy_internal (source, context, TRUE);
2077 SOURCE_UNREF (source, context);
2080 g_ptr_array_set_size (context->pending_dispatches, 0);
2083 /* Holds context's lock */
2084 static inline GSource *
2085 next_valid_source (GMainContext *context,
2088 GSource *new_source = source ? source->next : context->source_list;
2092 if (!SOURCE_DESTROYED (new_source))
2094 new_source->ref_count++;
2098 new_source = new_source->next;
2102 SOURCE_UNREF (source, context);
2108 * g_main_context_acquire:
2109 * @context: a #GMainContext
2111 * Tries to become the owner of the specified context.
2112 * If some other context is the owner of the context,
2113 * returns %FALSE immediately. Ownership is properly
2114 * recursive: the owner can require ownership again
2115 * and will release ownership when g_main_context_release()
2116 * is called as many times as g_main_context_acquire().
2118 * You must be the owner of a context before you
2119 * can call g_main_context_prepare(), g_main_context_query(),
2120 * g_main_context_check(), g_main_context_dispatch().
2122 * Return value: %TRUE if the operation succeeded, and
2123 * this thread is now the owner of @context.
2126 g_main_context_acquire (GMainContext *context)
2128 #ifdef G_THREADS_ENABLED
2129 gboolean result = FALSE;
2130 GThread *self = G_THREAD_SELF;
2132 if (context == NULL)
2133 context = g_main_context_default ();
2135 LOCK_CONTEXT (context);
2137 if (!context->owner)
2139 context->owner = self;
2140 g_assert (context->owner_count == 0);
2143 if (context->owner == self)
2145 context->owner_count++;
2149 UNLOCK_CONTEXT (context);
2152 #else /* !G_THREADS_ENABLED */
2154 #endif /* G_THREADS_ENABLED */
2158 * g_main_context_release:
2159 * @context: a #GMainContext
2161 * Releases ownership of a context previously acquired by this thread
2162 * with g_main_context_acquire(). If the context was acquired multiple
2163 * times, the only release ownership when g_main_context_release()
2164 * is called as many times as it was acquired.
2167 g_main_context_release (GMainContext *context)
2169 #ifdef G_THREADS_ENABLED
2170 if (context == NULL)
2171 context = g_main_context_default ();
2173 LOCK_CONTEXT (context);
2175 context->owner_count--;
2176 if (context->owner_count == 0)
2178 context->owner = NULL;
2180 if (context->waiters)
2182 GMainWaiter *waiter = context->waiters->data;
2183 gboolean loop_internal_waiter =
2184 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
2185 context->waiters = g_slist_delete_link (context->waiters,
2187 if (!loop_internal_waiter)
2188 g_mutex_lock (waiter->mutex);
2190 g_cond_signal (waiter->cond);
2192 if (!loop_internal_waiter)
2193 g_mutex_unlock (waiter->mutex);
2197 UNLOCK_CONTEXT (context);
2198 #endif /* G_THREADS_ENABLED */
2202 * g_main_context_wait:
2203 * @context: a #GMainContext
2204 * @cond: a condition variable
2205 * @mutex: a mutex, currently held
2207 * Tries to become the owner of the specified context,
2208 * as with g_main_context_acquire(). But if another thread
2209 * is the owner, atomically drop @mutex and wait on @cond until
2210 * that owner releases ownership or until @cond is signaled, then
2211 * try again (once) to become the owner.
2213 * Return value: %TRUE if the operation succeeded, and
2214 * this thread is now the owner of @context.
2217 g_main_context_wait (GMainContext *context,
2221 #ifdef G_THREADS_ENABLED
2222 gboolean result = FALSE;
2223 GThread *self = G_THREAD_SELF;
2224 gboolean loop_internal_waiter;
2226 if (context == NULL)
2227 context = g_main_context_default ();
2229 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2231 if (!loop_internal_waiter)
2232 LOCK_CONTEXT (context);
2234 if (context->owner && context->owner != self)
2239 waiter.mutex = mutex;
2241 context->waiters = g_slist_append (context->waiters, &waiter);
2243 if (!loop_internal_waiter)
2244 UNLOCK_CONTEXT (context);
2245 g_cond_wait (cond, mutex);
2246 if (!loop_internal_waiter)
2247 LOCK_CONTEXT (context);
2249 context->waiters = g_slist_remove (context->waiters, &waiter);
2252 if (!context->owner)
2254 context->owner = self;
2255 g_assert (context->owner_count == 0);
2258 if (context->owner == self)
2260 context->owner_count++;
2264 if (!loop_internal_waiter)
2265 UNLOCK_CONTEXT (context);
2268 #else /* !G_THREADS_ENABLED */
2270 #endif /* G_THREADS_ENABLED */
2274 * g_main_context_prepare:
2275 * @context: a #GMainContext
2276 * @priority: location to store priority of highest priority
2277 * source already ready.
2279 * Prepares to poll sources within a main loop. The resulting information
2280 * for polling is determined by calling g_main_context_query ().
2282 * Return value: %TRUE if some source is ready to be dispatched
2286 g_main_context_prepare (GMainContext *context,
2291 gint current_priority = G_MAXINT;
2294 if (context == NULL)
2295 context = g_main_context_default ();
2297 LOCK_CONTEXT (context);
2299 context->time_is_current = FALSE;
2301 if (context->in_check_or_prepare)
2303 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2304 "prepare() member.");
2305 UNLOCK_CONTEXT (context);
2309 #ifdef G_THREADS_ENABLED
2310 if (context->poll_waiting)
2312 g_warning("g_main_context_prepare(): main loop already active in another thread");
2313 UNLOCK_CONTEXT (context);
2317 context->poll_waiting = TRUE;
2318 #endif /* G_THREADS_ENABLED */
2321 /* If recursing, finish up current dispatch, before starting over */
2322 if (context->pending_dispatches)
2325 g_main_dispatch (context, ¤t_time);
2327 UNLOCK_CONTEXT (context);
2332 /* If recursing, clear list of pending dispatches */
2334 for (i = 0; i < context->pending_dispatches->len; i++)
2336 if (context->pending_dispatches->pdata[i])
2337 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2339 g_ptr_array_set_size (context->pending_dispatches, 0);
2341 /* Prepare all sources */
2343 context->timeout = -1;
2345 source = next_valid_source (context, NULL);
2348 gint source_timeout = -1;
2350 if ((n_ready > 0) && (source->priority > current_priority))
2352 SOURCE_UNREF (source, context);
2355 if (SOURCE_BLOCKED (source))
2358 if (!(source->flags & G_SOURCE_READY))
2361 gboolean (*prepare) (GSource *source,
2364 prepare = source->source_funcs->prepare;
2365 context->in_check_or_prepare++;
2366 UNLOCK_CONTEXT (context);
2368 result = (*prepare) (source, &source_timeout);
2370 LOCK_CONTEXT (context);
2371 context->in_check_or_prepare--;
2374 source->flags |= G_SOURCE_READY;
2377 if (source->flags & G_SOURCE_READY)
2380 current_priority = source->priority;
2381 context->timeout = 0;
2384 if (source_timeout >= 0)
2386 if (context->timeout < 0)
2387 context->timeout = source_timeout;
2389 context->timeout = MIN (context->timeout, source_timeout);
2393 source = next_valid_source (context, source);
2396 UNLOCK_CONTEXT (context);
2399 *priority = current_priority;
2401 return (n_ready > 0);
2405 * g_main_context_query:
2406 * @context: a #GMainContext
2407 * @max_priority: maximum priority source to check
2408 * @timeout_: location to store timeout to be used in polling
2409 * @fds: location to store #GPollFD records that need to be polled.
2410 * @n_fds: length of @fds.
2412 * Determines information necessary to poll this main loop.
2414 * Return value: the number of records actually stored in @fds,
2415 * or, if more than @n_fds records need to be stored, the number
2416 * of records that need to be stored.
2419 g_main_context_query (GMainContext *context,
2428 LOCK_CONTEXT (context);
2430 pollrec = context->poll_records;
2432 while (pollrec && max_priority >= pollrec->priority)
2434 if (pollrec->fd->events)
2438 fds[n_poll].fd = pollrec->fd->fd;
2439 /* In direct contradiction to the Unix98 spec, IRIX runs into
2440 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2441 * flags in the events field of the pollfd while it should
2442 * just ignoring them. So we mask them out here.
2444 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2445 fds[n_poll].revents = 0;
2450 pollrec = pollrec->next;
2453 #ifdef G_THREADS_ENABLED
2454 context->poll_changed = FALSE;
2459 *timeout = context->timeout;
2461 context->time_is_current = FALSE;
2464 UNLOCK_CONTEXT (context);
2470 * g_main_context_check:
2471 * @context: a #GMainContext
2472 * @max_priority: the maximum numerical priority of sources to check
2473 * @fds: array of #GPollFD's that was passed to the last call to
2474 * g_main_context_query()
2475 * @n_fds: return value of g_main_context_query()
2477 * Passes the results of polling back to the main loop.
2479 * Return value: %TRUE if some sources are ready to be dispatched.
2482 g_main_context_check (GMainContext *context,
2492 LOCK_CONTEXT (context);
2494 if (context->in_check_or_prepare)
2496 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2497 "prepare() member.");
2498 UNLOCK_CONTEXT (context);
2502 #ifdef G_THREADS_ENABLED
2503 if (!context->poll_waiting)
2507 read (context->wake_up_pipe[0], &a, 1);
2511 context->poll_waiting = FALSE;
2513 /* If the set of poll file descriptors changed, bail out
2514 * and let the main loop rerun
2516 if (context->poll_changed)
2518 UNLOCK_CONTEXT (context);
2521 #endif /* G_THREADS_ENABLED */
2523 pollrec = context->poll_records;
2527 if (pollrec->fd->events)
2529 pollrec->fd->revents = fds[i].revents;
2532 pollrec = pollrec->next;
2535 source = next_valid_source (context, NULL);
2538 if ((n_ready > 0) && (source->priority > max_priority))
2540 SOURCE_UNREF (source, context);
2543 if (SOURCE_BLOCKED (source))
2546 if (!(source->flags & G_SOURCE_READY))
2549 gboolean (*check) (GSource *source);
2551 check = source->source_funcs->check;
2553 context->in_check_or_prepare++;
2554 UNLOCK_CONTEXT (context);
2556 result = (*check) (source);
2558 LOCK_CONTEXT (context);
2559 context->in_check_or_prepare--;
2562 source->flags |= G_SOURCE_READY;
2565 if (source->flags & G_SOURCE_READY)
2567 source->ref_count++;
2568 g_ptr_array_add (context->pending_dispatches, source);
2572 /* never dispatch sources with less priority than the first
2573 * one we choose to dispatch
2575 max_priority = source->priority;
2579 source = next_valid_source (context, source);
2582 UNLOCK_CONTEXT (context);
2588 * g_main_context_dispatch:
2589 * @context: a #GMainContext
2591 * Dispatches all pending sources.
2594 g_main_context_dispatch (GMainContext *context)
2596 LOCK_CONTEXT (context);
2598 if (context->pending_dispatches->len > 0)
2600 g_main_dispatch (context);
2603 UNLOCK_CONTEXT (context);
2606 /* HOLDS context lock */
2608 g_main_context_iterate (GMainContext *context,
2615 gboolean some_ready;
2616 gint nfds, allocated_nfds;
2617 GPollFD *fds = NULL;
2619 UNLOCK_CONTEXT (context);
2621 #ifdef G_THREADS_ENABLED
2622 if (!g_main_context_acquire (context))
2624 gboolean got_ownership;
2626 g_return_val_if_fail (g_thread_supported (), FALSE);
2631 LOCK_CONTEXT (context);
2634 context->cond = g_cond_new ();
2636 got_ownership = g_main_context_wait (context,
2638 g_static_mutex_get_mutex (&context->mutex));
2642 UNLOCK_CONTEXT (context);
2647 LOCK_CONTEXT (context);
2648 #endif /* G_THREADS_ENABLED */
2650 if (!context->cached_poll_array)
2652 context->cached_poll_array_size = context->n_poll_records;
2653 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2656 allocated_nfds = context->cached_poll_array_size;
2657 fds = context->cached_poll_array;
2659 UNLOCK_CONTEXT (context);
2661 g_main_context_prepare (context, &max_priority);
2663 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
2664 allocated_nfds)) > allocated_nfds)
2666 LOCK_CONTEXT (context);
2668 context->cached_poll_array_size = allocated_nfds = nfds;
2669 context->cached_poll_array = fds = g_new (GPollFD, nfds);
2670 UNLOCK_CONTEXT (context);
2676 g_main_context_poll (context, timeout, max_priority, fds, nfds);
2678 some_ready = g_main_context_check (context, max_priority, fds, nfds);
2681 g_main_context_dispatch (context);
2683 #ifdef G_THREADS_ENABLED
2684 g_main_context_release (context);
2685 #endif /* G_THREADS_ENABLED */
2687 LOCK_CONTEXT (context);
2693 * g_main_context_pending:
2694 * @context: a #GMainContext (if %NULL, the default context will be used)
2696 * Checks if any sources have pending events for the given context.
2698 * Return value: %TRUE if events are pending.
2701 g_main_context_pending (GMainContext *context)
2706 context = g_main_context_default();
2708 LOCK_CONTEXT (context);
2709 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
2710 UNLOCK_CONTEXT (context);
2716 * g_main_context_iteration:
2717 * @context: a #GMainContext (if %NULL, the default context will be used)
2718 * @may_block: whether the call may block.
2720 * Runs a single iteration for the given main loop. This involves
2721 * checking to see if any event sources are ready to be processed,
2722 * then if no events sources are ready and @may_block is %TRUE, waiting
2723 * for a source to become ready, then dispatching the highest priority
2724 * events sources that are ready. Note that even when @may_block is %TRUE,
2725 * it is still possible for g_main_context_iteration() to return
2726 * %FALSE, since the the wait may be interrupted for other
2727 * reasons than an event source becoming ready.
2729 * Return value: %TRUE if events were dispatched.
2732 g_main_context_iteration (GMainContext *context, gboolean may_block)
2737 context = g_main_context_default();
2739 LOCK_CONTEXT (context);
2740 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
2741 UNLOCK_CONTEXT (context);
2748 * @context: a #GMainContext (if %NULL, the default context will be used).
2749 * @is_running: set to %TRUE to indicate that the loop is running. This
2750 * is not very important since calling g_main_loop_run() will set this to
2753 * Creates a new #GMainLoop structure.
2755 * Return value: a new #GMainLoop.
2758 g_main_loop_new (GMainContext *context,
2759 gboolean is_running)
2764 context = g_main_context_default();
2766 g_main_context_ref (context);
2768 loop = g_new0 (GMainLoop, 1);
2769 loop->context = context;
2770 loop->is_running = is_running != FALSE;
2771 loop->ref_count = 1;
2778 * @loop: a #GMainLoop
2780 * Increases the reference count on a #GMainLoop object by one.
2782 * Return value: @loop
2785 g_main_loop_ref (GMainLoop *loop)
2787 g_return_val_if_fail (loop != NULL, NULL);
2788 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2790 g_atomic_int_inc (&loop->ref_count);
2796 * g_main_loop_unref:
2797 * @loop: a #GMainLoop
2799 * Decreases the reference count on a #GMainLoop object by one. If
2800 * the result is zero, free the loop and free all associated memory.
2803 g_main_loop_unref (GMainLoop *loop)
2805 g_return_if_fail (loop != NULL);
2806 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2808 if (!g_atomic_int_dec_and_test (&loop->ref_count))
2811 g_main_context_unref (loop->context);
2817 * @loop: a #GMainLoop
2819 * Runs a main loop until g_main_loop_quit() is called on the loop.
2820 * If this is called for the thread of the loop's #GMainContext,
2821 * it will process events from the loop, otherwise it will
2825 g_main_loop_run (GMainLoop *loop)
2827 GThread *self = G_THREAD_SELF;
2829 g_return_if_fail (loop != NULL);
2830 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2832 #ifdef G_THREADS_ENABLED
2833 if (!g_main_context_acquire (loop->context))
2835 gboolean got_ownership = FALSE;
2837 /* Another thread owns this context */
2838 if (!g_thread_supported ())
2840 g_warning ("g_main_loop_run() was called from second thread but "
2841 "g_thread_init() was never called.");
2845 LOCK_CONTEXT (loop->context);
2847 g_atomic_int_inc (&loop->ref_count);
2849 if (!loop->is_running)
2850 loop->is_running = TRUE;
2852 if (!loop->context->cond)
2853 loop->context->cond = g_cond_new ();
2855 while (loop->is_running && !got_ownership)
2856 got_ownership = g_main_context_wait (loop->context,
2857 loop->context->cond,
2858 g_static_mutex_get_mutex (&loop->context->mutex));
2860 if (!loop->is_running)
2862 UNLOCK_CONTEXT (loop->context);
2864 g_main_context_release (loop->context);
2865 g_main_loop_unref (loop);
2869 g_assert (got_ownership);
2872 LOCK_CONTEXT (loop->context);
2873 #endif /* G_THREADS_ENABLED */
2875 if (loop->context->in_check_or_prepare)
2877 g_warning ("g_main_loop_run(): called recursively from within a source's "
2878 "check() or prepare() member, iteration not possible.");
2882 g_atomic_int_inc (&loop->ref_count);
2883 loop->is_running = TRUE;
2884 while (loop->is_running)
2885 g_main_context_iterate (loop->context, TRUE, TRUE, self);
2887 UNLOCK_CONTEXT (loop->context);
2889 #ifdef G_THREADS_ENABLED
2890 g_main_context_release (loop->context);
2891 #endif /* G_THREADS_ENABLED */
2893 g_main_loop_unref (loop);
2898 * @loop: a #GMainLoop
2900 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
2901 * for the loop will return.
2904 g_main_loop_quit (GMainLoop *loop)
2906 g_return_if_fail (loop != NULL);
2907 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2909 LOCK_CONTEXT (loop->context);
2910 loop->is_running = FALSE;
2911 g_main_context_wakeup_unlocked (loop->context);
2913 #ifdef G_THREADS_ENABLED
2914 if (loop->context->cond)
2915 g_cond_broadcast (loop->context->cond);
2916 #endif /* G_THREADS_ENABLED */
2918 UNLOCK_CONTEXT (loop->context);
2922 * g_main_loop_is_running:
2923 * @loop: a #GMainLoop.
2925 * Checks to see if the main loop is currently being run via g_main_loop_run().
2927 * Return value: %TRUE if the mainloop is currently being run.
2930 g_main_loop_is_running (GMainLoop *loop)
2932 g_return_val_if_fail (loop != NULL, FALSE);
2933 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
2935 return loop->is_running;
2939 * g_main_loop_get_context:
2940 * @loop: a #GMainLoop.
2942 * Returns the #GMainContext of @loop.
2944 * Return value: the #GMainContext of @loop
2947 g_main_loop_get_context (GMainLoop *loop)
2949 g_return_val_if_fail (loop != NULL, NULL);
2950 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2952 return loop->context;
2955 /* HOLDS: context's lock */
2957 g_main_context_poll (GMainContext *context,
2963 #ifdef G_MAIN_POLL_DEBUG
2969 GPollFunc poll_func;
2971 if (n_fds || timeout != 0)
2973 #ifdef G_MAIN_POLL_DEBUG
2974 g_print ("g_main_poll(%d) timeout: %d\n", n_fds, timeout);
2975 poll_timer = g_timer_new ();
2978 LOCK_CONTEXT (context);
2980 poll_func = context->poll_func;
2982 UNLOCK_CONTEXT (context);
2983 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
2986 g_warning ("poll(2) failed due to: %s.",
2987 g_strerror (errno));
2989 /* If g_poll () returns -1, it has already called g_warning() */
2993 #ifdef G_MAIN_POLL_DEBUG
2994 LOCK_CONTEXT (context);
2996 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
2999 g_timer_elapsed (poll_timer, NULL));
3000 g_timer_destroy (poll_timer);
3001 pollrec = context->poll_records;
3005 if (pollrec->fd->events)
3009 g_print (" [%d:", fds[i].fd);
3010 if (fds[i].revents & G_IO_IN)
3012 if (fds[i].revents & G_IO_OUT)
3014 if (fds[i].revents & G_IO_PRI)
3016 if (fds[i].revents & G_IO_ERR)
3018 if (fds[i].revents & G_IO_HUP)
3020 if (fds[i].revents & G_IO_NVAL)
3026 pollrec = pollrec->next;
3030 UNLOCK_CONTEXT (context);
3032 } /* if (n_fds || timeout != 0) */
3036 * g_main_context_add_poll:
3037 * @context: a #GMainContext (or %NULL for the default context)
3038 * @fd: a #GPollFD structure holding information about a file
3039 * descriptor to watch.
3040 * @priority: the priority for this file descriptor which should be
3041 * the same as the priority used for g_source_attach() to ensure that the
3042 * file descriptor is polled whenever the results may be needed.
3044 * Adds a file descriptor to the set of file descriptors polled for
3045 * this context. This will very seldomly be used directly. Instead
3046 * a typical event source will use g_source_add_poll() instead.
3049 g_main_context_add_poll (GMainContext *context,
3054 context = g_main_context_default ();
3056 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3057 g_return_if_fail (fd);
3059 LOCK_CONTEXT (context);
3060 g_main_context_add_poll_unlocked (context, priority, fd);
3061 UNLOCK_CONTEXT (context);
3064 /* HOLDS: main_loop_lock */
3066 g_main_context_add_poll_unlocked (GMainContext *context,
3070 GPollRec *lastrec, *pollrec;
3071 GPollRec *newrec = g_slice_new (GPollRec);
3073 /* This file descriptor may be checked before we ever poll */
3076 newrec->priority = priority;
3079 pollrec = context->poll_records;
3080 while (pollrec && priority >= pollrec->priority)
3083 pollrec = pollrec->next;
3087 lastrec->next = newrec;
3089 context->poll_records = newrec;
3091 newrec->next = pollrec;
3093 context->n_poll_records++;
3095 #ifdef G_THREADS_ENABLED
3096 context->poll_changed = TRUE;
3098 /* Now wake up the main loop if it is waiting in the poll() */
3099 g_main_context_wakeup_unlocked (context);
3104 * g_main_context_remove_poll:
3105 * @context:a #GMainContext
3106 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3108 * Removes file descriptor from the set of file descriptors to be
3109 * polled for a particular context.
3112 g_main_context_remove_poll (GMainContext *context,
3116 context = g_main_context_default ();
3118 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3119 g_return_if_fail (fd);
3121 LOCK_CONTEXT (context);
3122 g_main_context_remove_poll_unlocked (context, fd);
3123 UNLOCK_CONTEXT (context);
3127 g_main_context_remove_poll_unlocked (GMainContext *context,
3130 GPollRec *pollrec, *lastrec;
3133 pollrec = context->poll_records;
3137 if (pollrec->fd == fd)
3139 if (lastrec != NULL)
3140 lastrec->next = pollrec->next;
3142 context->poll_records = pollrec->next;
3144 g_slice_free (GPollRec, pollrec);
3146 context->n_poll_records--;
3150 pollrec = pollrec->next;
3153 #ifdef G_THREADS_ENABLED
3154 context->poll_changed = TRUE;
3156 /* Now wake up the main loop if it is waiting in the poll() */
3157 g_main_context_wakeup_unlocked (context);
3162 * g_source_get_current_time:
3163 * @source: a #GSource
3164 * @timeval: #GTimeVal structure in which to store current time.
3166 * Gets the "current time" to be used when checking
3167 * this source. The advantage of calling this function over
3168 * calling g_get_current_time() directly is that when
3169 * checking multiple sources, GLib can cache a single value
3170 * instead of having to repeatedly get the system time.
3173 g_source_get_current_time (GSource *source,
3176 GMainContext *context;
3178 g_return_if_fail (source->context != NULL);
3180 context = source->context;
3182 LOCK_CONTEXT (context);
3184 if (!context->time_is_current)
3186 g_get_current_time (&context->current_time);
3187 context->time_is_current = TRUE;
3190 *timeval = context->current_time;
3192 UNLOCK_CONTEXT (context);
3196 * g_main_context_set_poll_func:
3197 * @context: a #GMainContext
3198 * @func: the function to call to poll all file descriptors
3200 * Sets the function to use to handle polling of file descriptors. It
3201 * will be used instead of the poll() system call
3202 * (or GLib's replacement function, which is used where
3203 * poll() isn't available).
3205 * This function could possibly be used to integrate the GLib event
3206 * loop with an external event loop.
3209 g_main_context_set_poll_func (GMainContext *context,
3213 context = g_main_context_default ();
3215 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3217 LOCK_CONTEXT (context);
3220 context->poll_func = func;
3224 context->poll_func = (GPollFunc) poll;
3226 context->poll_func = (GPollFunc) g_poll;
3230 UNLOCK_CONTEXT (context);
3234 * g_main_context_get_poll_func:
3235 * @context: a #GMainContext
3237 * Gets the poll function set by g_main_context_set_poll_func().
3239 * Return value: the poll function
3242 g_main_context_get_poll_func (GMainContext *context)
3247 context = g_main_context_default ();
3249 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3251 LOCK_CONTEXT (context);
3252 result = context->poll_func;
3253 UNLOCK_CONTEXT (context);
3258 /* HOLDS: context's lock */
3259 /* Wake the main loop up from a poll() */
3261 g_main_context_wakeup_unlocked (GMainContext *context)
3263 #ifdef G_THREADS_ENABLED
3264 if (g_thread_supported() && context->poll_waiting)
3266 context->poll_waiting = FALSE;
3268 write (context->wake_up_pipe[1], "A", 1);
3270 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
3277 * g_main_context_wakeup:
3278 * @context: a #GMainContext
3280 * If @context is currently waiting in a poll(), interrupt
3281 * the poll(), and continue the iteration process.
3284 g_main_context_wakeup (GMainContext *context)
3287 context = g_main_context_default ();
3289 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3291 LOCK_CONTEXT (context);
3292 g_main_context_wakeup_unlocked (context);
3293 UNLOCK_CONTEXT (context);
3297 * g_main_context_is_owner:
3298 * @context: a #GMainContext
3300 * Determines whether this thread holds the (recursive)
3301 * ownership of this #GMaincontext. This is useful to
3302 * know before waiting on another thread that may be
3303 * blocking to get ownership of @context.
3305 * Returns: %TRUE if current thread is owner of @context.
3310 g_main_context_is_owner (GMainContext *context)
3315 context = g_main_context_default ();
3317 #ifdef G_THREADS_ENABLED
3318 LOCK_CONTEXT (context);
3319 is_owner = context->owner == G_THREAD_SELF;
3320 UNLOCK_CONTEXT (context);
3331 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3332 GTimeVal *current_time)
3334 guint seconds = timeout_source->interval / 1000;
3335 guint msecs = timeout_source->interval - seconds * 1000;
3337 timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
3338 timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
3339 if (timeout_source->expiration.tv_usec >= 1000000)
3341 timeout_source->expiration.tv_usec -= 1000000;
3342 timeout_source->expiration.tv_sec++;
3344 if (timer_perturb==-1)
3347 * we want a per machine/session unique 'random' value; try the dbus
3348 * address first, that has a UUID in it. If there is no dbus, use the
3349 * hostname for hashing.
3351 const char *session_bus_address = getenv("DBUS_SESSION_BUS_ADDRESS");
3352 if (!session_bus_address)
3353 session_bus_address = getenv("HOSTNAME");
3354 if (session_bus_address)
3355 timer_perturb = g_str_hash(session_bus_address);
3359 if (timeout_source->granularity)
3362 gint gran; /* in usecs */
3365 gran = timeout_source->granularity * 1000;
3366 perturb = timer_perturb % gran;
3368 * We want to give each machine a per machine pertubation;
3369 * shift time back first, and forward later after the rounding
3372 timeout_source->expiration.tv_usec -= perturb;
3373 if (timeout_source->expiration.tv_usec < 0)
3375 timeout_source->expiration.tv_usec += 1000000;
3376 timeout_source->expiration.tv_sec--;
3379 remainder = timeout_source->expiration.tv_usec % gran;
3380 if (remainder >= gran/4) /* round up */
3381 timeout_source->expiration.tv_usec += gran;
3382 timeout_source->expiration.tv_usec -= remainder;
3384 timeout_source->expiration.tv_usec += perturb;
3386 /* the rounding may have overflown tv_usec */
3387 while (timeout_source->expiration.tv_usec > 1000000)
3389 timeout_source->expiration.tv_usec -= 1000000;
3390 timeout_source->expiration.tv_sec++;
3396 g_timeout_prepare (GSource *source,
3401 GTimeVal current_time;
3403 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3405 g_source_get_current_time (source, ¤t_time);
3407 sec = timeout_source->expiration.tv_sec - current_time.tv_sec;
3408 msec = (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000;
3410 /* We do the following in a rather convoluted fashion to deal with
3411 * the fact that we don't have an integral type big enough to hold
3412 * the difference of two timevals in millseconds.
3414 if (sec < 0 || (sec == 0 && msec < 0))
3418 glong interval_sec = timeout_source->interval / 1000;
3419 glong interval_msec = timeout_source->interval % 1000;
3427 if (sec > interval_sec ||
3428 (sec == interval_sec && msec > interval_msec))
3430 /* The system time has been set backwards, so we
3431 * reset the expiration time to now + timeout_source->interval;
3432 * this at least avoids hanging for long periods of time.
3434 g_timeout_set_expiration (timeout_source, ¤t_time);
3435 msec = MIN (G_MAXINT, timeout_source->interval);
3439 msec = MIN (G_MAXINT, (guint)msec + 1000 * (guint)sec);
3443 *timeout = (gint)msec;
3449 g_timeout_check (GSource *source)
3451 GTimeVal current_time;
3452 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3454 g_source_get_current_time (source, ¤t_time);
3456 return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
3457 ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
3458 (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
3462 g_timeout_dispatch (GSource *source,
3463 GSourceFunc callback,
3466 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3470 g_warning ("Timeout source dispatched without callback\n"
3471 "You must call g_source_set_callback().");
3475 if (callback (user_data))
3477 GTimeVal current_time;
3479 g_source_get_current_time (source, ¤t_time);
3480 g_timeout_set_expiration (timeout_source, ¤t_time);
3489 * g_timeout_source_new:
3490 * @interval: the timeout interval in milliseconds.
3492 * Creates a new timeout source.
3494 * The source will not initially be associated with any #GMainContext
3495 * and must be added to one with g_source_attach() before it will be
3498 * Return value: the newly-created timeout source
3501 g_timeout_source_new (guint interval)
3503 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3504 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3505 GTimeVal current_time;
3507 timeout_source->interval = interval;
3509 g_get_current_time (¤t_time);
3510 g_timeout_set_expiration (timeout_source, ¤t_time);
3516 * g_timeout_source_new_seconds:
3517 * @interval: the timeout interval in seconds
3519 * Creates a new timeout source.
3521 * The source will not initially be associated with any #GMainContext
3522 * and must be added to one with g_source_attach() before it will be
3524 * The scheduling granularity/accuracy of this timeout source will be
3527 * Return value: the newly-created timeout source
3532 g_timeout_source_new_seconds (guint interval)
3534 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3535 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3536 GTimeVal current_time;
3538 timeout_source->interval = 1000*interval;
3539 timeout_source->granularity = 1000;
3541 g_get_current_time (¤t_time);
3542 g_timeout_set_expiration (timeout_source, ¤t_time);
3549 * g_timeout_add_full:
3550 * @priority: the priority of the idle source. Typically this will be in the
3551 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3552 * @interval: the time between calls to the function, in milliseconds
3553 * (1/1000ths of a second)
3554 * @function: function to call
3555 * @data: data to pass to @function
3556 * @notify: function to call when the idle is removed, or %NULL
3558 * Sets a function to be called at regular intervals, with the given
3559 * priority. The function is called repeatedly until it returns
3560 * %FALSE, at which point the timeout is automatically destroyed and
3561 * the function will not be called again. The @notify function is
3562 * called when the timeout is destroyed. The first call to the
3563 * function will be at the end of the first @interval.
3565 * Note that timeout functions may be delayed, due to the processing of other
3566 * event sources. Thus they should not be relied on for precise timing.
3567 * After each call to the timeout function, the time of the next
3568 * timeout is recalculated based on the current time and the given interval
3569 * (it does not try to 'catch up' time lost in delays).
3571 * Return value: the ID (greater than 0) of the event source.
3574 g_timeout_add_full (gint priority,
3576 GSourceFunc function,
3578 GDestroyNotify notify)
3583 g_return_val_if_fail (function != NULL, 0);
3585 source = g_timeout_source_new (interval);
3587 if (priority != G_PRIORITY_DEFAULT)
3588 g_source_set_priority (source, priority);
3590 g_source_set_callback (source, function, data, notify);
3591 id = g_source_attach (source, NULL);
3592 g_source_unref (source);
3599 * @interval: the time between calls to the function, in milliseconds
3600 * (1/1000ths of a second)
3601 * @function: function to call
3602 * @data: data to pass to @function
3604 * Sets a function to be called at regular intervals, with the default
3605 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
3606 * until it returns %FALSE, at which point the timeout is automatically
3607 * destroyed and the function will not be called again. The first call
3608 * to the function will be at the end of the first @interval.
3610 * Note that timeout functions may be delayed, due to the processing of other
3611 * event sources. Thus they should not be relied on for precise timing.
3612 * After each call to the timeout function, the time of the next
3613 * timeout is recalculated based on the current time and the given interval
3614 * (it does not try to 'catch up' time lost in delays).
3616 * If you want to have a timer in the "seconds" range and do not care
3617 * about the exact time of the first call of the timer, use the
3618 * g_timeout_add_seconds() function; this function allows for more
3619 * optimizations and more efficient system power usage.
3621 * Return value: the ID (greater than 0) of the event source.
3624 g_timeout_add (guint32 interval,
3625 GSourceFunc function,
3628 return g_timeout_add_full (G_PRIORITY_DEFAULT,
3629 interval, function, data, NULL);
3633 * g_timeout_add_seconds:
3634 * @interval: the time between calls to the function, in seconds
3635 * @function: function to call
3636 * @data: data to pass to @function
3638 * Sets a function to be called at regular intervals, with the default
3639 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
3640 * until it returns %FALSE, at which point the timeout is automatically
3641 * destroyed and the function will not be called again.
3643 * Unlike g_timeout_add(), this function operates at whole second granularity.
3644 * The initial starting point of the timer is determined by the implementation
3645 * and the implementation is expected to group multiple timers together so that
3646 * they fire all at the same time.
3647 * To allow this grouping, the @interval to the first timer is rounded
3648 * and can deviate up to one second from the specified interval.
3649 * Subsequent timer iterations will generally run at the specified interval.
3651 * Note that timeout functions may be delayed, due to the processing of other
3652 * event sources. Thus they should not be relied on for precise timing.
3653 * After each call to the timeout function, the time of the next
3654 * timeout is recalculated based on the current time and the given @interval
3656 * If you want timing more precise than whole seconds, use g_timeout_add()
3659 * The grouping of timers to fire at the same time results in a more power
3660 * and CPU efficient behavior so if your timer is in multiples of seconds
3661 * and you don't require the first timer exactly 1 second from now, the
3662 * use of g_timeout_add_second() is prefered over g_timeout_add().
3664 * Return value: the ID (greater than 0) of the event source.
3669 g_timeout_add_seconds (guint32 interval,
3670 GSourceFunc function,
3676 g_return_val_if_fail (function != NULL, 0);
3678 source = g_timeout_source_new_seconds (interval);
3680 g_source_set_callback (source, function, data, NULL);
3681 id = g_source_attach (source, NULL);
3682 g_source_unref (source);
3688 /* Child watch functions */
3693 g_child_watch_prepare (GSource *source,
3702 g_child_watch_check (GSource *source)
3704 GChildWatchSource *child_watch_source;
3705 gboolean child_exited;
3707 child_watch_source = (GChildWatchSource *) source;
3709 child_exited = child_watch_source->poll.revents & G_IO_IN;
3716 * Note: We do _not_ check for the special value of STILL_ACTIVE
3717 * since we know that the process has exited and doing so runs into
3718 * problems if the child process "happens to return STILL_ACTIVE(259)"
3719 * as Microsoft's Platform SDK puts it.
3721 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
3723 gchar *emsg = g_win32_error_message (GetLastError ());
3724 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
3727 child_watch_source->child_status = -1;
3730 child_watch_source->child_status = child_status;
3733 return child_exited;
3736 #else /* G_OS_WIN32 */
3739 check_for_child_exited (GSource *source)
3741 GChildWatchSource *child_watch_source;
3744 /* protect against another SIGCHLD in the middle of this call */
3745 count = child_watch_count;
3747 child_watch_source = (GChildWatchSource *) source;
3749 if (child_watch_source->child_exited)
3752 if (child_watch_source->count < count)
3756 if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
3758 child_watch_source->child_status = child_status;
3759 child_watch_source->child_exited = TRUE;
3761 child_watch_source->count = count;
3764 return child_watch_source->child_exited;
3768 g_child_watch_prepare (GSource *source,
3773 return check_for_child_exited (source);
3778 g_child_watch_check (GSource *source)
3780 return check_for_child_exited (source);
3783 #endif /* G_OS_WIN32 */
3786 g_child_watch_dispatch (GSource *source,
3787 GSourceFunc callback,
3790 GChildWatchSource *child_watch_source;
3791 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
3793 child_watch_source = (GChildWatchSource *) source;
3797 g_warning ("Child watch source dispatched without callback\n"
3798 "You must call g_source_set_callback().");
3802 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
3804 /* We never keep a child watch source around as the child is gone */
3811 g_child_watch_signal_handler (int signum)
3813 child_watch_count ++;
3815 if (child_watch_init_state == CHILD_WATCH_INITIALIZED_THREADED)
3817 write (child_watch_wake_up_pipe[1], "B", 1);
3821 /* We count on the signal interrupting the poll in the same thread.
3827 g_child_watch_source_init_single (void)
3829 struct sigaction action;
3831 g_assert (! g_thread_supported());
3832 g_assert (child_watch_init_state == CHILD_WATCH_UNINITIALIZED);
3834 child_watch_init_state = CHILD_WATCH_INITIALIZED_SINGLE;
3836 action.sa_handler = g_child_watch_signal_handler;
3837 sigemptyset (&action.sa_mask);
3838 action.sa_flags = SA_NOCLDSTOP;
3839 sigaction (SIGCHLD, &action, NULL);
3843 child_watch_helper_thread (gpointer data)
3850 read (child_watch_wake_up_pipe[0], b, 20);
3852 /* We were woken up. Wake up all other contexts in all other threads */
3853 G_LOCK (main_context_list);
3854 for (list = main_context_list; list; list = list->next)
3856 GMainContext *context;
3858 context = list->data;
3859 if (g_atomic_int_get (&context->ref_count) > 0)
3860 /* Due to racing conditions we can find ref_count == 0, in
3861 * that case, however, the context is still not destroyed
3862 * and no poll can be active, otherwise the ref_count
3864 g_main_context_wakeup (context);
3866 G_UNLOCK (main_context_list);
3871 g_child_watch_source_init_multi_threaded (void)
3873 GError *error = NULL;
3874 struct sigaction action;
3876 g_assert (g_thread_supported());
3878 if (pipe (child_watch_wake_up_pipe) < 0)
3879 g_error ("Cannot create wake up pipe: %s\n", g_strerror (errno));
3880 fcntl (child_watch_wake_up_pipe[1], F_SETFL, O_NONBLOCK | fcntl (child_watch_wake_up_pipe[1], F_GETFL));
3882 /* We create a helper thread that polls on the wakeup pipe indefinitely */
3883 /* FIXME: Think this through for races */
3884 if (g_thread_create (child_watch_helper_thread, NULL, FALSE, &error) == NULL)
3885 g_error ("Cannot create a thread to monitor child exit status: %s\n", error->message);
3886 child_watch_init_state = CHILD_WATCH_INITIALIZED_THREADED;
3888 action.sa_handler = g_child_watch_signal_handler;
3889 sigemptyset (&action.sa_mask);
3890 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
3891 sigaction (SIGCHLD, &action, NULL);
3895 g_child_watch_source_init_promote_single_to_threaded (void)
3897 g_child_watch_source_init_multi_threaded ();
3901 g_child_watch_source_init (void)
3903 if (g_thread_supported())
3905 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
3906 g_child_watch_source_init_multi_threaded ();
3907 else if (child_watch_init_state == CHILD_WATCH_INITIALIZED_SINGLE)
3908 g_child_watch_source_init_promote_single_to_threaded ();
3912 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
3913 g_child_watch_source_init_single ();
3917 #endif /* !G_OS_WIN32 */
3920 * g_child_watch_source_new:
3921 * @pid: process id of a child process to watch. On Windows, a HANDLE
3922 * for the process to watch (which actually doesn't have to be a child).
3924 * Creates a new child_watch source.
3926 * The source will not initially be associated with any #GMainContext
3927 * and must be added to one with g_source_attach() before it will be
3930 * Note that child watch sources can only be used in conjunction with
3931 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
3934 * Note that on platforms where #GPid must be explicitly closed
3935 * (see g_spawn_close_pid()) @pid must not be closed while the
3936 * source is still active. Typically, you will want to call
3937 * g_spawn_close_pid() in the callback function for the source.
3939 * Note further that using g_child_watch_source_new() is not
3940 * compatible with calling <literal>waitpid(-1)</literal> in
3941 * the application. Calling waitpid() for individual pids will
3944 * Return value: the newly-created child watch source
3949 g_child_watch_source_new (GPid pid)
3951 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
3952 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
3955 child_watch_source->poll.fd = (int)pid;
3956 child_watch_source->poll.events = G_IO_IN;
3958 g_source_add_poll (source, &child_watch_source->poll);
3959 #else /* G_OS_WIN32 */
3960 g_child_watch_source_init ();
3961 #endif /* G_OS_WIN32 */
3963 child_watch_source->pid = pid;
3969 * g_child_watch_add_full:
3970 * @priority: the priority of the idle source. Typically this will be in the
3971 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3972 * @pid: process id of a child process to watch
3973 * @function: function to call
3974 * @data: data to pass to @function
3975 * @notify: function to call when the idle is removed, or %NULL
3977 * Sets a function to be called when the child indicated by @pid
3978 * exits, at the priority @priority.
3980 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
3981 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
3982 * the spawn function for the child watching to work.
3984 * Note that on platforms where #GPid must be explicitly closed
3985 * (see g_spawn_close_pid()) @pid must not be closed while the
3986 * source is still active. Typically, you will want to call
3987 * g_spawn_close_pid() in the callback function for the source.
3989 * GLib supports only a single callback per process id.
3991 * Return value: the ID (greater than 0) of the event source.
3996 g_child_watch_add_full (gint priority,
3998 GChildWatchFunc function,
4000 GDestroyNotify notify)
4005 g_return_val_if_fail (function != NULL, 0);
4007 source = g_child_watch_source_new (pid);
4009 if (priority != G_PRIORITY_DEFAULT)
4010 g_source_set_priority (source, priority);
4012 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4013 id = g_source_attach (source, NULL);
4014 g_source_unref (source);
4020 * g_child_watch_add:
4021 * @pid: process id of a child process to watch
4022 * @function: function to call
4023 * @data: data to pass to @function
4025 * Sets a function to be called when the child indicated by @pid
4026 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4028 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4029 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4030 * the spawn function for the child watching to work.
4032 * Note that on platforms where #GPid must be explicitly closed
4033 * (see g_spawn_close_pid()) @pid must not be closed while the
4034 * source is still active. Typically, you will want to call
4035 * g_spawn_close_pid() in the callback function for the source.
4037 * GLib supports only a single callback per process id.
4039 * Return value: the ID (greater than 0) of the event source.
4044 g_child_watch_add (GPid pid,
4045 GChildWatchFunc function,
4048 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4052 /* Idle functions */
4055 g_idle_prepare (GSource *source,
4064 g_idle_check (GSource *source)
4070 g_idle_dispatch (GSource *source,
4071 GSourceFunc callback,
4076 g_warning ("Idle source dispatched without callback\n"
4077 "You must call g_source_set_callback().");
4081 return callback (user_data);
4085 * g_idle_source_new:
4087 * Creates a new idle source.
4089 * The source will not initially be associated with any #GMainContext
4090 * and must be added to one with g_source_attach() before it will be
4091 * executed. Note that the default priority for idle sources is
4092 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4093 * have a default priority of %G_PRIORITY_DEFAULT.
4095 * Return value: the newly-created idle source
4098 g_idle_source_new (void)
4102 source = g_source_new (&g_idle_funcs, sizeof (GSource));
4103 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4110 * @priority: the priority of the idle source. Typically this will be in the
4111 * range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4112 * @function: function to call
4113 * @data: data to pass to @function
4114 * @notify: function to call when the idle is removed, or %NULL
4116 * Adds a function to be called whenever there are no higher priority
4117 * events pending. If the function returns %FALSE it is automatically
4118 * removed from the list of event sources and will not be called again.
4120 * Return value: the ID (greater than 0) of the event source.
4123 g_idle_add_full (gint priority,
4124 GSourceFunc function,
4126 GDestroyNotify notify)
4131 g_return_val_if_fail (function != NULL, 0);
4133 source = g_idle_source_new ();
4135 if (priority != G_PRIORITY_DEFAULT_IDLE)
4136 g_source_set_priority (source, priority);
4138 g_source_set_callback (source, function, data, notify);
4139 id = g_source_attach (source, NULL);
4140 g_source_unref (source);
4147 * @function: function to call
4148 * @data: data to pass to @function.
4150 * Adds a function to be called whenever there are no higher priority
4151 * events pending to the default main loop. The function is given the
4152 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4153 * returns %FALSE it is automatically removed from the list of event
4154 * sources and will not be called again.
4156 * Return value: the ID (greater than 0) of the event source.
4159 g_idle_add (GSourceFunc function,
4162 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4166 * g_idle_remove_by_data:
4167 * @data: the data for the idle source's callback.
4169 * Removes the idle function with the given data.
4171 * Return value: %TRUE if an idle source was found and removed.
4174 g_idle_remove_by_data (gpointer data)
4176 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4179 #define __G_MAIN_C__
4180 #include "galiasdef.c"