1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * gmain.c: Main loop abstraction, timeouts, and idle functions
5 * Copyright 1998 Owen Taylor
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the
19 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 * Boston, MA 02111-1307, USA.
24 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
25 * file for a list of people on the GLib Team. See the ChangeLog
26 * files for a list of changes. These files are distributed with
27 * GLib at ftp://ftp.gtk.org/pub/gtk/.
36 /* uncomment the next line to get poll() debugging info */
37 /* #define G_MAIN_POLL_DEBUG */
40 #include "gthreadinit.h"
42 #include <sys/types.h>
44 #ifdef HAVE_SYS_TIME_H
46 #endif /* HAVE_SYS_TIME_H */
47 #ifdef GLIB_HAVE_SYS_POLL_H
48 # include <sys/poll.h>
49 # undef events /* AIX 4.1.5 & 4.3.2 define this for SVR3,4 compatibility */
50 # undef revents /* AIX 4.1.5 & 4.3.2 define this for SVR3,4 compatibility */
51 #endif /* GLIB_HAVE_SYS_POLL_H */
54 #endif /* HAVE_UNISTD_H */
60 #endif /* G_OS_WIN32 */
63 #include <net/socket.h>
64 #endif /* G_OS_BEOS */
72 typedef struct _GTimeoutSource GTimeoutSource;
73 typedef struct _GChildWatchSource GChildWatchSource;
74 typedef struct _GPollRec GPollRec;
75 typedef struct _GSourceCallback GSourceCallback;
79 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
80 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
83 #ifdef G_THREADS_ENABLED
84 typedef struct _GMainWaiter GMainWaiter;
95 #ifdef G_THREADS_ENABLED
96 /* The following lock is used for both the list of sources
97 * and the list of poll records
108 GPtrArray *pending_dispatches;
109 gint timeout; /* Timeout for current iteration */
112 GSource *source_list;
113 gint in_check_or_prepare;
115 GPollRec *poll_records;
116 GPollRec *poll_free_list;
117 GMemChunk *poll_chunk;
118 guint n_poll_records;
119 GPollFD *cached_poll_array;
120 guint cached_poll_array_size;
122 #ifdef G_THREADS_ENABLED
124 /* this pipe is used to wake up the main loop when a source is added.
126 gint wake_up_pipe[2];
127 #else /* G_OS_WIN32 */
128 HANDLE wake_up_semaphore;
129 #endif /* G_OS_WIN32 */
132 gboolean poll_waiting;
134 /* Flag indicating whether the set of fd's changed during a poll */
135 gboolean poll_changed;
136 #endif /* G_THREADS_ENABLED */
140 GTimeVal current_time;
141 gboolean time_is_current;
144 struct _GSourceCallback
149 GDestroyNotify notify;
154 GMainContext *context;
159 struct _GTimeoutSource
166 struct _GChildWatchSource
172 gboolean child_exited;
182 #ifdef G_THREADS_ENABLED
183 #define LOCK_CONTEXT(context) g_static_mutex_lock (&context->mutex)
184 #define UNLOCK_CONTEXT(context) g_static_mutex_unlock (&context->mutex)
185 #define G_THREAD_SELF g_thread_self ()
187 #define LOCK_CONTEXT(context) (void)0
188 #define UNLOCK_CONTEXT(context) (void)0
189 #define G_THREAD_SELF NULL
192 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
194 #define SOURCE_UNREF(source, context) \
196 if ((source)->ref_count > 1) \
197 (source)->ref_count--; \
199 g_source_unref_internal ((source), (context), TRUE); \
203 /* Forward declarations */
205 static void g_source_unref_internal (GSource *source,
206 GMainContext *context,
208 static void g_source_destroy_internal (GSource *source,
209 GMainContext *context,
211 static void g_main_context_poll (GMainContext *context,
216 static void g_main_context_add_poll_unlocked (GMainContext *context,
219 static void g_main_context_remove_poll_unlocked (GMainContext *context,
221 static void g_main_context_wakeup_unlocked (GMainContext *context);
223 static gboolean g_timeout_prepare (GSource *source,
225 static gboolean g_timeout_check (GSource *source);
226 static gboolean g_timeout_dispatch (GSource *source,
227 GSourceFunc callback,
229 static gboolean g_child_watch_prepare (GSource *source,
231 static gboolean g_child_watch_check (GSource *source);
232 static gboolean g_child_watch_dispatch (GSource *source,
233 GSourceFunc callback,
235 static gboolean g_idle_prepare (GSource *source,
237 static gboolean g_idle_check (GSource *source);
238 static gboolean g_idle_dispatch (GSource *source,
239 GSourceFunc callback,
242 G_LOCK_DEFINE_STATIC (main_loop);
243 static GMainContext *default_main_context;
244 static GSList *main_contexts_without_pipe = NULL;
246 /* Child status monitoring code */
248 CHILD_WATCH_UNINITIALIZED,
249 CHILD_WATCH_INITIALIZED_SINGLE,
250 CHILD_WATCH_INITIALIZED_THREADED
252 static gint child_watch_init_state = CHILD_WATCH_UNINITIALIZED;
253 static gint child_watch_count = 0;
255 static gint child_watch_wake_up_pipe[2] = {0, 0};
257 static HANDLE child_watch_wake_up_semaphore = NULL;
259 G_LOCK_DEFINE_STATIC (main_context_list);
260 static GSList *main_context_list = NULL;
262 #if defined(G_PLATFORM_WIN32) && defined(__GNUC__)
263 __declspec(dllexport)
265 GSourceFuncs g_timeout_funcs =
273 GSourceFuncs g_child_watch_funcs =
275 g_child_watch_prepare,
277 g_child_watch_dispatch,
281 #if defined(G_PLATFORM_WIN32) && defined(__GNUC__)
282 __declspec(dllexport)
284 GSourceFuncs g_idle_funcs =
293 /* SunOS has poll, but doesn't provide a prototype. */
294 # if defined (sun) && !defined (__SVR4)
295 extern gint poll (GPollFD *ufds, guint nfsd, gint timeout);
297 #else /* !HAVE_POLL */
302 g_poll (GPollFD *fds,
306 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
307 gboolean poll_msgs = FALSE;
314 for (f = fds; f < &fds[nfds]; ++f)
317 if (f->fd == G_WIN32_MSG_HANDLE)
319 else if (nhandles == MAXIMUM_WAIT_OBJECTS)
321 g_warning (G_STRLOC ": Too many handles to wait for!\n");
326 #ifdef G_MAIN_POLL_DEBUG
327 g_print ("g_poll: waiting for %#x\n", f->fd);
329 handles[nhandles++] = (HANDLE) f->fd;
338 /* Waiting for messages, and maybe events
339 * -> First PeekMessage
341 #ifdef G_MAIN_POLL_DEBUG
342 g_print ("PeekMessage\n");
344 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
345 ready = WAIT_OBJECT_0 + nhandles;
350 /* Waiting just for messages */
351 if (timeout == INFINITE)
356 #ifdef G_MAIN_POLL_DEBUG
357 g_print ("WaitMessage\n");
361 gchar *emsg = g_win32_error_message (GetLastError ());
362 g_warning (G_STRLOC ": WaitMessage() failed: %s", emsg);
365 ready = WAIT_OBJECT_0 + nhandles;
367 else if (timeout == 0)
369 /* Waiting just for messages, zero timeout.
370 * If we got here, there was no message
372 ready = WAIT_TIMEOUT;
376 /* Waiting just for messages, some timeout
377 * -> Set a timer, wait for message,
378 * kill timer, use PeekMessage
380 timer = SetTimer (NULL, 0, timeout, NULL);
383 gchar *emsg = g_win32_error_message (GetLastError ());
384 g_warning (G_STRLOC ": SetTimer() failed: %s", emsg);
386 ready = WAIT_TIMEOUT;
390 #ifdef G_MAIN_POLL_DEBUG
391 g_print ("WaitMessage\n");
394 KillTimer (NULL, timer);
395 #ifdef G_MAIN_POLL_DEBUG
396 g_print ("PeekMessage\n");
398 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE)
399 && msg.message != WM_TIMER)
400 ready = WAIT_OBJECT_0;
402 ready = WAIT_TIMEOUT;
408 /* Wait for either message or event
409 * -> Use MsgWaitForMultipleObjects
411 #ifdef G_MAIN_POLL_DEBUG
412 g_print ("MsgWaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
414 ready = MsgWaitForMultipleObjects (nhandles, handles, FALSE,
415 timeout, QS_ALLINPUT);
417 if (ready == WAIT_FAILED)
419 gchar *emsg = g_win32_error_message (GetLastError ());
420 g_warning (G_STRLOC ": MsgWaitForMultipleObjects() failed: %s", emsg);
426 else if (nhandles == 0)
428 /* Wait for nothing (huh?) */
433 /* Wait for just events
434 * -> Use WaitForMultipleObjects
436 #ifdef G_MAIN_POLL_DEBUG
437 g_print ("WaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
439 ready = WaitForMultipleObjects (nhandles, handles, FALSE, timeout);
440 if (ready == WAIT_FAILED)
442 gchar *emsg = g_win32_error_message (GetLastError ());
443 g_warning (G_STRLOC ": WaitForMultipleObjects() failed: %s", emsg);
448 #ifdef G_MAIN_POLL_DEBUG
449 g_print ("wait returns %ld%s\n",
451 (ready == WAIT_FAILED ? " (WAIT_FAILED)" :
452 (ready == WAIT_TIMEOUT ? " (WAIT_TIMEOUT)" :
453 (poll_msgs && ready == WAIT_OBJECT_0 + nhandles ? " (msg)" : ""))));
455 for (f = fds; f < &fds[nfds]; ++f)
458 if (ready == WAIT_FAILED)
460 else if (ready == WAIT_TIMEOUT)
462 else if (poll_msgs && ready == WAIT_OBJECT_0 + nhandles)
464 for (f = fds; f < &fds[nfds]; ++f)
467 if (f->events & G_IO_IN)
468 if (f->fd == G_WIN32_MSG_HANDLE)
469 f->revents |= G_IO_IN;
472 #if 1 /* TEST_WITHOUT_THIS */
473 else if (ready >= WAIT_OBJECT_0 && ready < WAIT_OBJECT_0 + nhandles)
474 for (f = fds; f < &fds[nfds]; ++f)
476 if ((f->events & (G_IO_IN | G_IO_OUT))
477 && f->fd == (gint) handles[ready - WAIT_OBJECT_0])
479 if (f->events & G_IO_IN)
480 f->revents |= G_IO_IN;
482 f->revents |= G_IO_OUT;
483 #ifdef G_MAIN_POLL_DEBUG
484 g_print ("g_poll: got event %#x\n", f->fd);
487 ResetEvent ((HANDLE) f->fd);
496 #else /* !G_OS_WIN32 */
498 /* The following implementation of poll() comes from the GNU C Library.
499 * Copyright (C) 1994, 1996, 1997 Free Software Foundation, Inc.
502 #include <string.h> /* for bzero on BSD systems */
504 #ifdef HAVE_SYS_SELECT_H
505 #include <sys/select.h>
506 #endif /* HAVE_SYS_SELECT_H */
510 #endif /* G_OS_BEOS */
513 # define SELECT_MASK fd_set
514 #else /* !NO_FD_SET */
516 typedef long fd_mask;
519 # define SELECT_MASK void
521 # define SELECT_MASK int
522 # endif /* !_IBMR2 */
523 #endif /* !NO_FD_SET */
526 g_poll (GPollFD *fds,
531 SELECT_MASK rset, wset, xset;
540 for (f = fds; f < &fds[nfds]; ++f)
543 if (f->events & G_IO_IN)
544 FD_SET (f->fd, &rset);
545 if (f->events & G_IO_OUT)
546 FD_SET (f->fd, &wset);
547 if (f->events & G_IO_PRI)
548 FD_SET (f->fd, &xset);
549 if (f->fd > maxfd && (f->events & (G_IO_IN|G_IO_OUT|G_IO_PRI)))
553 tv.tv_sec = timeout / 1000;
554 tv.tv_usec = (timeout % 1000) * 1000;
556 ready = select (maxfd + 1, &rset, &wset, &xset,
557 timeout == -1 ? NULL : &tv);
559 for (f = fds; f < &fds[nfds]; ++f)
564 if (FD_ISSET (f->fd, &rset))
565 f->revents |= G_IO_IN;
566 if (FD_ISSET (f->fd, &wset))
567 f->revents |= G_IO_OUT;
568 if (FD_ISSET (f->fd, &xset))
569 f->revents |= G_IO_PRI;
576 #endif /* !G_OS_WIN32 */
578 #endif /* !HAVE_POLL */
581 * g_main_context_ref:
582 * @context: a #GMainContext
584 * Increases the reference count on a #GMainContext object by one.
587 g_main_context_ref (GMainContext *context)
589 g_return_if_fail (context != NULL);
590 g_return_if_fail (context->ref_count > 0);
592 LOCK_CONTEXT (context);
594 context->ref_count++;
596 UNLOCK_CONTEXT (context);
599 /* If DISABLE_MEM_POOLS is defined, then freeing the
600 * mem chunk won't free the records, so we have to
601 * do it manually. The conditionalization here is
602 * an optimization; g_mem_chunk_free() is a no-op
603 * when DISABLE_MEM_POOLS is set.
605 #ifdef DISABLE_MEM_POOLS
607 poll_rec_list_free (GMainContext *context,
612 GPollRec *tmp_rec = list;
614 g_chunk_free (tmp_rec, context->poll_chunk);
617 #endif /* DISABLE_MEM_POOLS */
620 g_main_context_unref_and_unlock (GMainContext *context)
624 context->ref_count--;
626 if (context->ref_count != 0)
628 UNLOCK_CONTEXT (context);
632 G_LOCK (main_context_list);
633 main_context_list = g_slist_remove (main_context_list, context);
634 G_UNLOCK (main_context_list);
636 source = context->source_list;
639 GSource *next = source->next;
640 g_source_destroy_internal (source, context, TRUE);
643 UNLOCK_CONTEXT (context);
645 #ifdef G_THREADS_ENABLED
646 g_static_mutex_free (&context->mutex);
649 g_ptr_array_free (context->pending_dispatches, TRUE);
650 g_free (context->cached_poll_array);
652 #ifdef DISABLE_MEM_POLLS
653 poll_rec_list_free (context, context->poll_records);
654 poll_rec_list_free (context, context->poll_free_list);
655 #endif /* DISABLE_MEM_POOLS */
657 if (context->poll_chunk)
658 g_mem_chunk_destroy (context->poll_chunk);
660 #ifdef G_THREADS_ENABLED
661 if (g_thread_supported())
664 close (context->wake_up_pipe[0]);
665 close (context->wake_up_pipe[1]);
667 CloseHandle (context->wake_up_semaphore);
671 main_contexts_without_pipe = g_slist_remove (main_contexts_without_pipe,
679 * g_main_context_unref:
680 * @context: a #GMainContext
682 * Decreases the reference count on a #GMainContext object by one. If
683 * the result is zero, free the context and free all associated memory.
686 g_main_context_unref (GMainContext *context)
688 g_return_if_fail (context != NULL);
689 g_return_if_fail (context->ref_count > 0);
691 LOCK_CONTEXT (context);
692 g_main_context_unref_and_unlock (context);
695 #ifdef G_THREADS_ENABLED
697 g_main_context_init_pipe (GMainContext *context)
700 if (context->wake_up_pipe[0] != -1)
702 if (pipe (context->wake_up_pipe) < 0)
703 g_error ("Cannot create pipe main loop wake-up: %s\n",
706 context->wake_up_rec.fd = context->wake_up_pipe[0];
707 context->wake_up_rec.events = G_IO_IN;
709 if (context->wake_up_semaphore != NULL)
711 context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
712 if (context->wake_up_semaphore == NULL)
713 g_error ("Cannot create wake-up semaphore: %s",
714 g_win32_error_message (GetLastError ()));
715 context->wake_up_rec.fd = (gint) context->wake_up_semaphore;
716 context->wake_up_rec.events = G_IO_IN;
717 # ifdef G_MAIN_POLL_DEBUG
718 g_print ("wake-up semaphore: %#x\n", (guint) context->wake_up_semaphore);
721 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
725 _g_main_thread_init ()
727 GSList *curr = main_contexts_without_pipe;
730 g_main_context_init_pipe ((GMainContext *)curr->data);
733 g_slist_free (main_contexts_without_pipe);
734 main_contexts_without_pipe = NULL;
736 #endif /* G_THREADS_ENABLED */
739 * g_main_context_new:
741 * Creates a new #GMainContext strcuture
743 * Return value: the new #GMainContext
746 g_main_context_new ()
748 GMainContext *context = g_new0 (GMainContext, 1);
750 #ifdef G_THREADS_ENABLED
751 g_static_mutex_init (&context->mutex);
753 context->owner = NULL;
754 context->waiters = NULL;
757 context->wake_up_pipe[0] = -1;
758 context->wake_up_pipe[1] = -1;
760 context->wake_up_semaphore = NULL;
764 context->ref_count = 1;
766 context->next_id = 1;
768 context->source_list = NULL;
771 context->poll_func = (GPollFunc)poll;
773 context->poll_func = g_poll;
776 context->cached_poll_array = NULL;
777 context->cached_poll_array_size = 0;
779 context->pending_dispatches = g_ptr_array_new ();
781 context->time_is_current = FALSE;
783 #ifdef G_THREADS_ENABLED
784 if (g_thread_supported ())
785 g_main_context_init_pipe (context);
787 main_contexts_without_pipe = g_slist_prepend (main_contexts_without_pipe,
791 G_LOCK (main_context_list);
792 main_context_list = g_slist_append (main_context_list, context);
793 G_UNLOCK (main_context_list);
799 * g_main_context_default:
801 * Returns the default main context. This is the main context used
802 * for main loop functions when a main loop is not explicitly
805 * Return value: the default main context.
808 g_main_context_default (void)
814 if (!default_main_context)
815 default_main_context = g_main_context_new ();
817 G_UNLOCK (main_loop);
819 return default_main_context;
822 /* Hooks for adding to the main loop */
826 * @source_funcs: structure containing functions that implement
827 * the sources behavior.
828 * @struct_size: size of the #GSource structure to create.
830 * Creates a new #GSource structure. The size is specified to
831 * allow creating structures derived from #GSource that contain
832 * additional data. The size passed in must be at least
833 * <literal>sizeof (GSource)</literal>.
835 * The source will not initially be associated with any #GMainContext
836 * and must be added to one with g_source_attach() before it will be
839 * Return value: the newly-created #GSource.
842 g_source_new (GSourceFuncs *source_funcs,
847 g_return_val_if_fail (source_funcs != NULL, NULL);
848 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
850 source = (GSource*) g_malloc0 (struct_size);
852 source->source_funcs = source_funcs;
853 source->ref_count = 1;
855 source->priority = G_PRIORITY_DEFAULT;
857 source->flags = G_HOOK_FLAG_ACTIVE;
859 /* NULL/0 initialization for all other fields */
864 /* Holds context's lock
867 g_source_list_add (GSource *source,
868 GMainContext *context)
870 GSource *tmp_source, *last_source;
873 tmp_source = context->source_list;
874 while (tmp_source && tmp_source->priority <= source->priority)
876 last_source = tmp_source;
877 tmp_source = tmp_source->next;
880 source->next = tmp_source;
882 tmp_source->prev = source;
884 source->prev = last_source;
886 last_source->next = source;
888 context->source_list = source;
891 /* Holds context's lock
894 g_source_list_remove (GSource *source,
895 GMainContext *context)
898 source->prev->next = source->next;
900 context->source_list = source->next;
903 source->next->prev = source->prev;
911 * @source: a #GSource
912 * @context: a #GMainContext (if %NULL, the default context will be used)
914 * Adds a #GSource to a @context so that it will be executed within
917 * Return value: the ID for the source within the #GMainContext
920 g_source_attach (GSource *source,
921 GMainContext *context)
926 g_return_val_if_fail (source->context == NULL, 0);
927 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
930 context = g_main_context_default ();
932 LOCK_CONTEXT (context);
934 source->context = context;
935 result = source->source_id = context->next_id++;
938 g_source_list_add (source, context);
940 tmp_list = source->poll_fds;
943 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
944 tmp_list = tmp_list->next;
947 #ifdef G_THREADS_ENABLED
948 /* Now wake up the main loop if it is waiting in the poll() */
949 g_main_context_wakeup_unlocked (context);
952 UNLOCK_CONTEXT (context);
958 g_source_destroy_internal (GSource *source,
959 GMainContext *context,
963 LOCK_CONTEXT (context);
965 if (!SOURCE_DESTROYED (source))
968 gpointer old_cb_data;
969 GSourceCallbackFuncs *old_cb_funcs;
971 source->flags &= ~G_HOOK_FLAG_ACTIVE;
973 old_cb_data = source->callback_data;
974 old_cb_funcs = source->callback_funcs;
976 source->callback_data = NULL;
977 source->callback_funcs = NULL;
981 UNLOCK_CONTEXT (context);
982 old_cb_funcs->unref (old_cb_data);
983 LOCK_CONTEXT (context);
986 tmp_list = source->poll_fds;
989 g_main_context_remove_poll_unlocked (context, tmp_list->data);
990 tmp_list = tmp_list->next;
993 g_source_unref_internal (source, context, TRUE);
997 UNLOCK_CONTEXT (context);
1002 * @source: a #GSource
1004 * Removes a source from its #GMainContext, if any, and mark it as
1005 * destroyed. The source cannot be subsequently added to another
1009 g_source_destroy (GSource *source)
1011 GMainContext *context;
1013 g_return_if_fail (source != NULL);
1015 context = source->context;
1018 g_source_destroy_internal (source, context, FALSE);
1020 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1025 * @source: a #GSource
1027 * Returns the numeric ID for a particular source. The ID of a source
1028 * is unique within a particular main loop context. The reverse
1029 * mapping from ID to source is done by g_main_context_find_source_by_id().
1031 * Return value: the ID for the source
1034 g_source_get_id (GSource *source)
1038 g_return_val_if_fail (source != NULL, 0);
1039 g_return_val_if_fail (source->context != NULL, 0);
1041 LOCK_CONTEXT (source->context);
1042 result = source->source_id;
1043 UNLOCK_CONTEXT (source->context);
1049 * g_source_get_context:
1050 * @source: a #GSource
1052 * Gets the #GMainContext with which the source is associated.
1053 * Calling this function on a destroyed source is an error.
1055 * Return value: the #GMainContext with which the source is associated,
1056 * or %NULL if the context has not yet been added
1060 g_source_get_context (GSource *source)
1062 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1064 return source->context;
1068 * g_source_add_poll:
1069 * @source:a #GSource
1070 * @fd: a #GPollFD structure holding information about a file
1071 * descriptor to watch.
1073 * Adds a file descriptor to the set of file descriptors polled for
1074 * this source. This is usually combined with g_source_new() to add an
1075 * event source. The event source's check function will typically test
1076 * the @revents field in the #GPollFD struct and return %TRUE if events need
1080 g_source_add_poll (GSource *source,
1083 GMainContext *context;
1085 g_return_if_fail (source != NULL);
1086 g_return_if_fail (fd != NULL);
1087 g_return_if_fail (!SOURCE_DESTROYED (source));
1089 context = source->context;
1092 LOCK_CONTEXT (context);
1094 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1098 g_main_context_add_poll_unlocked (context, source->priority, fd);
1099 UNLOCK_CONTEXT (context);
1104 * g_source_remove_poll:
1105 * @source:a #GSource
1106 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1108 * Removes a file descriptor from the set of file descriptors polled for
1112 g_source_remove_poll (GSource *source,
1115 GMainContext *context;
1117 g_return_if_fail (source != NULL);
1118 g_return_if_fail (fd != NULL);
1119 g_return_if_fail (!SOURCE_DESTROYED (source));
1121 context = source->context;
1124 LOCK_CONTEXT (context);
1126 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1130 g_main_context_remove_poll_unlocked (context, fd);
1131 UNLOCK_CONTEXT (context);
1136 * g_source_set_callback_indirect:
1137 * @source: the source
1138 * @callback_data: pointer to callback data "object"
1139 * @callback_funcs: functions for reference counting @callback_data
1140 * and getting the callback and data
1142 * Sets the callback function storing the data as a refcounted callback
1143 * "object". This is used internally. Note that calling
1144 * g_source_set_callback_indirect() assumes
1145 * an initial reference count on @callback_data, and thus
1146 * @callback_funcs->unref will eventually be called once more
1147 * than @callback_funcs->ref.
1150 g_source_set_callback_indirect (GSource *source,
1151 gpointer callback_data,
1152 GSourceCallbackFuncs *callback_funcs)
1154 GMainContext *context;
1155 gpointer old_cb_data;
1156 GSourceCallbackFuncs *old_cb_funcs;
1158 g_return_if_fail (source != NULL);
1159 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1161 context = source->context;
1164 LOCK_CONTEXT (context);
1166 old_cb_data = source->callback_data;
1167 old_cb_funcs = source->callback_funcs;
1169 source->callback_data = callback_data;
1170 source->callback_funcs = callback_funcs;
1173 UNLOCK_CONTEXT (context);
1176 old_cb_funcs->unref (old_cb_data);
1180 g_source_callback_ref (gpointer cb_data)
1182 GSourceCallback *callback = cb_data;
1184 callback->ref_count++;
1189 g_source_callback_unref (gpointer cb_data)
1191 GSourceCallback *callback = cb_data;
1193 callback->ref_count--;
1194 if (callback->ref_count == 0)
1196 if (callback->notify)
1197 callback->notify (callback->data);
1203 g_source_callback_get (gpointer cb_data,
1208 GSourceCallback *callback = cb_data;
1210 *func = callback->func;
1211 *data = callback->data;
1214 static GSourceCallbackFuncs g_source_callback_funcs = {
1215 g_source_callback_ref,
1216 g_source_callback_unref,
1217 g_source_callback_get,
1221 * g_source_set_callback:
1222 * @source: the source
1223 * @func: a callback function
1224 * @data: the data to pass to callback function
1225 * @notify: a function to call when @data is no longer in use, or %NULL.
1227 * Sets the callback function for a source. The callback for a source is
1228 * called from the source's dispatch function.
1230 * The exact type of @func depends on the type of source; ie. you
1231 * should not count on @func being called with @data as its first
1234 * Typically, you won't use this function. Instead use functions specific
1235 * to the type of source you are using.
1238 g_source_set_callback (GSource *source,
1241 GDestroyNotify notify)
1243 GSourceCallback *new_callback;
1245 g_return_if_fail (source != NULL);
1247 new_callback = g_new (GSourceCallback, 1);
1249 new_callback->ref_count = 1;
1250 new_callback->func = func;
1251 new_callback->data = data;
1252 new_callback->notify = notify;
1254 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1258 * g_source_set_priority:
1259 * @source: a #GSource
1260 * @priority: the new priority.
1262 * Sets the priority of a source. While the main loop is being
1263 * run, a source will be dispatched if it is ready to be dispatched and no sources
1264 * at a higher (numerically smaller) priority are ready to be dispatched.
1267 g_source_set_priority (GSource *source,
1271 GMainContext *context;
1273 g_return_if_fail (source != NULL);
1275 context = source->context;
1278 LOCK_CONTEXT (context);
1280 source->priority = priority;
1284 source->next = NULL;
1285 source->prev = NULL;
1287 tmp_list = source->poll_fds;
1290 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1291 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1293 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 */
1720 /* HOLDS: context's lock */
1722 g_main_dispatch (GMainContext *context)
1726 for (i = 0; i < context->pending_dispatches->len; i++)
1728 GSource *source = context->pending_dispatches->pdata[i];
1730 context->pending_dispatches->pdata[i] = NULL;
1733 source->flags &= ~G_SOURCE_READY;
1735 if (!SOURCE_DESTROYED (source))
1737 gboolean was_in_call;
1738 gpointer user_data = NULL;
1739 GSourceFunc callback = NULL;
1740 GSourceCallbackFuncs *cb_funcs;
1742 gboolean need_destroy;
1744 gboolean (*dispatch) (GSource *,
1748 dispatch = source->source_funcs->dispatch;
1749 cb_funcs = source->callback_funcs;
1750 cb_data = source->callback_data;
1753 cb_funcs->ref (cb_data);
1755 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
1756 source->flags |= G_HOOK_FLAG_IN_CALL;
1759 cb_funcs->get (cb_data, source, &callback, &user_data);
1761 UNLOCK_CONTEXT (context);
1763 need_destroy = ! dispatch (source,
1766 LOCK_CONTEXT (context);
1769 cb_funcs->unref (cb_data);
1772 source->flags &= ~G_HOOK_FLAG_IN_CALL;
1774 /* Note: this depends on the fact that we can't switch
1775 * sources from one main context to another
1777 if (need_destroy && !SOURCE_DESTROYED (source))
1779 g_assert (source->context == context);
1780 g_source_destroy_internal (source, context, TRUE);
1784 SOURCE_UNREF (source, context);
1787 g_ptr_array_set_size (context->pending_dispatches, 0);
1790 /* Holds context's lock */
1791 static inline GSource *
1792 next_valid_source (GMainContext *context,
1795 GSource *new_source = source ? source->next : context->source_list;
1799 if (!SOURCE_DESTROYED (new_source))
1801 new_source->ref_count++;
1805 new_source = new_source->next;
1809 SOURCE_UNREF (source, context);
1815 * g_main_context_acquire:
1816 * @context: a #GMainContext
1818 * Tries to become the owner of the specified context.
1819 * If some other context is the owner of the context,
1820 * returns %FALSE immediately. Ownership is properly
1821 * recursive: the owner can require ownership again
1822 * and will release ownership when g_main_context_release()
1823 * is called as many times as g_main_context_acquire().
1825 * You must be the owner of a context before you
1826 * can call g_main_context_prepare(), g_main_context_query(),
1827 * g_main_context_check(), g_main_context_dispatch().
1829 * Return value: %TRUE if the operation succeeded, and
1830 * this thread is now the owner of @context.
1833 g_main_context_acquire (GMainContext *context)
1835 #ifdef G_THREADS_ENABLED
1836 gboolean result = FALSE;
1837 GThread *self = G_THREAD_SELF;
1839 if (context == NULL)
1840 context = g_main_context_default ();
1842 LOCK_CONTEXT (context);
1844 if (!context->owner)
1846 context->owner = self;
1847 g_assert (context->owner_count == 0);
1850 if (context->owner == self)
1852 context->owner_count++;
1856 UNLOCK_CONTEXT (context);
1859 #else /* !G_THREADS_ENABLED */
1861 #endif /* G_THREADS_ENABLED */
1865 * g_main_context_release:
1866 * @context: a #GMainContext
1868 * Releases ownership of a context previously acquired by this thread
1869 * with g_main_context_acquire(). If the context was acquired multiple
1870 * times, the only release ownership when g_main_context_release()
1871 * is called as many times as it was acquired.
1874 g_main_context_release (GMainContext *context)
1876 #ifdef G_THREADS_ENABLED
1877 if (context == NULL)
1878 context = g_main_context_default ();
1880 LOCK_CONTEXT (context);
1882 context->owner_count--;
1883 if (context->owner_count == 0)
1885 context->owner = NULL;
1887 if (context->waiters)
1889 GMainWaiter *waiter = context->waiters->data;
1890 gboolean loop_internal_waiter =
1891 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
1892 context->waiters = g_slist_delete_link (context->waiters,
1894 if (!loop_internal_waiter)
1895 g_mutex_lock (waiter->mutex);
1897 g_cond_signal (waiter->cond);
1899 if (!loop_internal_waiter)
1900 g_mutex_unlock (waiter->mutex);
1904 UNLOCK_CONTEXT (context);
1905 #endif /* G_THREADS_ENABLED */
1909 * g_main_context_wait:
1910 * @context: a #GMainContext
1911 * @cond: a condition variable
1912 * @mutex: a mutex, currently held
1914 * Tries to become the owner of the specified context,
1915 * as with g_main_context_acquire(). But if another thread
1916 * is the owner, atomically drop @mutex and wait on @cond until
1917 * that owner releases ownership or until @cond is signaled, then
1918 * try again (once) to become the owner.
1920 * Return value: %TRUE if the operation succeeded, and
1921 * this thread is now the owner of @context.
1924 g_main_context_wait (GMainContext *context,
1928 #ifdef G_THREADS_ENABLED
1929 gboolean result = FALSE;
1930 GThread *self = G_THREAD_SELF;
1931 gboolean loop_internal_waiter;
1933 if (context == NULL)
1934 context = g_main_context_default ();
1936 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
1938 if (!loop_internal_waiter)
1939 LOCK_CONTEXT (context);
1941 if (context->owner && context->owner != self)
1946 waiter.mutex = mutex;
1948 context->waiters = g_slist_append (context->waiters, &waiter);
1950 if (!loop_internal_waiter)
1951 UNLOCK_CONTEXT (context);
1952 g_cond_wait (cond, mutex);
1953 if (!loop_internal_waiter)
1954 LOCK_CONTEXT (context);
1956 context->waiters = g_slist_remove (context->waiters, &waiter);
1959 if (!context->owner)
1961 context->owner = self;
1962 g_assert (context->owner_count == 0);
1965 if (context->owner == self)
1967 context->owner_count++;
1971 if (!loop_internal_waiter)
1972 UNLOCK_CONTEXT (context);
1975 #else /* !G_THREADS_ENABLED */
1977 #endif /* G_THREADS_ENABLED */
1981 * g_main_context_prepare:
1982 * @context: a #GMainContext
1983 * @priority: location to store priority of highest priority
1984 * source already ready.
1986 * Prepares to poll sources within a main loop. The resulting information
1987 * for polling is determined by calling g_main_context_query ().
1989 * Return value: %TRUE if some source is ready to be dispatched
1993 g_main_context_prepare (GMainContext *context,
1998 gint current_priority = G_MAXINT;
2001 if (context == NULL)
2002 context = g_main_context_default ();
2004 LOCK_CONTEXT (context);
2006 context->time_is_current = FALSE;
2008 if (context->in_check_or_prepare)
2010 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2011 "prepare() member.");
2012 UNLOCK_CONTEXT (context);
2016 #ifdef G_THREADS_ENABLED
2017 if (context->poll_waiting)
2019 g_warning("g_main_context_prepare(): main loop already active in another thread");
2020 UNLOCK_CONTEXT (context);
2024 context->poll_waiting = TRUE;
2025 #endif /* G_THREADS_ENABLED */
2028 /* If recursing, finish up current dispatch, before starting over */
2029 if (context->pending_dispatches)
2032 g_main_dispatch (context, ¤t_time);
2034 UNLOCK_CONTEXT (context);
2039 /* If recursing, clear list of pending dispatches */
2041 for (i = 0; i < context->pending_dispatches->len; i++)
2043 if (context->pending_dispatches->pdata[i])
2044 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2046 g_ptr_array_set_size (context->pending_dispatches, 0);
2048 /* Prepare all sources */
2050 context->timeout = -1;
2052 source = next_valid_source (context, NULL);
2055 gint source_timeout = -1;
2057 if ((n_ready > 0) && (source->priority > current_priority))
2059 SOURCE_UNREF (source, context);
2062 if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
2065 if (!(source->flags & G_SOURCE_READY))
2068 gboolean (*prepare) (GSource *source,
2071 prepare = source->source_funcs->prepare;
2072 context->in_check_or_prepare++;
2073 UNLOCK_CONTEXT (context);
2075 result = (*prepare) (source, &source_timeout);
2077 LOCK_CONTEXT (context);
2078 context->in_check_or_prepare--;
2081 source->flags |= G_SOURCE_READY;
2084 if (source->flags & G_SOURCE_READY)
2087 current_priority = source->priority;
2088 context->timeout = 0;
2091 if (source_timeout >= 0)
2093 if (context->timeout < 0)
2094 context->timeout = source_timeout;
2096 context->timeout = MIN (context->timeout, source_timeout);
2100 source = next_valid_source (context, source);
2103 UNLOCK_CONTEXT (context);
2106 *priority = current_priority;
2108 return (n_ready > 0);
2112 * g_main_context_query:
2113 * @context: a #GMainContext
2114 * @max_priority: maximum priority source to check
2115 * @timeout_: location to store timeout to be used in polling
2116 * @fds: location to store #GPollFD records that need to be polled.
2117 * @n_fds: length of @fds.
2119 * Determines information necessary to poll this main loop.
2121 * Return value: the number of records actually stored in @fds,
2122 * or, if more than @n_fds records need to be stored, the number
2123 * of records that need to be stored.
2126 g_main_context_query (GMainContext *context,
2135 LOCK_CONTEXT (context);
2137 pollrec = context->poll_records;
2139 while (pollrec && max_priority >= pollrec->priority)
2141 if (pollrec->fd->events)
2145 fds[n_poll].fd = pollrec->fd->fd;
2146 /* In direct contradiction to the Unix98 spec, IRIX runs into
2147 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2148 * flags in the events field of the pollfd while it should
2149 * just ignoring them. So we mask them out here.
2151 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2152 fds[n_poll].revents = 0;
2157 pollrec = pollrec->next;
2160 #ifdef G_THREADS_ENABLED
2161 context->poll_changed = FALSE;
2166 *timeout = context->timeout;
2168 context->time_is_current = FALSE;
2171 UNLOCK_CONTEXT (context);
2177 * g_main_context_check:
2178 * @context: a #GMainContext
2179 * @max_priority: the maximum numerical priority of sources to check
2180 * @fds: array of #GPollFD's that was passed to the last call to
2181 * g_main_context_query()
2182 * @n_fds: return value of g_main_context_query()
2184 * Passes the results of polling back to the main loop.
2186 * Return value: %TRUE if some sources are ready to be dispatched.
2189 g_main_context_check (GMainContext *context,
2199 LOCK_CONTEXT (context);
2201 if (context->in_check_or_prepare)
2203 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2204 "prepare() member.");
2205 UNLOCK_CONTEXT (context);
2209 #ifdef G_THREADS_ENABLED
2210 if (!context->poll_waiting)
2214 read (context->wake_up_pipe[0], &a, 1);
2218 context->poll_waiting = FALSE;
2220 /* If the set of poll file descriptors changed, bail out
2221 * and let the main loop rerun
2223 if (context->poll_changed)
2225 UNLOCK_CONTEXT (context);
2228 #endif /* G_THREADS_ENABLED */
2230 pollrec = context->poll_records;
2234 if (pollrec->fd->events)
2236 pollrec->fd->revents = fds[i].revents;
2239 pollrec = pollrec->next;
2242 source = next_valid_source (context, NULL);
2245 if ((n_ready > 0) && (source->priority > max_priority))
2247 SOURCE_UNREF (source, context);
2250 if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
2253 if (!(source->flags & G_SOURCE_READY))
2256 gboolean (*check) (GSource *source);
2258 check = source->source_funcs->check;
2260 context->in_check_or_prepare++;
2261 UNLOCK_CONTEXT (context);
2263 result = (*check) (source);
2265 LOCK_CONTEXT (context);
2266 context->in_check_or_prepare--;
2269 source->flags |= G_SOURCE_READY;
2272 if (source->flags & G_SOURCE_READY)
2274 source->ref_count++;
2275 g_ptr_array_add (context->pending_dispatches, source);
2279 /* never dispatch sources with less priority than the first
2280 * one we choose to dispatch
2282 max_priority = source->priority;
2286 source = next_valid_source (context, source);
2289 UNLOCK_CONTEXT (context);
2295 * g_main_context_dispatch:
2296 * @context: a #GMainContext
2298 * Dispatches all pending sources.
2301 g_main_context_dispatch (GMainContext *context)
2303 LOCK_CONTEXT (context);
2305 if (context->pending_dispatches->len > 0)
2307 g_main_dispatch (context);
2310 UNLOCK_CONTEXT (context);
2313 /* HOLDS context lock */
2315 g_main_context_iterate (GMainContext *context,
2322 gboolean some_ready;
2323 gint nfds, allocated_nfds;
2324 GPollFD *fds = NULL;
2326 UNLOCK_CONTEXT (context);
2328 #ifdef G_THREADS_ENABLED
2329 if (!g_main_context_acquire (context))
2331 gboolean got_ownership;
2333 g_return_val_if_fail (g_thread_supported (), FALSE);
2338 LOCK_CONTEXT (context);
2341 context->cond = g_cond_new ();
2343 got_ownership = g_main_context_wait (context,
2345 g_static_mutex_get_mutex (&context->mutex));
2349 UNLOCK_CONTEXT (context);
2354 LOCK_CONTEXT (context);
2355 #endif /* G_THREADS_ENABLED */
2357 if (!context->cached_poll_array)
2359 context->cached_poll_array_size = context->n_poll_records;
2360 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2363 allocated_nfds = context->cached_poll_array_size;
2364 fds = context->cached_poll_array;
2366 UNLOCK_CONTEXT (context);
2368 g_main_context_prepare (context, &max_priority);
2370 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
2371 allocated_nfds)) > allocated_nfds)
2373 LOCK_CONTEXT (context);
2375 context->cached_poll_array_size = allocated_nfds = nfds;
2376 context->cached_poll_array = fds = g_new (GPollFD, nfds);
2377 UNLOCK_CONTEXT (context);
2383 g_main_context_poll (context, timeout, max_priority, fds, nfds);
2385 some_ready = g_main_context_check (context, max_priority, fds, nfds);
2388 g_main_context_dispatch (context);
2390 #ifdef G_THREADS_ENABLED
2391 g_main_context_release (context);
2392 #endif /* G_THREADS_ENABLED */
2394 LOCK_CONTEXT (context);
2400 * g_main_context_pending:
2401 * @context: a #GMainContext (if %NULL, the default context will be used)
2403 * Checks if any sources have pending events for the given context.
2405 * Return value: %TRUE if events are pending.
2408 g_main_context_pending (GMainContext *context)
2413 context = g_main_context_default();
2415 LOCK_CONTEXT (context);
2416 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
2417 UNLOCK_CONTEXT (context);
2423 * g_main_context_iteration:
2424 * @context: a #GMainContext (if %NULL, the default context will be used)
2425 * @may_block: whether the call may block.
2427 * Runs a single iteration for the given main loop. This involves
2428 * checking to see if any event sources are ready to be processed,
2429 * then if no events sources are ready and @may_block is %TRUE, waiting
2430 * for a source to become ready, then dispatching the highest priority
2431 * events sources that are ready. Note that even when @may_block is %TRUE,
2432 * it is still possible for g_main_context_iteration() to return
2433 * %FALSE, since the the wait may be interrupted for other
2434 * reasons than an event source becoming ready.
2436 * Return value: %TRUE if events were dispatched.
2439 g_main_context_iteration (GMainContext *context, gboolean may_block)
2444 context = g_main_context_default();
2446 LOCK_CONTEXT (context);
2447 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
2448 UNLOCK_CONTEXT (context);
2455 * @context: a #GMainContext (if %NULL, the default context will be used).
2456 * @is_running: set to %TRUE to indicate that the loop is running. This
2457 * is not very important since calling g_main_loop_run() will set this to
2460 * Creates a new #GMainLoop structure.
2462 * Return value: a new #GMainLoop.
2465 g_main_loop_new (GMainContext *context,
2466 gboolean is_running)
2471 context = g_main_context_default();
2473 g_main_context_ref (context);
2475 loop = g_new0 (GMainLoop, 1);
2476 loop->context = context;
2477 loop->is_running = is_running != FALSE;
2478 loop->ref_count = 1;
2485 * @loop: a #GMainLoop
2487 * Increases the reference count on a #GMainLoop object by one.
2489 * Return value: @loop
2492 g_main_loop_ref (GMainLoop *loop)
2494 g_return_val_if_fail (loop != NULL, NULL);
2495 g_return_val_if_fail (loop->ref_count > 0, NULL);
2497 LOCK_CONTEXT (loop->context);
2499 UNLOCK_CONTEXT (loop->context);
2505 g_main_loop_unref_and_unlock (GMainLoop *loop)
2508 if (loop->ref_count == 0)
2510 /* When the ref_count is 0, there can be nobody else using the
2511 * loop, so it is safe to unlock before destroying.
2513 g_main_context_unref_and_unlock (loop->context);
2517 UNLOCK_CONTEXT (loop->context);
2521 * g_main_loop_unref:
2522 * @loop: a #GMainLoop
2524 * Decreases the reference count on a #GMainLoop object by one. If
2525 * the result is zero, free the loop and free all associated memory.
2528 g_main_loop_unref (GMainLoop *loop)
2530 g_return_if_fail (loop != NULL);
2531 g_return_if_fail (loop->ref_count > 0);
2533 LOCK_CONTEXT (loop->context);
2535 g_main_loop_unref_and_unlock (loop);
2540 * @loop: a #GMainLoop
2542 * Runs a main loop until g_main_loop_quit() is called on the loop.
2543 * If this is called for the thread of the loop's #GMainContext,
2544 * it will process events from the loop, otherwise it will
2548 g_main_loop_run (GMainLoop *loop)
2550 GThread *self = G_THREAD_SELF;
2552 g_return_if_fail (loop != NULL);
2553 g_return_if_fail (loop->ref_count > 0);
2555 #ifdef G_THREADS_ENABLED
2556 if (!g_main_context_acquire (loop->context))
2558 gboolean got_ownership = FALSE;
2560 /* Another thread owns this context */
2561 if (!g_thread_supported ())
2563 g_warning ("g_main_loop_run() was called from second thread but "
2564 "g_thread_init() was never called.");
2568 LOCK_CONTEXT (loop->context);
2572 if (!loop->is_running)
2573 loop->is_running = TRUE;
2575 if (!loop->context->cond)
2576 loop->context->cond = g_cond_new ();
2578 while (loop->is_running && !got_ownership)
2579 got_ownership = g_main_context_wait (loop->context,
2580 loop->context->cond,
2581 g_static_mutex_get_mutex (&loop->context->mutex));
2583 if (!loop->is_running)
2585 UNLOCK_CONTEXT (loop->context);
2587 g_main_context_release (loop->context);
2588 g_main_loop_unref (loop);
2592 g_assert (got_ownership);
2595 LOCK_CONTEXT (loop->context);
2596 #endif /* G_THREADS_ENABLED */
2598 if (loop->context->in_check_or_prepare)
2600 g_warning ("g_main_loop_run(): called recursively from within a source's "
2601 "check() or prepare() member, iteration not possible.");
2606 loop->is_running = TRUE;
2607 while (loop->is_running)
2608 g_main_context_iterate (loop->context, TRUE, TRUE, self);
2610 UNLOCK_CONTEXT (loop->context);
2612 #ifdef G_THREADS_ENABLED
2613 g_main_context_release (loop->context);
2614 #endif /* G_THREADS_ENABLED */
2616 g_main_loop_unref (loop);
2621 * @loop: a #GMainLoop
2623 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
2624 * for the loop will return.
2627 g_main_loop_quit (GMainLoop *loop)
2629 g_return_if_fail (loop != NULL);
2630 g_return_if_fail (loop->ref_count > 0);
2632 LOCK_CONTEXT (loop->context);
2633 loop->is_running = FALSE;
2634 g_main_context_wakeup_unlocked (loop->context);
2636 #ifdef G_THREADS_ENABLED
2637 if (loop->context->cond)
2638 g_cond_broadcast (loop->context->cond);
2639 #endif /* G_THREADS_ENABLED */
2641 UNLOCK_CONTEXT (loop->context);
2645 * g_main_loop_is_running:
2646 * @loop: a #GMainLoop.
2648 * Checks to see if the main loop is currently being run via g_main_loop_run().
2650 * Return value: %TRUE if the mainloop is currently being run.
2653 g_main_loop_is_running (GMainLoop *loop)
2655 g_return_val_if_fail (loop != NULL, FALSE);
2656 g_return_val_if_fail (loop->ref_count > 0, FALSE);
2658 return loop->is_running;
2662 * g_main_loop_get_context:
2663 * @loop: a #GMainLoop.
2665 * Returns the #GMainContext of @loop.
2667 * Return value: the #GMainContext of @loop
2670 g_main_loop_get_context (GMainLoop *loop)
2672 g_return_val_if_fail (loop != NULL, NULL);
2673 g_return_val_if_fail (loop->ref_count > 0, NULL);
2675 return loop->context;
2678 /* HOLDS: context's lock */
2680 g_main_context_poll (GMainContext *context,
2686 #ifdef G_MAIN_POLL_DEBUG
2692 GPollFunc poll_func;
2694 if (n_fds || timeout != 0)
2696 #ifdef G_MAIN_POLL_DEBUG
2697 g_print ("g_main_poll(%d) timeout: %d\n", n_fds, timeout);
2698 poll_timer = g_timer_new ();
2701 LOCK_CONTEXT (context);
2703 poll_func = context->poll_func;
2705 UNLOCK_CONTEXT (context);
2706 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
2709 g_warning ("poll(2) failed due to: %s.",
2710 g_strerror (errno));
2712 /* If g_poll () returns -1, it has already called g_warning() */
2716 #ifdef G_MAIN_POLL_DEBUG
2717 LOCK_CONTEXT (context);
2719 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
2722 g_timer_elapsed (poll_timer, NULL));
2723 g_timer_destroy (poll_timer);
2724 pollrec = context->poll_records;
2728 if (pollrec->fd->events)
2732 g_print (" [%d:", fds[i].fd);
2733 if (fds[i].revents & G_IO_IN)
2735 if (fds[i].revents & G_IO_OUT)
2737 if (fds[i].revents & G_IO_PRI)
2739 if (fds[i].revents & G_IO_ERR)
2741 if (fds[i].revents & G_IO_HUP)
2743 if (fds[i].revents & G_IO_NVAL)
2749 pollrec = pollrec->next;
2753 UNLOCK_CONTEXT (context);
2755 } /* if (n_fds || timeout != 0) */
2759 * g_main_context_add_poll:
2760 * @context: a #GMainContext (or %NULL for the default context)
2761 * @fd: a #GPollFD structure holding information about a file
2762 * descriptor to watch.
2763 * @priority: the priority for this file descriptor which should be
2764 * the same as the priority used for g_source_attach() to ensure that the
2765 * file descriptor is polled whenever the results may be needed.
2767 * Adds a file descriptor to the set of file descriptors polled for
2768 * this context. This will very seldomly be used directly. Instead
2769 * a typical event source will use g_source_add_poll() instead.
2772 g_main_context_add_poll (GMainContext *context,
2777 context = g_main_context_default ();
2779 g_return_if_fail (context->ref_count > 0);
2780 g_return_if_fail (fd);
2782 LOCK_CONTEXT (context);
2783 g_main_context_add_poll_unlocked (context, priority, fd);
2784 UNLOCK_CONTEXT (context);
2787 /* HOLDS: main_loop_lock */
2789 g_main_context_add_poll_unlocked (GMainContext *context,
2793 GPollRec *lastrec, *pollrec, *newrec;
2795 if (!context->poll_chunk)
2796 context->poll_chunk = g_mem_chunk_create (GPollRec, 32, G_ALLOC_ONLY);
2798 if (context->poll_free_list)
2800 newrec = context->poll_free_list;
2801 context->poll_free_list = newrec->next;
2804 newrec = g_chunk_new (GPollRec, context->poll_chunk);
2806 /* This file descriptor may be checked before we ever poll */
2809 newrec->priority = priority;
2812 pollrec = context->poll_records;
2813 while (pollrec && priority >= pollrec->priority)
2816 pollrec = pollrec->next;
2820 lastrec->next = newrec;
2822 context->poll_records = newrec;
2824 newrec->next = pollrec;
2826 context->n_poll_records++;
2828 #ifdef G_THREADS_ENABLED
2829 context->poll_changed = TRUE;
2831 /* Now wake up the main loop if it is waiting in the poll() */
2832 g_main_context_wakeup_unlocked (context);
2837 * g_main_context_remove_poll:
2838 * @context:a #GMainContext
2839 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
2841 * Removes file descriptor from the set of file descriptors to be
2842 * polled for a particular context.
2845 g_main_context_remove_poll (GMainContext *context,
2849 context = g_main_context_default ();
2851 g_return_if_fail (context->ref_count > 0);
2852 g_return_if_fail (fd);
2854 LOCK_CONTEXT (context);
2855 g_main_context_remove_poll_unlocked (context, fd);
2856 UNLOCK_CONTEXT (context);
2860 g_main_context_remove_poll_unlocked (GMainContext *context,
2863 GPollRec *pollrec, *lastrec;
2866 pollrec = context->poll_records;
2870 if (pollrec->fd == fd)
2872 if (lastrec != NULL)
2873 lastrec->next = pollrec->next;
2875 context->poll_records = pollrec->next;
2877 #ifdef ENABLE_GC_FRIENDLY
2879 #endif /* ENABLE_GC_FRIENDLY */
2881 pollrec->next = context->poll_free_list;
2882 context->poll_free_list = pollrec;
2884 context->n_poll_records--;
2888 pollrec = pollrec->next;
2891 #ifdef G_THREADS_ENABLED
2892 context->poll_changed = TRUE;
2894 /* Now wake up the main loop if it is waiting in the poll() */
2895 g_main_context_wakeup_unlocked (context);
2900 * g_source_get_current_time:
2901 * @source: a #GSource
2902 * @timeval: #GTimeVal structure in which to store current time.
2904 * Gets the "current time" to be used when checking
2905 * this source. The advantage of calling this function over
2906 * calling g_get_current_time() directly is that when
2907 * checking multiple sources, GLib can cache a single value
2908 * instead of having to repeatedly get the system time.
2911 g_source_get_current_time (GSource *source,
2914 GMainContext *context;
2916 g_return_if_fail (source->context != NULL);
2918 context = source->context;
2920 LOCK_CONTEXT (context);
2922 if (!context->time_is_current)
2924 g_get_current_time (&context->current_time);
2925 context->time_is_current = TRUE;
2928 *timeval = context->current_time;
2930 UNLOCK_CONTEXT (context);
2934 * g_main_context_set_poll_func:
2935 * @context: a #GMainContext
2936 * @func: the function to call to poll all file descriptors
2938 * Sets the function to use to handle polling of file descriptors. It
2939 * will be used instead of the poll() system call
2940 * (or GLib's replacement function, which is used where
2941 * poll() isn't available).
2943 * This function could possibly be used to integrate the GLib event
2944 * loop with an external event loop.
2947 g_main_context_set_poll_func (GMainContext *context,
2951 context = g_main_context_default ();
2953 g_return_if_fail (context->ref_count > 0);
2955 LOCK_CONTEXT (context);
2958 context->poll_func = func;
2962 context->poll_func = (GPollFunc) poll;
2964 context->poll_func = (GPollFunc) g_poll;
2968 UNLOCK_CONTEXT (context);
2972 * g_main_context_get_poll_func:
2973 * @context: a #GMainContext
2975 * Gets the poll function set by g_main_context_set_poll_func().
2977 * Return value: the poll function
2980 g_main_context_get_poll_func (GMainContext *context)
2985 context = g_main_context_default ();
2987 g_return_val_if_fail (context->ref_count > 0, NULL);
2989 LOCK_CONTEXT (context);
2990 result = context->poll_func;
2991 UNLOCK_CONTEXT (context);
2996 /* HOLDS: context's lock */
2997 /* Wake the main loop up from a poll() */
2999 g_main_context_wakeup_unlocked (GMainContext *context)
3001 #ifdef G_THREADS_ENABLED
3002 if (g_thread_supported() && context->poll_waiting)
3004 context->poll_waiting = FALSE;
3006 write (context->wake_up_pipe[1], "A", 1);
3008 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
3015 * g_main_context_wakeup:
3016 * @context: a #GMainContext
3018 * If @context is currently waiting in a poll(), interrupt
3019 * the poll(), and continue the iteration process.
3022 g_main_context_wakeup (GMainContext *context)
3025 context = g_main_context_default ();
3027 g_return_if_fail (context->ref_count > 0);
3029 LOCK_CONTEXT (context);
3030 g_main_context_wakeup_unlocked (context);
3031 UNLOCK_CONTEXT (context);
3037 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3038 GTimeVal *current_time)
3040 guint seconds = timeout_source->interval / 1000;
3041 guint msecs = timeout_source->interval - seconds * 1000;
3043 timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
3044 timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
3045 if (timeout_source->expiration.tv_usec >= 1000000)
3047 timeout_source->expiration.tv_usec -= 1000000;
3048 timeout_source->expiration.tv_sec++;
3053 g_timeout_prepare (GSource *source,
3058 GTimeVal current_time;
3060 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3062 g_source_get_current_time (source, ¤t_time);
3064 sec = timeout_source->expiration.tv_sec - current_time.tv_sec;
3065 msec = (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000;
3067 /* We do the following in a rather convoluted fashion to deal with
3068 * the fact that we don't have an integral type big enough to hold
3069 * the difference of two timevals in millseconds.
3071 if (sec < 0 || (sec == 0 && msec < 0))
3075 glong interval_sec = timeout_source->interval / 1000;
3076 glong interval_msec = timeout_source->interval % 1000;
3084 if (sec > interval_sec ||
3085 (sec == interval_sec && msec > interval_msec))
3087 /* The system time has been set backwards, so we
3088 * reset the expiration time to now + timeout_source->interval;
3089 * this at least avoids hanging for long periods of time.
3091 g_timeout_set_expiration (timeout_source, ¤t_time);
3092 msec = MIN (G_MAXINT, timeout_source->interval);
3096 msec = MIN (G_MAXINT, (guint)msec + 1000 * (guint)sec);
3100 *timeout = (gint)msec;
3106 g_timeout_check (GSource *source)
3108 GTimeVal current_time;
3109 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3111 g_source_get_current_time (source, ¤t_time);
3113 return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
3114 ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
3115 (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
3119 g_timeout_dispatch (GSource *source,
3120 GSourceFunc callback,
3123 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3127 g_warning ("Timeout source dispatched without callback\n"
3128 "You must call g_source_set_callback().");
3132 if (callback (user_data))
3134 GTimeVal current_time;
3136 g_source_get_current_time (source, ¤t_time);
3137 g_timeout_set_expiration (timeout_source, ¤t_time);
3146 * g_timeout_source_new:
3147 * @interval: the timeout interval in milliseconds.
3149 * Creates a new timeout source.
3151 * The source will not initially be associated with any #GMainContext
3152 * and must be added to one with g_source_attach() before it will be
3155 * Return value: the newly-created timeout source
3158 g_timeout_source_new (guint interval)
3160 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3161 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3162 GTimeVal current_time;
3164 timeout_source->interval = interval;
3166 g_get_current_time (¤t_time);
3167 g_timeout_set_expiration (timeout_source, ¤t_time);
3173 * g_timeout_add_full:
3174 * @priority: the priority of the idle source. Typically this will be in the
3175 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3176 * @interval: the time between calls to the function, in milliseconds
3177 * (1/1000ths of a second)
3178 * @function: function to call
3179 * @data: data to pass to @function
3180 * @notify: function to call when the idle is removed, or %NULL
3182 * Sets a function to be called at regular intervals, with the given
3183 * priority. The function is called repeatedly until it returns
3184 * %FALSE, at which point the timeout is automatically destroyed and
3185 * the function will not be called again. The @notify function is
3186 * called when the timeout is destroyed. The first call to the
3187 * function will be at the end of the first @interval.
3189 * Note that timeout functions may be delayed, due to the processing of other
3190 * event sources. Thus they should not be relied on for precise timing.
3191 * After each call to the timeout function, the time of the next
3192 * timeout is recalculated based on the current time and the given interval
3193 * (it does not try to 'catch up' time lost in delays).
3195 * Return value: the id of event source.
3198 g_timeout_add_full (gint priority,
3200 GSourceFunc function,
3202 GDestroyNotify notify)
3207 g_return_val_if_fail (function != NULL, 0);
3209 source = g_timeout_source_new (interval);
3211 if (priority != G_PRIORITY_DEFAULT)
3212 g_source_set_priority (source, priority);
3214 g_source_set_callback (source, function, data, notify);
3215 id = g_source_attach (source, NULL);
3216 g_source_unref (source);
3223 * @interval: the time between calls to the function, in milliseconds
3224 * (1/1000ths of a second)
3225 * @function: function to call
3226 * @data: data to pass to @function
3228 * Sets a function to be called at regular intervals, with the default
3229 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
3230 * until it returns %FALSE, at which point the timeout is automatically
3231 * destroyed and the function will not be called again. The first call
3232 * to the function will be at the end of the first @interval.
3234 * Note that timeout functions may be delayed, due to the processing of other
3235 * event sources. Thus they should not be relied on for precise timing.
3236 * After each call to the timeout function, the time of the next
3237 * timeout is recalculated based on the current time and the given interval
3238 * (it does not try to 'catch up' time lost in delays).
3240 * Return value: the id of event source.
3243 g_timeout_add (guint32 interval,
3244 GSourceFunc function,
3247 return g_timeout_add_full (G_PRIORITY_DEFAULT,
3248 interval, function, data, NULL);
3251 /* Child watch functions */
3254 check_for_child_exited (GSource *source)
3256 GChildWatchSource *child_watch_source;
3259 /* protect against another SIGCHLD in the middle of this call */
3260 count = child_watch_count;
3262 child_watch_source = (GChildWatchSource *) source;
3264 if (child_watch_source->count < count)
3269 if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
3272 if (GetExitCodeProcess (child_watch_source->pid, &child_status) &&
3273 child_status != STILL_ACTIVE)
3276 child_watch_source->child_status = child_status;
3277 child_watch_source->child_exited = TRUE;
3279 child_watch_source->count = count;
3284 g_child_watch_prepare (GSource *source,
3287 GChildWatchSource *child_watch_source;
3290 child_watch_source = (GChildWatchSource *) source;
3292 check_for_child_exited (source);
3294 return child_watch_source->child_exited;
3299 g_child_watch_check (GSource *source)
3301 GChildWatchSource *child_watch_source;
3303 child_watch_source = (GChildWatchSource *) source;
3305 return (child_watch_source->count < child_watch_count);
3309 g_child_watch_dispatch (GSource *source,
3310 GSourceFunc callback,
3313 GChildWatchSource *child_watch_source;
3314 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
3316 child_watch_source = (GChildWatchSource *) source;
3320 g_warning ("Child watch source dispatched without callback\n"
3321 "You must call g_source_set_callback().");
3325 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
3327 /* We never keep a child watch source around as the child is gone */
3332 g_child_watch_signal_handler (int signum)
3334 child_watch_count ++;
3336 if (child_watch_init_state == CHILD_WATCH_INITIALIZED_THREADED)
3339 write (child_watch_wake_up_pipe[1], "B", 1);
3341 ReleaseSemaphore(child_watch_wake_up_semaphore, 1, NULL);
3346 /* We count on the signal interrupting the poll in the same thread.
3352 g_child_watch_source_init_single (void)
3354 g_assert (! g_thread_supported());
3355 g_assert (child_watch_init_state == CHILD_WATCH_UNINITIALIZED);
3357 child_watch_init_state = CHILD_WATCH_INITIALIZED_SINGLE;
3360 signal (SIGCHLD, g_child_watch_signal_handler);
3362 /* FIXME: really nothing to be done ? --hb */
3367 child_watch_helper_thread (gpointer data)
3370 GPollFunc poll_func;
3373 poll_func = (GPollFunc)poll;
3379 fds.fd = child_watch_wake_up_pipe[0];
3380 fds.events = G_IO_IN;
3389 read (child_watch_wake_up_pipe[0], b, 20);
3391 WaitForSingleObject(child_watch_wake_up_semaphore, INFINITE);
3394 /* We were woken up. Wake up all other contexts in all other threads */
3395 G_UNLOCK (main_context_list);
3396 for (list = main_context_list; list; list = list->next)
3398 GMainContext *context;
3400 context = list->data;
3401 g_main_context_wakeup (context);
3403 G_LOCK (main_context_list);
3409 g_child_watch_source_init_multi_threaded (void)
3411 GError *error = NULL;
3413 g_assert (g_thread_supported());
3416 if (pipe (child_watch_wake_up_pipe) < 0)
3417 g_error ("Cannot create wake up pipe: %s\n", g_strerror (errno));
3418 fcntl (child_watch_wake_up_pipe[1], F_SETFL, O_NONBLOCK | fcntl (child_watch_wake_up_pipe[1], F_GETFL));
3420 child_watch_wake_up_semaphore = CreateSemaphore (NULL, 0, G_MAXINT, NULL);
3423 /* We create a helper thread that polls on the wakeup pipe indefinitely */
3424 /* FIXME: Think this through for races */
3425 if (g_thread_create (child_watch_helper_thread, NULL, FALSE, &error) == NULL)
3426 g_error ("Cannot create a thread to monitor child exit status: %s\n", error->message);
3427 child_watch_init_state = CHILD_WATCH_INITIALIZED_THREADED;
3429 signal (SIGCHLD, g_child_watch_signal_handler);
3431 /* FIXME: really nothing to be done ? --hb */
3436 g_child_watch_source_init_promote_single_to_threaded (void)
3438 g_child_watch_source_init_multi_threaded ();
3442 g_child_watch_source_init (void)
3444 if (g_thread_supported())
3446 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
3447 g_child_watch_source_init_multi_threaded ();
3448 else if (child_watch_init_state == CHILD_WATCH_INITIALIZED_SINGLE)
3449 g_child_watch_source_init_promote_single_to_threaded ();
3453 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
3454 g_child_watch_source_init_single ();
3459 * g_child_watch_source_new:
3460 * @pid: process id of a child process to watch
3462 * Creates a new child_watch source.
3464 * The source will not initially be associated with any #GMainContext
3465 * and must be added to one with g_source_attach() before it will be
3468 * Return value: the newly-created child watch source
3473 g_child_watch_source_new (GPid pid)
3475 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
3476 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
3478 g_child_watch_source_init ();
3480 child_watch_source->pid = pid;
3486 * g_child_watch_add_full:
3487 * @priority: the priority of the idle source. Typically this will be in the
3488 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3489 * @pid: process id of a child process to watch
3490 * @function: function to call
3491 * @data: data to pass to @function
3492 * @notify: function to call when the idle is removed, or %NULL
3494 * Sets a function to be called when the child indicated by @pid exits, at a
3495 * default priority, #G_PRIORITY_DEFAULT.
3497 * Return value: the id of event source.
3502 g_child_watch_add_full (gint priority,
3504 GChildWatchFunc function,
3506 GDestroyNotify notify)
3511 g_return_val_if_fail (function != NULL, 0);
3513 source = g_child_watch_source_new (pid);
3515 if (priority != G_PRIORITY_DEFAULT)
3516 g_source_set_priority (source, priority);
3518 g_source_set_callback (source, (GSourceFunc) function, data, notify);
3519 id = g_source_attach (source, NULL);
3520 g_source_unref (source);
3526 * g_child_watch_add:
3527 * @pid: process id of a child process to watch
3528 * @function: function to call
3529 * @data: data to pass to @function
3531 * Sets a function to be called when the child indicated by @pid exits, at a
3532 * default priority, #G_PRIORITY_DEFAULT.
3534 * Return value: the id of event source.
3539 g_child_watch_add (GPid pid,
3540 GChildWatchFunc function,
3543 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
3547 /* Idle functions */
3550 g_idle_prepare (GSource *source,
3559 g_idle_check (GSource *source)
3565 g_idle_dispatch (GSource *source,
3566 GSourceFunc callback,
3571 g_warning ("Idle source dispatched without callback\n"
3572 "You must call g_source_set_callback().");
3576 return callback (user_data);
3580 * g_idle_source_new:
3582 * Creates a new idle source.
3584 * The source will not initially be associated with any #GMainContext
3585 * and must be added to one with g_source_attach() before it will be
3586 * executed. Note that the default priority for idle sources is
3587 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
3588 * have a default priority of %G_PRIORITY_DEFAULT.
3590 * Return value: the newly-created idle source
3593 g_idle_source_new (void)
3597 source = g_source_new (&g_idle_funcs, sizeof (GSource));
3598 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
3605 * @priority: the priority of the idle source. Typically this will be in the
3606 * range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3607 * @function: function to call
3608 * @data: data to pass to @function
3609 * @notify: function to call when the idle is removed, or %NULL
3611 * Adds a function to be called whenever there are no higher priority
3612 * events pending. If the function returns %FALSE it is automatically
3613 * removed from the list of event sources and will not be called again.
3615 * Return value: the id of the event source.
3618 g_idle_add_full (gint priority,
3619 GSourceFunc function,
3621 GDestroyNotify notify)
3626 g_return_val_if_fail (function != NULL, 0);
3628 source = g_idle_source_new ();
3630 if (priority != G_PRIORITY_DEFAULT_IDLE)
3631 g_source_set_priority (source, priority);
3633 g_source_set_callback (source, function, data, notify);
3634 id = g_source_attach (source, NULL);
3635 g_source_unref (source);
3642 * @function: function to call
3643 * @data: data to pass to @function.
3645 * Adds a function to be called whenever there are no higher priority
3646 * events pending to the default main loop. The function is given the
3647 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
3648 * returns %FALSE it is automatically removed from the list of event
3649 * sources and will not be called again.
3651 * Return value: the id of the event source.
3654 g_idle_add (GSourceFunc function,
3657 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
3661 * g_idle_remove_by_data:
3662 * @data: the data for the idle source's callback.
3664 * Removes the idle function with the given data.
3666 * Return value: %TRUE if an idle source was found and removed.
3669 g_idle_remove_by_data (gpointer data)
3671 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);