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 <sys/types.h>
42 #ifdef HAVE_SYS_TIME_H
44 #endif /* HAVE_SYS_TIME_H */
45 #ifdef GLIB_HAVE_SYS_POLL_H
46 # include <sys/poll.h>
47 # undef events /* AIX 4.1.5 & 4.3.2 define this for SVR3,4 compatibility */
48 # undef revents /* AIX 4.1.5 & 4.3.2 define this for SVR3,4 compatibility */
49 #endif /* GLIB_HAVE_SYS_POLL_H */
52 #endif /* HAVE_UNISTD_H */
58 #endif /* G_OS_WIN32 */
61 #include <net/socket.h>
62 #endif /* G_OS_BEOS */
66 typedef struct _GTimeoutSource GTimeoutSource;
67 typedef struct _GPollRec GPollRec;
68 typedef struct _GSourceCallback GSourceCallback;
72 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
73 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
78 #ifdef G_THREADS_ENABLED
79 /* The following lock is used for both the list of sources
80 * and the list of poll records
86 GPtrArray *pending_dispatches;
87 gint timeout; /* Timeout for current iteration */
91 gint in_check_or_prepare;
93 GPollRec *poll_records;
94 GPollRec *poll_free_list;
95 GMemChunk *poll_chunk;
97 GPollFD *cached_poll_array;
98 gint cached_poll_array_size;
100 #ifdef G_THREADS_ENABLED
102 /* this pipe is used to wake up the main loop when a source is added.
104 gint wake_up_pipe[2];
105 #else /* G_OS_WIN32 */
106 HANDLE wake_up_semaphore;
107 #endif /* G_OS_WIN32 */
110 gboolean poll_waiting;
112 /* Flag indicating whether the set of fd's changed during a poll */
113 gboolean poll_changed;
114 #endif /* G_THREADS_ENABLED */
118 GTimeVal current_time;
119 gboolean time_is_current;
122 struct _GSourceCallback
127 GDestroyNotify notify;
132 GMainContext *context;
136 #ifdef G_THREADS_ENABLED
139 #endif /* G_THREADS_ENABLED */
142 struct _GTimeoutSource
156 #ifdef G_THREADS_ENABLED
157 #define LOCK_CONTEXT(context) g_mutex_lock(context->mutex)
158 #define UNLOCK_CONTEXT(context) g_mutex_unlock(context->mutex)
159 #define LOCK_LOOP(loop) g_mutex_lock(loop->mutex)
160 #define UNLOCK_LOOP(loop) g_mutex_unlock(loop->mutex)
162 #define LOCK_CONTEXT(context) (void)0
163 #define UNLOCK_CONTEXT(context) (void)0
164 #define LOCK_LOOP(context) (void)0
165 #define UNLOCK_LOOP(context) (void)0
168 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
170 #define SOURCE_UNREF(source, context) \
172 if ((source)->ref_count > 1) \
173 (source)->ref_count--; \
175 g_source_unref_internal ((source), (context), TRUE); \
179 /* Forward declarations */
181 static void g_source_unref_internal (GSource *source,
182 GMainContext *context,
184 static void g_source_destroy_internal (GSource *source,
185 GMainContext *context,
187 static void g_main_context_poll (GMainContext *context,
192 static void g_main_context_add_poll_unlocked (GMainContext *context,
195 static void g_main_context_remove_poll_unlocked (GMainContext *context,
197 static void g_main_context_wakeup (GMainContext *context);
199 static gboolean g_timeout_prepare (GSource *source,
201 static gboolean g_timeout_check (GSource *source);
202 static gboolean g_timeout_dispatch (GSource *source,
203 GSourceFunc callback,
205 static gboolean g_idle_prepare (GSource *source,
207 static gboolean g_idle_check (GSource *source);
208 static gboolean g_idle_dispatch (GSource *source,
209 GSourceFunc callback,
212 G_LOCK_DEFINE_STATIC (main_loop);
213 static GMainContext *default_main_context;
215 static GSourceFuncs timeout_funcs =
223 static GSourceFuncs idle_funcs =
232 /* SunOS has poll, but doesn't provide a prototype. */
233 # if defined (sun) && !defined (__SVR4)
234 extern gint poll (GPollFD *ufds, guint nfsd, gint timeout);
236 #else /* !HAVE_POLL */
241 g_poll (GPollFD *fds,
245 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
246 gboolean poll_msgs = FALSE;
253 for (f = fds; f < &fds[nfds]; ++f)
256 if (f->events & G_IO_IN)
258 if (f->fd == G_WIN32_MSG_HANDLE)
262 #ifdef G_MAIN_POLL_DEBUG
263 g_print ("g_poll: waiting for %#x\n", f->fd);
265 handles[nhandles++] = (HANDLE) f->fd;
275 /* Waiting for messages, and maybe events */
278 if (timeout == INFINITE)
280 /* Waiting just for messages, infinite timeout
281 * -> Use PeekMessage, then WaitMessage
283 #ifdef G_MAIN_POLL_DEBUG
284 g_print ("PeekMessage, then WaitMessage\n");
286 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
287 ready = WAIT_OBJECT_0;
288 else if (!WaitMessage ())
289 g_warning ("g_poll: WaitMessage failed");
290 ready = WAIT_OBJECT_0;
292 else if (timeout == 0)
294 /* Waiting just for messages, zero timeout
297 #ifdef G_MAIN_POLL_DEBUG
298 g_print ("PeekMessage\n");
300 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
301 ready = WAIT_OBJECT_0;
303 ready = WAIT_TIMEOUT;
307 /* Waiting just for messages, some timeout
308 * -> First try PeekMessage, then set a timer, wait for message,
309 * kill timer, use PeekMessage
311 #ifdef G_MAIN_POLL_DEBUG
312 g_print ("PeekMessage\n");
314 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
315 ready = WAIT_OBJECT_0;
316 else if ((timer = SetTimer (NULL, 0, timeout, NULL)) == 0)
317 g_warning ("g_poll: SetTimer failed");
320 #ifdef G_MAIN_POLL_DEBUG
321 g_print ("WaitMessage\n");
324 KillTimer (NULL, timer);
325 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE)
326 && msg.message != WM_TIMER)
327 ready = WAIT_OBJECT_0;
329 ready = WAIT_TIMEOUT;
335 /* Wait for either message or event
336 * -> Use MsgWaitForMultipleObjects
338 #ifdef G_MAIN_POLL_DEBUG
339 g_print ("MsgWaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
341 ready = MsgWaitForMultipleObjects (nhandles, handles, FALSE,
342 timeout, QS_ALLINPUT);
344 if (ready == WAIT_FAILED)
345 g_warning ("g_poll: MsgWaitForMultipleObjects failed");
348 else if (nhandles == 0)
350 /* Wait for nothing (huh?) */
355 /* Wait for just events
356 * -> Use WaitForMultipleObjects
358 #ifdef G_MAIN_POLL_DEBUG
359 g_print ("WaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
361 ready = WaitForMultipleObjects (nhandles, handles, FALSE, timeout);
362 if (ready == WAIT_FAILED)
363 g_warning ("g_poll: WaitForMultipleObjects failed");
366 for (f = fds; f < &fds[nfds]; ++f)
369 if (ready == WAIT_FAILED)
371 else if (ready == WAIT_TIMEOUT)
373 else if (poll_msgs && ready == WAIT_OBJECT_0 + nhandles)
375 for (f = fds; f < &fds[nfds]; ++f)
378 if (f->events & G_IO_IN)
379 if (f->fd == G_WIN32_MSG_HANDLE)
380 f->revents |= G_IO_IN;
383 else if (ready >= WAIT_OBJECT_0 && ready < WAIT_OBJECT_0 + nhandles)
384 for (f = fds; f < &fds[nfds]; ++f)
386 if ((f->events & G_IO_IN)
387 && f->fd == (gint) handles[ready - WAIT_OBJECT_0])
389 f->revents |= G_IO_IN;
390 #ifdef G_MAIN_POLL_DEBUG
391 g_print ("g_poll: got event %#x\n", f->fd);
394 ResetEvent ((HANDLE) f->fd);
399 if (ready >= WAIT_OBJECT_0 && ready < WAIT_OBJECT_0 + nhandles)
400 return ready - WAIT_OBJECT_0 + 1;
405 #else /* !G_OS_WIN32 */
407 /* The following implementation of poll() comes from the GNU C Library.
408 * Copyright (C) 1994, 1996, 1997 Free Software Foundation, Inc.
411 #include <string.h> /* for bzero on BSD systems */
413 #ifdef HAVE_SYS_SELECT_H
414 #include <sys/select.h>
415 #endif /* HAVE_SYS_SELECT_H */
419 #endif /* G_OS_BEOS */
422 # define SELECT_MASK fd_set
423 #else /* !NO_FD_SET */
425 typedef long fd_mask;
428 # define SELECT_MASK void
430 # define SELECT_MASK int
431 # endif /* !_IBMR2 */
432 #endif /* !NO_FD_SET */
435 g_poll (GPollFD *fds,
440 SELECT_MASK rset, wset, xset;
449 for (f = fds; f < &fds[nfds]; ++f)
452 if (f->events & G_IO_IN)
453 FD_SET (f->fd, &rset);
454 if (f->events & G_IO_OUT)
455 FD_SET (f->fd, &wset);
456 if (f->events & G_IO_PRI)
457 FD_SET (f->fd, &xset);
458 if (f->fd > maxfd && (f->events & (G_IO_IN|G_IO_OUT|G_IO_PRI)))
462 tv.tv_sec = timeout / 1000;
463 tv.tv_usec = (timeout % 1000) * 1000;
465 ready = select (maxfd + 1, &rset, &wset, &xset,
466 timeout == -1 ? NULL : &tv);
468 for (f = fds; f < &fds[nfds]; ++f)
473 if (FD_ISSET (f->fd, &rset))
474 f->revents |= G_IO_IN;
475 if (FD_ISSET (f->fd, &wset))
476 f->revents |= G_IO_OUT;
477 if (FD_ISSET (f->fd, &xset))
478 f->revents |= G_IO_PRI;
485 #endif /* !G_OS_WIN32 */
487 #endif /* !HAVE_POLL */
489 /* Called to clean up when a thread terminates
492 g_main_context_destroy (GMainContext *context)
496 /* We need the lock here only because g_source_destroy expects
497 * to be able to unlock when destroying the source's data
499 LOCK_CONTEXT (context);
500 source = context->source_list;
503 GSource *next = source->next;
504 g_source_destroy_internal (source, context, TRUE);
507 UNLOCK_CONTEXT (context);
509 #ifdef G_THREADS_ENABLED
510 g_mutex_free (context->mutex);
513 g_ptr_array_free (context->pending_dispatches, TRUE);
514 g_free (context->cached_poll_array);
516 g_mem_chunk_destroy (context->poll_chunk);
518 #ifdef G_THREADS_ENABLED
519 if (g_thread_supported())
522 close (context->wake_up_pipe[0]);
523 close (context->wake_up_pipe[1]);
525 CloseHandle (context->wake_up_semaphore);
534 * g_main_context_get:
535 * @thread: a #GThread
537 * Retrieves the main loop context for a particular thread. This
538 * will create the main context for the thread if none previously
539 * existed. The context will exist until the thread terminates.
541 * Return value: the main loop context for @thread.
544 g_main_context_get (GThread *thread)
546 static GStaticPrivate private_key = G_STATIC_PRIVATE_INIT;
547 GMainContext *context;
549 g_return_val_if_fail (thread != NULL, NULL);
551 if (g_thread_supported ())
552 context = g_static_private_get_for_thread (&private_key, thread);
554 context = default_main_context;
558 context = g_new0 (GMainContext, 1);
560 #ifdef G_THREADS_ENABLED
561 if (g_thread_supported ())
562 context->mutex = g_mutex_new();
564 context->thread = thread;
567 context->next_id = 1;
569 context->source_list = NULL;
572 context->poll_func = (GPollFunc)poll;
574 context->poll_func = g_poll;
577 context->cached_poll_array = NULL;
578 context->cached_poll_array_size = 0;
580 context->pending_dispatches = g_ptr_array_new ();
582 context->time_is_current = FALSE;
584 #ifdef G_THREADS_ENABLED
585 if (g_thread_supported ())
588 if (pipe (context->wake_up_pipe) < 0)
589 g_error ("Cannot create pipe main loop wake-up: %s\n",
592 context->wake_up_rec.fd = context->wake_up_pipe[0];
593 context->wake_up_rec.events = G_IO_IN;
594 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
596 if ((context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL)) == NULL)
597 g_error ("Cannot create wake-up semaphore: %s", g_win32_error_message (GetLastError ()));
598 context->wake_up_rec.fd = (gint) context->wake_up_semaphore;
599 context->wake_up_rec.events = G_IO_IN;
600 #ifdef G_MAIN_POLL_DEBUG
601 g_print ("wake-up semaphore: %#x\n", (guint) context->wake_up_semaphore);
603 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
608 if (g_thread_supported ())
609 g_static_private_set_for_thread (&private_key, thread,
611 (GDestroyNotify)g_main_context_destroy);
613 default_main_context = context;
620 * g_main_context_default:
622 * Return the default main context. This is the main context used
623 * for main loop functions when a main loop is not explicitly
626 * Return value: the default main context.
629 g_main_context_default (void)
635 if (!default_main_context)
636 default_main_context = g_main_context_get (g_thread_self ());
638 G_UNLOCK (main_loop);
640 return default_main_context;
643 /* Hooks for adding to the main loop */
647 * @source_funcs: structure containing functions that implement
648 * the sources behavior.
649 * @struct_size: size of the #GSource structure to create
651 * Create a new GSource structure. The size is specified to
652 * allow creating structures derived from GSource that contain
653 * additional data. The size passed in must be at least
656 * The source will not initially be associated with any #GMainContext
657 * and must be added to one with g_source_add() before it will be
660 * Return value: the newly create #GSource
663 g_source_new (GSourceFuncs *source_funcs,
668 g_return_val_if_fail (source_funcs != NULL, NULL);
669 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
671 source = (GSource*) g_malloc0 (struct_size);
673 source->source_funcs = source_funcs;
674 source->ref_count = 1;
676 source->priority = G_PRIORITY_DEFAULT;
678 source->flags = G_HOOK_FLAG_ACTIVE;
680 /* NULL/0 initialization for all other fields */
685 /* Holds context's lock
688 g_source_list_add (GSource *source,
689 GMainContext *context)
691 GSource *tmp_source, *last_source;
694 tmp_source = context->source_list;
695 while (tmp_source && tmp_source->priority <= source->priority)
697 last_source = tmp_source;
698 tmp_source = tmp_source->next;
701 source->next = tmp_source;
703 tmp_source->prev = source;
705 source->prev = last_source;
707 last_source->next = source;
709 context->source_list = source;
712 /* Holds context's lock
715 g_source_list_remove (GSource *source,
716 GMainContext *context)
719 source->prev->next = source->next;
721 context->source_list = source->next;
724 source->next->prev = source->prev;
732 * @source: a #GSource
733 * @context: a #GMainContext (if %NULL, the default context will be used)
735 * Adds a #GSource to a @context so that it will be executed within
738 * Return value: the ID for the source within the #GMainContext
741 g_source_attach (GSource *source,
742 GMainContext *context)
747 g_return_val_if_fail (source->context == NULL, 0);
748 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
751 context = g_main_context_default ();
753 LOCK_CONTEXT (context);
755 source->context = context;
756 result = source->id = context->next_id++;
759 g_source_list_add (source, context);
761 tmp_list = source->poll_fds;
764 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
765 tmp_list = tmp_list->next;
768 #ifdef G_THREADS_ENABLED
769 /* Now wake up the main loop if it is waiting in the poll() */
770 g_main_context_wakeup (context);
773 UNLOCK_CONTEXT (context);
779 g_source_destroy_internal (GSource *source,
780 GMainContext *context,
784 LOCK_CONTEXT (context);
786 if (!SOURCE_DESTROYED (source))
789 gpointer old_cb_data;
790 GSourceCallbackFuncs *old_cb_funcs;
792 source->flags &= ~G_HOOK_FLAG_ACTIVE;
794 old_cb_data = source->callback_data;
795 old_cb_funcs = source->callback_funcs;
797 source->callback_data = NULL;
798 source->callback_funcs = NULL;
802 UNLOCK_CONTEXT (context);
803 old_cb_funcs->unref (old_cb_data);
804 LOCK_CONTEXT (context);
807 tmp_list = source->poll_fds;
810 g_main_context_remove_poll_unlocked (context, tmp_list->data);
811 tmp_list = tmp_list->next;
814 g_source_unref_internal (source, context, TRUE);
818 UNLOCK_CONTEXT (context);
823 * @source: a #GSource
825 * Remove a source from its #GMainContext, if any, and mark it as
826 * destroyed. The source cannot be subsequently added to another
830 g_source_destroy (GSource *source)
832 GMainContext *context;
834 g_return_if_fail (source != NULL);
836 context = source->context;
839 g_source_destroy_internal (source, context, FALSE);
841 source->flags &= ~G_HOOK_FLAG_ACTIVE;
846 * @source: a #GSource
848 * Return the numeric ID for a particular source. The ID of a source
849 * is unique within a particular main loop context. The reverse
850 * mapping from ID to source is done by g_main_context_find_source_by_id().
852 * Return value: the ID for the source
855 g_source_get_id (GSource *source)
859 g_return_val_if_fail (source != NULL, 0);
860 g_return_val_if_fail (source->context != NULL, 0);
862 LOCK_CONTEXT (source->context);
864 UNLOCK_CONTEXT (source->context);
870 * g_source_get_context:
871 * @source: a #GSource
873 * Get the #GMainContext with which the source is associated.
874 * Calling this function on a destroyed source is an error.
876 * Return value: the #GMainContext with which the source is associated,
877 * or %NULL if the context has not yet been added
881 g_source_get_context (GSource *source)
883 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
885 return source->context;
889 * g_main_source_add_poll:
891 * @fd: a #GPollFD structure holding information about a file
892 * descriptor to watch.
894 * Add a file descriptor to the set of file descriptors polled * for
895 * this source. This is usually combined with g_source_new() to add an
896 * event source. The event source's check function will typically test
897 * the revents field in the #GPollFD struct and return %TRUE if events need
901 g_source_add_poll (GSource *source,
904 GMainContext *context;
906 g_return_if_fail (source != NULL);
907 g_return_if_fail (fd != NULL);
908 g_return_if_fail (!SOURCE_DESTROYED (source));
910 context = source->context;
913 LOCK_CONTEXT (context);
915 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
919 g_main_context_add_poll_unlocked (context, source->priority, fd);
920 UNLOCK_CONTEXT (context);
925 * g_source_set_callback_indirect:
926 * @source: the source
927 * @callback_data: pointer to callback data "object"
928 * @callback_funcs: functions for reference counting callback_data
929 * and getting the callback and data
931 * Set the callback function storing the data as a refcounted callback
932 * "object". This is used to implement g_source_set_callback_closure()
933 * and internally. Note that calling g_source_set_callback_indirect() assumes
934 * an initial reference count on @callback_data, and thus
935 * @callback_funcs->unref will eventually be called once more
936 * than @callback_funcs->ref.
939 g_source_set_callback_indirect (GSource *source,
940 gpointer callback_data,
941 GSourceCallbackFuncs *callback_funcs)
943 GMainContext *context;
944 gpointer old_cb_data;
945 GSourceCallbackFuncs *old_cb_funcs;
947 g_return_if_fail (source != NULL);
948 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
950 context = source->context;
953 LOCK_CONTEXT (context);
955 old_cb_data = source->callback_data;
956 old_cb_funcs = source->callback_funcs;
958 source->callback_data = callback_data;
959 source->callback_funcs = callback_funcs;
962 UNLOCK_CONTEXT (context);
965 old_cb_funcs->unref (old_cb_data);
969 g_source_callback_ref (gpointer cb_data)
971 GSourceCallback *callback = cb_data;
973 callback->ref_count++;
978 g_source_callback_unref (gpointer cb_data)
980 GSourceCallback *callback = cb_data;
982 callback->ref_count--;
983 if (callback->ref_count == 0)
985 if (callback->notify)
986 callback->notify (callback->data);
991 g_source_callback_get (gpointer cb_data,
995 GSourceCallback *callback = cb_data;
997 *func = callback->func;
998 *data = callback->data;
1001 static GSourceCallbackFuncs g_source_callback_funcs = {
1002 g_source_callback_ref,
1003 g_source_callback_unref,
1004 g_source_callback_get,
1008 * g_source_set_callback:
1009 * @source: the source
1010 * @func: a callback function
1011 * @data: the data to pass to callback function
1012 * @notify: a function to call when @data is no longer in use, or %NULL.
1014 * Set the callback function for a source.
1017 g_source_set_callback (GSource *source,
1020 GDestroyNotify notify)
1022 GSourceCallback *new_callback;
1024 g_return_if_fail (source != NULL);
1026 new_callback = g_new (GSourceCallback, 1);
1028 new_callback->func = func;
1029 new_callback->data = data;
1030 new_callback->notify = notify;
1032 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1036 * g_source_set_priority:
1037 * @source: a #GSource
1038 * @priority: the new priority.
1040 * Set the priority of a source. While the main loop is being
1041 * run, a source will
1044 g_source_set_priority (GSource *source,
1048 GMainContext *context;
1050 g_return_if_fail (source != NULL);
1052 context = source->context;
1055 LOCK_CONTEXT (context);
1057 source->priority = priority;
1061 source->next = NULL;
1062 source->prev = NULL;
1064 tmp_list = source->poll_fds;
1067 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1068 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1070 tmp_list = tmp_list->next;
1073 UNLOCK_CONTEXT (source->context);
1078 * g_source_get_priority:
1079 * @source: a #GSource
1081 * Gets the priority of a surce
1083 * Return value: the priority of the source
1086 g_source_get_priority (GSource *source)
1088 g_return_val_if_fail (source != NULL, 0);
1090 return source->priority;
1094 * g_source_set_can_recurse:
1095 * @source: a #GSource
1096 * @can_recurse: whether recursion is allowed for this source
1098 * Sets whether a source can be called recursively. If @can_recurse is
1099 * %TRUE, then while the source is being dispatched then this source
1100 * will be processed normally. Otherwise, all processing of this
1101 * source is blocked until the dispatch function returns.
1104 g_source_set_can_recurse (GSource *source,
1105 gboolean can_recurse)
1107 GMainContext *context;
1109 g_return_if_fail (source != NULL);
1111 context = source->context;
1114 LOCK_CONTEXT (context);
1117 source->flags |= G_SOURCE_CAN_RECURSE;
1119 source->flags &= ~G_SOURCE_CAN_RECURSE;
1122 UNLOCK_CONTEXT (context);
1126 * g_source_get_can_recurse:
1127 * @source: a #GSource
1129 * Checks whether a source is allowed to be called recursively.
1130 * see g_source_set_can_recurse.
1132 * Return value: whether recursion is allowed.
1135 g_source_get_can_recurse (GSource *source)
1137 g_return_val_if_fail (source != NULL, FALSE);
1139 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1144 * @source: a #GSource
1146 * Increases the reference count on a source by one.
1148 * Return value: @source
1151 g_source_ref (GSource *source)
1153 GMainContext *context;
1155 g_return_val_if_fail (source != NULL, NULL);
1157 context = source->context;
1160 LOCK_CONTEXT (context);
1162 source->ref_count++;
1165 UNLOCK_CONTEXT (context);
1170 /* g_source_unref() but possible to call within context lock
1173 g_source_unref_internal (GSource *source,
1174 GMainContext *context,
1177 gpointer old_cb_data = NULL;
1178 GSourceCallbackFuncs *old_cb_funcs = NULL;
1180 g_return_if_fail (source != NULL);
1182 if (!have_lock && context)
1183 LOCK_CONTEXT (context);
1185 source->ref_count--;
1186 if (source->ref_count == 0)
1188 old_cb_data = source->callback_data;
1189 old_cb_funcs = source->callback_funcs;
1191 source->callback_data = NULL;
1192 source->callback_funcs = NULL;
1194 if (context && !SOURCE_DESTROYED (source))
1196 g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1197 source->ref_count++;
1200 g_source_list_remove (source, context);
1202 if (source->source_funcs->destroy)
1203 source->source_funcs->destroy (source);
1205 g_slist_free (source->poll_fds);
1206 source->poll_fds = NULL;
1210 if (!have_lock && context)
1211 UNLOCK_CONTEXT (context);
1216 UNLOCK_CONTEXT (context);
1218 old_cb_funcs->unref (old_cb_data);
1221 LOCK_CONTEXT (context);
1227 * @source: a #GSource
1229 * Decreases the reference count of a source by one. If the
1230 * resulting reference count is zero the source and associated
1231 * memory will be destroyed.
1234 g_source_unref (GSource *source)
1236 g_return_if_fail (source != NULL);
1238 g_source_unref_internal (source, source->context, FALSE);
1242 * g_main_context_find_source_by_id:
1243 * @context: a #GMainContext (if %NULL, the default context will be used)
1244 * @id: the source ID, as returned by g_source_get_id()
1246 * Finds a #GSource given a pair of context and ID
1248 * Return value: the #GSource if found, otherwise, %NULL
1251 g_main_context_find_source_by_id (GMainContext *context,
1256 g_return_val_if_fail (id > 0, FALSE);
1258 if (context == NULL)
1259 context = g_main_context_default ();
1261 LOCK_CONTEXT (context);
1263 source = context->source_list;
1266 if (!SOURCE_DESTROYED (source) &&
1269 source = source->next;
1272 UNLOCK_CONTEXT (context);
1278 * g_main_context_find_source_by_funcs_user_data:
1279 * @context: a #GMainContext (if %NULL, the default context will be used).
1280 * @funcs: the @source_funcs passed to g_source_new().
1281 * @user_data: the user data from the callback.
1283 * Finds a source with the given source functions and user data. If
1284 * multiple sources exist with the same source function and user data,
1285 * the first one found will be returned.
1287 * Return value: the source, if one was found, otherwise %NULL
1290 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1291 GSourceFuncs *funcs,
1296 g_return_val_if_fail (funcs != NULL, FALSE);
1298 if (context == NULL)
1299 context = g_main_context_default ();
1301 LOCK_CONTEXT (context);
1303 source = context->source_list;
1306 if (!SOURCE_DESTROYED (source) &&
1307 source->source_funcs == funcs &&
1308 source->callback_data == user_data)
1310 source = source->next;
1313 UNLOCK_CONTEXT (context);
1319 * g_main_context_find_source_by_user_data:
1320 * @context: a #GMainContext
1321 * @user_data: the user_data for the callback.
1323 * Finds a source with the given user data for the callback. If
1324 * multiple sources exist with the same user data, the first
1325 * one found will be returned.
1327 * Return value: the source, if one was found, otherwise %NULL
1330 g_main_context_find_source_by_user_data (GMainContext *context,
1335 if (context == NULL)
1336 context = g_main_context_default ();
1338 LOCK_CONTEXT (context);
1340 source = context->source_list;
1343 if (!SOURCE_DESTROYED (source) &&
1344 source->callback_data == user_data)
1346 source = source->next;
1349 UNLOCK_CONTEXT (context);
1356 * @tag: the id of the source to remove.
1358 * Removes the source with the given id from the default main
1359 * context. The id of a #GSource is given by g_source_get_id(),
1360 * or will be returned by the functions g_source_attach(),
1361 * g_idle_add(), g_idle_add_full(), g_timeout_add(),
1362 * g_timeout_add_full(), g_io_add_watch, and g_io_add_watch_full().
1364 * See also g_source_destroy().
1366 * Return value: %TRUE if the source was found and removed.
1369 g_source_remove (guint tag)
1373 g_return_val_if_fail (tag > 0, FALSE);
1375 source = g_main_context_find_source_by_id (NULL, tag);
1377 g_source_destroy (source);
1379 return source != NULL;
1383 * g_source_remove_by_user_data:
1384 * @user_data: the user_data for the callback.
1386 * Removes a source from the default main loop context given the user
1387 * data for the callback. If multiple sources exist with the same user
1388 * data, only one will be destroyed.
1390 * Return value: %TRUE if a source was found and removed.
1393 g_source_remove_by_user_data (gpointer user_data)
1397 source = g_main_context_find_source_by_user_data (NULL, user_data);
1400 g_source_destroy (source);
1408 * g_source_remove_by_funcs_user_data:
1409 * @funcs: The @source_funcs passed to g_source_new()
1410 * @user_data: the user data for the callback
1412 * Removes a source from the default main loop context given the
1413 * source functions and user data. If multiple sources exist with the
1414 * same source functions and user data, only one will be destroyed.
1416 * Return value: %TRUE if a source was found and removed.
1419 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1424 g_return_val_if_fail (funcs != NULL, FALSE);
1426 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1429 g_source_destroy (source);
1437 * g_get_current_time:
1438 * @result: #GTimeVal structure in which to store current time.
1440 * Equivalent to Unix's <function>gettimeofday()</function>, but portable
1443 g_get_current_time (GTimeVal *result)
1448 g_return_if_fail (result != NULL);
1450 /*this is required on alpha, there the timeval structs are int's
1451 not longs and a cast only would fail horribly*/
1452 gettimeofday (&r, NULL);
1453 result->tv_sec = r.tv_sec;
1454 result->tv_usec = r.tv_usec;
1456 /* Avoid calling time() except for the first time.
1457 * GetTickCount() should be pretty fast and low-level?
1458 * I could also use ftime() but it seems unnecessarily overheady.
1460 static DWORD start_tick = 0;
1461 static time_t start_time;
1464 g_return_if_fail (result != NULL);
1466 if (start_tick == 0)
1468 start_tick = GetTickCount ();
1472 tick = GetTickCount ();
1474 result->tv_sec = (tick - start_tick) / 1000 + start_time;
1475 result->tv_usec = ((tick - start_tick) % 1000) * 1000;
1479 /* Running the main loop */
1481 /* HOLDS: context's lock */
1483 g_main_dispatch (GMainContext *context)
1487 for (i = 0; i < context->pending_dispatches->len; i++)
1489 GSource *source = context->pending_dispatches->pdata[i];
1491 context->pending_dispatches->pdata[i] = NULL;
1494 source->flags &= ~G_SOURCE_READY;
1496 if (!SOURCE_DESTROYED (source))
1498 gboolean was_in_call;
1499 gpointer user_data = NULL;
1500 GSourceFunc callback = NULL;
1501 GSourceCallbackFuncs *cb_funcs;
1503 gboolean need_destroy;
1505 gboolean (*dispatch) (GSource *,
1509 dispatch = source->source_funcs->dispatch;
1510 cb_funcs = source->callback_funcs;
1511 cb_data = source->callback_data;
1514 cb_funcs->ref (cb_data);
1516 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
1517 source->flags |= G_HOOK_FLAG_IN_CALL;
1519 UNLOCK_CONTEXT (context);
1522 cb_funcs->get (cb_data, &callback, &user_data);
1524 need_destroy = ! dispatch (source,
1527 LOCK_CONTEXT (context);
1530 cb_funcs->unref (cb_data);
1533 source->flags &= ~G_HOOK_FLAG_IN_CALL;
1535 /* Note: this depends on the fact that we can't switch
1536 * sources from one main context to another
1538 if (need_destroy && !SOURCE_DESTROYED (source))
1540 g_assert (source->context == context);
1541 g_source_destroy_internal (source, context, TRUE);
1545 SOURCE_UNREF (source, context);
1548 g_ptr_array_set_size (context->pending_dispatches, 0);
1551 /* Holds context's lock */
1552 static inline GSource *
1553 next_valid_source (GMainContext *context,
1556 GSource *new_source = source ? source->next : context->source_list;
1560 if (!SOURCE_DESTROYED (new_source))
1562 new_source->ref_count++;
1566 new_source = new_source->next;
1570 SOURCE_UNREF (source, context);
1577 * g_main_context_prepare:
1578 * @context: a #GMainContext
1579 * @priority: location to store priority of highest priority
1580 * source already ready.
1582 * Prepares to poll sources within a main loop. The resulting information
1583 * for polling is determined by calling g_main_context_query ().
1585 * Return value: %TRUE if some source is ready to be dispatched
1589 g_main_context_prepare (GMainContext *context,
1593 gint current_priority = G_MAXINT;
1596 if (context == NULL)
1597 context = g_main_context_default ();
1599 LOCK_CONTEXT (context);
1601 context->time_is_current = FALSE;
1603 if (context->in_check_or_prepare)
1605 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
1606 "prepare() member.");
1610 #ifdef G_THREADS_ENABLED
1611 if (context->poll_waiting)
1613 g_warning("g_main_context_prepare(): main loop already active in another thread");
1614 UNLOCK_CONTEXT (context);
1618 context->poll_waiting = TRUE;
1619 #endif /* G_THREADS_ENABLED */
1622 /* If recursing, finish up current dispatch, before starting over */
1623 if (context->pending_dispatches)
1626 g_main_dispatch (context, ¤t_time);
1628 UNLOCK_CONTEXT (context);
1633 /* If recursing, clear list of pending dispatches */
1634 g_ptr_array_set_size (context->pending_dispatches, 0);
1636 /* Prepare all sources */
1638 context->timeout = -1;
1640 source = next_valid_source (context, NULL);
1643 gint source_timeout = -1;
1645 if ((n_ready > 0) && (source->priority > current_priority))
1647 SOURCE_UNREF (source, context);
1650 if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
1653 if (!(source->flags & G_SOURCE_READY))
1656 gboolean (*prepare) (GSource *source,
1659 prepare = source->source_funcs->prepare;
1660 context->in_check_or_prepare++;
1661 UNLOCK_CONTEXT (context);
1663 result = (*prepare) (source, &source_timeout);
1665 LOCK_CONTEXT (context);
1666 context->in_check_or_prepare--;
1669 source->flags |= G_SOURCE_READY;
1672 if (source->flags & G_SOURCE_READY)
1675 current_priority = source->priority;
1676 context->timeout = 0;
1679 if (source_timeout >= 0)
1681 if (context->timeout < 0)
1682 context->timeout = source_timeout;
1684 context->timeout = MIN (context->timeout, source_timeout);
1688 source = next_valid_source (context, source);
1691 UNLOCK_CONTEXT (context);
1694 *priority = current_priority;
1696 return (n_ready > 0);
1700 * g_main_context_query:
1701 * @context: a #GMainContext
1702 * @max_priority: maximum priority source to check
1703 * @timeout: location to store timeout to be used in polling
1704 * @fds: location to store #GPollFD records that need to be polled.
1705 * @n_fds: length of @fds.
1707 * Determines information necessary to poll this main loop.
1712 g_main_context_query (GMainContext *context,
1721 LOCK_CONTEXT (context);
1723 pollrec = context->poll_records;
1725 while (pollrec && max_priority >= pollrec->priority)
1727 if (pollrec->fd->events)
1731 fds[n_poll].fd = pollrec->fd->fd;
1732 /* In direct contradiction to the Unix98 spec, IRIX runs into
1733 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
1734 * flags in the events field of the pollfd while it should
1735 * just ignoring them. So we mask them out here.
1737 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
1738 fds[n_poll].revents = 0;
1743 pollrec = pollrec->next;
1746 #ifdef G_THREADS_ENABLED
1747 context->poll_changed = FALSE;
1752 *timeout = context->timeout;
1754 context->time_is_current = FALSE;
1757 UNLOCK_CONTEXT (context);
1763 * g_main_context_check:
1764 * @context: a #GMainContext
1765 * @max_priority: the maximum numerical priority of sources to check
1766 * @fds: array of #GPollFD's that was passed to the last call to
1767 * g_main_context_query()
1768 * @n_fds: return value of g_main_context_query()
1770 * Pass the results of polling back to the main loop.
1772 * Return value: %TRUE if some sources are ready to be dispatched.
1775 g_main_context_check (GMainContext *context,
1785 LOCK_CONTEXT (context);
1787 if (context->in_check_or_prepare)
1789 g_warning ("g_main_context_check() called recursively from within a source's check() or "
1790 "prepare() member.");
1794 #ifdef G_THREADS_ENABLED
1795 if (!context->poll_waiting)
1799 read (context->wake_up_pipe[0], &c, 1);
1803 context->poll_waiting = FALSE;
1805 /* If the set of poll file descriptors changed, bail out
1806 * and let the main loop rerun
1808 if (context->poll_changed)
1810 #endif /* G_THREADS_ENABLED */
1812 pollrec = context->poll_records;
1816 if (pollrec->fd->events)
1818 pollrec->fd->revents = fds[i].revents;
1821 pollrec = pollrec->next;
1824 source = next_valid_source (context, NULL);
1827 if ((n_ready > 0) && (source->priority > max_priority))
1829 SOURCE_UNREF (source, context);
1832 if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
1835 if (!(source->flags & G_SOURCE_READY))
1838 gboolean (*check) (GSource *source);
1840 check = source->source_funcs->check;
1842 context->in_check_or_prepare++;
1843 UNLOCK_CONTEXT (context);
1845 result = (*check) (source);
1847 LOCK_CONTEXT (context);
1848 context->in_check_or_prepare--;
1851 source->flags |= G_SOURCE_READY;
1854 if (source->flags & G_SOURCE_READY)
1856 source->ref_count++;
1857 g_ptr_array_add (context->pending_dispatches, source);
1863 source = next_valid_source (context, source);
1866 UNLOCK_CONTEXT (context);
1872 * g_main_context_dispatch:
1873 * @context: a #GMainContext
1875 * Dispatch all pending sources()
1878 g_main_context_dispatch (GMainContext *context)
1880 LOCK_CONTEXT (context);
1882 if (context->pending_dispatches->len > 0)
1884 g_main_dispatch (context);
1887 UNLOCK_CONTEXT (context);
1891 g_main_context_iterate (GMainContext *context,
1897 gboolean some_ready;
1898 gint nfds, new_nfds;
1901 some_ready = g_main_context_prepare (context, &max_priority);
1905 LOCK_CONTEXT (context);
1907 if (context->cached_poll_array)
1909 nfds = context->cached_poll_array_size;
1910 fds = context->cached_poll_array;
1911 context->cached_poll_array = NULL;
1915 nfds = context->cached_poll_array_size = context->n_poll_records;
1916 fds = g_new (GPollFD, nfds);
1919 UNLOCK_CONTEXT (context);
1921 new_nfds = g_main_context_query (context, max_priority,
1922 &timeout, fds, nfds);
1924 while (new_nfds > nfds);
1929 g_main_context_poll (context, timeout, max_priority,
1932 g_main_context_check (context,
1936 LOCK_CONTEXT (context);
1938 g_assert (!context->cached_poll_array);
1940 context->cached_poll_array = fds;
1941 context->cached_poll_array_size = nfds;
1943 UNLOCK_CONTEXT (context);
1946 g_main_context_dispatch (context);
1952 * g_main_context_pending:
1953 * @context: a #GMainContext (if %NULL, the default context will be used)
1955 * Check if any sources have pending events for the given context.
1957 * Return value: %TRUE if events are pending.
1960 g_main_context_pending (GMainContext *context)
1963 context = g_main_context_default();
1965 return g_main_context_iterate (context, FALSE, FALSE);
1969 * g_main_context_iteration:
1970 * @context: a #GMainContext (if %NULL, the default context will be used)
1971 * @may_block: whether the call may block.
1973 * Run a single iteration for the given main loop. This involves
1974 * checking to see if any event sources are ready to be processed,
1975 * then if no events sources are ready and @may_block is %TRUE, waiting
1976 * for a source to become ready, then dispatching the highest priority
1977 * events sources that are ready. Note that even when @may_block is %TRUE,
1978 * it is still possible for g_main_context_iteration() to return
1979 * %FALSE, since the the wait may be interrupted for other
1980 * reasons than an event source becoming ready.
1982 * Return value: %TRUE if events were dispatched.
1985 g_main_context_iteration (GMainContext *context, gboolean may_block)
1988 context = g_main_context_default();
1990 return g_main_context_iterate (context, may_block, TRUE);
1995 * @context: a #GMainContext (if %NULL, the default context will be used).
1996 * @is_running: set to TRUE to indicate that the loop is running. This
1997 * is not very important since calling g_main_run() will set this to
2000 * Create a new #GMainLoop structure
2005 g_main_loop_new (GMainContext *context,
2006 gboolean is_running)
2011 context = g_main_context_default();
2013 loop = g_new0 (GMainLoop, 1);
2014 loop->context = context;
2015 loop->is_running = is_running != FALSE;
2016 loop->ref_count = 1;
2018 #ifdef G_THREADS_ENABLED
2019 if (g_thread_supported ())
2020 loop->mutex = g_mutex_new ();
2023 loop->sem_cond = NULL;
2024 #endif /* G_THREADS_ENABLED */
2031 * @loop: a #GMainLoop
2033 * Increase the reference count on a #GMainLoop object by one.
2035 * Return value: @loop
2038 g_main_loop_ref (GMainLoop *loop)
2040 g_return_val_if_fail (loop != NULL, NULL);
2050 main_loop_destroy (GMainLoop *loop)
2052 #ifdef G_THREADS_ENABLED
2053 g_mutex_free (loop->mutex);
2055 g_cond_free (loop->sem_cond);
2056 #endif /* G_THREADS_ENABLED */
2062 * g_main_loop_unref:
2063 * @loop: a #GMainLoop
2065 * Decreases the reference count on a #GMainLoop object by one. If
2066 * the result is zero, free the loop and free all associated memory.
2069 g_main_loop_unref (GMainLoop *loop)
2071 g_return_if_fail (loop != NULL);
2072 g_return_if_fail (loop->ref_count > 0);
2077 if (loop->ref_count == 0)
2079 /* When the ref_count is 0, there can be nobody else using the
2080 * loop, so it is safe to unlock before destroying.
2083 main_loop_destroy (loop);
2091 * @loop: a #GMainLoop
2093 * Run a main loop until g_main_quit() is called on the loop.
2094 * If this is called for the thread of the loop's #GMainContext,
2095 * it will process events from the loop, otherwise it will
2099 g_main_loop_run (GMainLoop *loop)
2101 g_return_if_fail (loop != NULL);
2103 /* The assumption here is that a reference is held to the loop
2104 * until we recursively iterate
2106 #ifdef G_THREADS_ENABLED
2107 if (loop->context->thread != g_thread_self ())
2113 if (!g_thread_supported ())
2115 g_warning ("g_main_loop_run() was called from second thread but"
2116 "g_thread_init() was never called.");
2120 if (!loop->sem_cond)
2121 loop->sem_cond = g_cond_new ();
2123 if (!loop->is_running)
2124 loop->is_running = TRUE;
2126 while (loop->is_running)
2127 g_cond_wait (loop->sem_cond, loop->mutex);
2131 #endif /* G_THREADS_ENABLED */
2133 LOCK_CONTEXT (loop->context);
2134 if (loop->context->in_check_or_prepare)
2136 g_warning ("g_main_run(): called recursively from within a source's check() or "
2137 "prepare() member, iteration not possible.");
2140 UNLOCK_CONTEXT (loop->context);
2145 loop->is_running = TRUE;
2146 while (loop->is_running)
2149 g_main_context_iterate (loop->context, TRUE, TRUE);
2154 /* We inline this here rather than calling g_main_loop_unref() to
2155 * avoid an extra unlock/lock.
2158 if (loop->ref_count == 0)
2161 main_loop_destroy (loop);
2169 * @loop: a #GMainLoop
2171 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
2172 * for the loop will return.
2175 g_main_loop_quit (GMainLoop *loop)
2177 g_return_if_fail (loop != NULL);
2180 loop->is_running = FALSE;
2182 #ifdef G_THREADS_ENABLED
2184 g_cond_broadcast (loop->sem_cond);
2189 LOCK_CONTEXT (loop->context);
2191 g_main_context_wakeup (loop->context);
2192 UNLOCK_CONTEXT (loop->context);
2196 * g_main_loop_is_running:
2197 * @loop: a #GMainLoop.
2199 * Check to see if the main loop is currently being run via g_main_run()
2201 * Return value: %TRUE if the mainloop is currently being run.
2204 g_main_loop_is_running (GMainLoop *loop)
2208 g_return_val_if_fail (loop != NULL, FALSE);
2211 result = loop->is_running;
2217 /* HOLDS: context's lock */
2219 g_main_context_poll (GMainContext *context,
2225 #ifdef G_MAIN_POLL_DEBUG
2231 GPollFunc poll_func;
2233 if (n_fds || timeout != 0)
2235 #ifdef G_MAIN_POLL_DEBUG
2236 g_print ("g_main_poll(%d) timeout: %d\n", n_fds, timeout);
2237 poll_timer = g_timer_new ();
2240 LOCK_CONTEXT (context);
2242 poll_func = context->poll_func;
2244 UNLOCK_CONTEXT (context);
2245 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
2246 g_warning ("poll(2) failed due to: %s.",
2247 g_strerror (errno));
2249 #ifdef G_MAIN_POLL_DEBUG
2250 LOCK_CONTEXT (context);
2252 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
2255 g_timer_elapsed (poll_timer, NULL));
2256 g_timer_destroy (poll_timer);
2257 pollrec = context->poll_records;
2261 if (pollrec->fd->events)
2265 g_print (" [%d:", fds[i].fd);
2266 if (fds[i].revents & G_IO_IN)
2268 if (fds[i].revents & G_IO_OUT)
2270 if (fds[i].revents & G_IO_PRI)
2272 if (fds[i].revents & G_IO_ERR)
2274 if (fds[i].revents & G_IO_HUP)
2276 if (fds[i].revents & G_IO_NVAL)
2282 pollrec = pollrec->next;
2286 UNLOCK_CONTEXT (context);
2288 } /* if (n_fds || timeout != 0) */
2292 * g_main_context_add_poll:
2293 * @context: a #GMainContext (or %NULL for the default context)
2294 * @fd: a #GPollFD structure holding information about a file
2295 * descriptor to watch.
2296 * @priority: the priority for this file descriptor which should be
2297 * the same as the priority used for g_source_attach() to ensure that the
2298 * file descriptor is polled whenever the results may be needed.
2300 * Add a file descriptor to the set of file descriptors polled * for
2301 * this context. This will very seldom be used directly. Instead
2302 * a typical event source will use g_source_add_poll() instead.
2305 g_main_context_add_poll (GMainContext *context,
2310 context = g_main_context_default ();
2312 LOCK_CONTEXT (context);
2313 g_main_context_add_poll_unlocked (context, priority, fd);
2314 UNLOCK_CONTEXT (context);
2317 /* HOLDS: main_loop_lock */
2319 g_main_context_add_poll_unlocked (GMainContext *context,
2323 GPollRec *lastrec, *pollrec, *newrec;
2325 if (!context->poll_chunk)
2326 context->poll_chunk = g_mem_chunk_create (GPollRec, 32, G_ALLOC_ONLY);
2328 if (context->poll_free_list)
2330 newrec = context->poll_free_list;
2331 context->poll_free_list = newrec->next;
2334 newrec = g_chunk_new (GPollRec, context->poll_chunk);
2336 /* This file descriptor may be checked before we ever poll */
2339 newrec->priority = priority;
2342 pollrec = context->poll_records;
2343 while (pollrec && priority >= pollrec->priority)
2346 pollrec = pollrec->next;
2350 lastrec->next = newrec;
2352 context->poll_records = newrec;
2354 newrec->next = pollrec;
2356 context->n_poll_records++;
2357 if (context->cached_poll_array &&
2358 context->cached_poll_array_size < context->n_poll_records)
2360 g_free (context->cached_poll_array);
2361 context->cached_poll_array = NULL;
2364 #ifdef G_THREADS_ENABLED
2365 context->poll_changed = TRUE;
2367 /* Now wake up the main loop if it is waiting in the poll() */
2368 g_main_context_wakeup (context);
2373 * g_main_context_remove_poll:
2374 * @context:a #GMainContext
2375 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
2377 * Remove file descriptor from the set of file descriptors to be
2378 * polled for a particular context.
2381 g_main_context_remove_poll (GMainContext *context,
2385 context = g_main_context_default ();
2387 LOCK_CONTEXT (context);
2389 g_main_context_remove_poll_unlocked (context, fd);
2391 UNLOCK_CONTEXT (context);
2395 g_main_context_remove_poll_unlocked (GMainContext *context,
2398 GPollRec *pollrec, *lastrec;
2401 pollrec = context->poll_records;
2405 if (pollrec->fd == fd)
2407 if (lastrec != NULL)
2408 lastrec->next = pollrec->next;
2410 context->poll_records = pollrec->next;
2412 #ifdef ENABLE_GC_FRIENDLY
2414 #endif /* ENABLE_GC_FRIENDLY */
2416 pollrec->next = context->poll_free_list;
2417 context->poll_free_list = pollrec;
2419 context->n_poll_records--;
2423 pollrec = pollrec->next;
2426 #ifdef G_THREADS_ENABLED
2427 context->poll_changed = TRUE;
2429 /* Now wake up the main loop if it is waiting in the poll() */
2430 g_main_context_wakeup (context);
2435 * g_source_get_current_time:
2436 * @source: a #GSource
2437 * @timeval: #GTimeVal structure in which to store current time.
2439 * Gets the "current time" to be used when checking
2440 * this source. The advantage of calling this function over
2441 * calling g_get_current_time() directly is that when
2442 * checking multiple sources, GLib can cache a single value
2443 * instead of having to repeatedly get the system time.
2446 g_source_get_current_time (GSource *source,
2449 GMainContext *context;
2451 g_return_if_fail (source->context != NULL);
2453 context = source->context;
2455 LOCK_CONTEXT (context);
2457 if (!context->time_is_current)
2459 g_get_current_time (&context->current_time);
2460 context->time_is_current = TRUE;
2463 *timeval = context->current_time;
2465 UNLOCK_CONTEXT (context);
2469 * g_main_context_set_poll_func:
2470 * @context: a #GMainContext
2471 * @func: the function to call to poll all file descriptors
2473 * Sets the function to use to handle polling of file descriptors. It
2474 * will be used instead of the poll() system call (or GLib's
2475 * replacement function, which is used where poll() isn't available).
2477 * This function could possibly be used to integrate the GLib event
2478 * loop with an external event loop.
2481 g_main_context_set_poll_func (GMainContext *context,
2485 context = g_main_context_default ();
2487 LOCK_CONTEXT (context);
2490 context->poll_func = func;
2494 context->poll_func = (GPollFunc) poll;
2496 context->poll_func = (GPollFunc) g_poll;
2500 UNLOCK_CONTEXT (context);
2504 * g_main_context_get_poll_func:
2505 * @context: a #GMainContext
2507 * Gets the poll function set by g_main_context_set_poll_func()
2509 * Return value: the poll function
2512 g_main_context_get_poll_func (GMainContext *context)
2517 context = g_main_context_default ();
2519 LOCK_CONTEXT (context);
2520 result = context->poll_func;
2521 UNLOCK_CONTEXT (context);
2526 /* HOLDS: context's lock */
2527 /* Wake the main loop up from a poll() */
2529 g_main_context_wakeup (GMainContext *context)
2531 #ifdef G_THREADS_ENABLED
2532 if (g_thread_supported() && context->poll_waiting)
2534 context->poll_waiting = FALSE;
2536 write (context->wake_up_pipe[1], "A", 1);
2538 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
2547 g_timeout_set_expiration (GTimeoutSource *timeout_source,
2548 GTimeVal *current_time)
2550 guint seconds = timeout_source->interval / 1000;
2551 guint msecs = timeout_source->interval - seconds * 1000;
2553 timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
2554 timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
2555 if (timeout_source->expiration.tv_usec >= 1000000)
2557 timeout_source->expiration.tv_usec -= 1000000;
2558 timeout_source->expiration.tv_sec++;
2563 g_timeout_prepare (GSource *source,
2567 GTimeVal current_time;
2569 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2571 g_source_get_current_time (source, ¤t_time);
2573 msec = ((timeout_source->expiration.tv_sec - current_time.tv_sec) * 1000 +
2574 (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000);
2578 else if (msec > timeout_source->interval)
2580 /* The system time has been set backwards, so we
2581 * reset the expiration time to now + timeout_source->interval;
2582 * this at least avoids hanging for long periods of time.
2584 g_timeout_set_expiration (timeout_source, ¤t_time);
2585 msec = timeout_source->interval;
2594 g_timeout_check (GSource *source)
2596 GTimeVal current_time;
2597 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2599 g_source_get_current_time (source, ¤t_time);
2601 return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
2602 ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
2603 (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
2607 g_timeout_dispatch (GSource *source,
2608 GSourceFunc callback,
2611 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2615 g_warning ("Timeout source dispatched without callback\n"
2616 "You must call g_source_set_callback().");
2620 if (callback (user_data))
2622 GTimeVal current_time;
2624 g_source_get_current_time (source, ¤t_time);
2625 g_timeout_set_expiration (timeout_source, ¤t_time);
2634 * g_timeout_source_new:
2635 * @interval: the timeout interval in milliseconds.
2637 * Create a new timeout source.
2639 * The source will not initially be associated with any #GMainContext
2640 * and must be added to one with g_source_attach() before it will be
2643 * Return value: the newly create timeout source
2646 g_timeout_source_new (guint interval)
2648 GSource *source = g_source_new (&timeout_funcs, sizeof (GTimeoutSource));
2649 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2650 GTimeVal current_time;
2652 timeout_source->interval = interval;
2654 g_get_current_time (¤t_time);
2655 g_timeout_set_expiration (timeout_source, ¤t_time);
2661 * g_timeout_add_full:
2662 * @priority: the priority of the idle source. Typically this will be in the
2663 * range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
2664 * @interval: the time between calls to the function, in milliseconds
2665 * (1/1000ths of a second.)
2666 * @function: function to call
2667 * @data: data to pass to @function
2668 * @notify: function to call when the idle is removed, or %NULL
2670 * Sets a function to be called at regular intervals, with the given
2671 * priority. The function is called repeatedly until it returns
2672 * FALSE, at which point the timeout is automatically destroyed and
2673 * the function will not be called again. The @notify function is
2674 * called when the timeout is destroyed. The first call to the
2675 * function will be at the end of the first @interval.
2677 * Note that timeout functions may be delayed, due to the processing of other
2678 * event sources. Thus they should not be relied on for precise timing.
2679 * After each call to the timeout function, the time of the next
2680 * timeout is recalculated based on the current time and the given interval
2681 * (it does not try to 'catch up' time lost in delays).
2683 * Return value: the id of event source.
2686 g_timeout_add_full (gint priority,
2688 GSourceFunc function,
2690 GDestroyNotify notify)
2695 g_return_val_if_fail (function != NULL, 0);
2697 source = g_timeout_source_new (interval);
2699 if (priority != G_PRIORITY_DEFAULT)
2700 g_source_set_priority (source, priority);
2702 g_source_set_callback (source, function, data, notify);
2703 id = g_source_attach (source, NULL);
2704 g_source_unref (source);
2711 * @interval: the time between calls to the function, in milliseconds
2712 * (1/1000ths of a second.)
2713 * @function: function to call
2714 * @data: data to pass to @function
2716 * Sets a function to be called at regular intervals, with the default
2717 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
2718 * until it returns FALSE, at which point the timeout is automatically
2719 * destroyed and the function will not be called again. The @notify
2720 * function is called when the timeout is destroyed. The first call
2721 * to the function will be at the end of the first @interval.
2723 * Note that timeout functions may be delayed, due to the processing of other
2724 * event sources. Thus they should not be relied on for precise timing.
2725 * After each call to the timeout function, the time of the next
2726 * timeout is recalculated based on the current time and the given interval
2727 * (it does not try to 'catch up' time lost in delays).
2729 * Return value: the id of event source.
2732 g_timeout_add (guint32 interval,
2733 GSourceFunc function,
2736 return g_timeout_add_full (G_PRIORITY_DEFAULT,
2737 interval, function, data, NULL);
2740 /* Idle functions */
2743 g_idle_prepare (GSource *source,
2752 g_idle_check (GSource *source)
2758 g_idle_dispatch (GSource *source,
2759 GSourceFunc callback,
2764 g_warning ("Idle source dispatched without callback\n"
2765 "You must call g_source_set_callback().");
2769 return callback (user_data);
2773 * g_idle_source_new:
2775 * Create a new idle source.
2777 * The source will not initially be associated with any #GMainContext
2778 * and must be added to one with g_source_attach() before it will be
2781 * Return value: the newly created idle source
2784 g_idle_source_new (void)
2786 return g_source_new (&idle_funcs, sizeof (GSource));
2791 * @priority: the priority of the idle source. Typically this will be in the
2792 * range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
2793 * @function: function to call
2794 * @data: data to pass to @function
2795 * @notify: function to call when the idle is removed, or %NULL
2797 * Adds a function to be called whenever there are no higher priority
2798 * events pending. If the function returns FALSE it is automatically
2799 * removed from the list of event sources and will not be called again.
2801 * Return value: the id of the event source.
2804 g_idle_add_full (gint priority,
2805 GSourceFunc function,
2807 GDestroyNotify notify)
2812 g_return_val_if_fail (function != NULL, 0);
2814 source = g_idle_source_new ();
2816 if (priority != G_PRIORITY_DEFAULT)
2817 g_source_set_priority (source, priority);
2819 g_source_set_callback (source, function, data, notify);
2820 id = g_source_attach (source, NULL);
2821 g_source_unref (source);
2828 * @function: function to call
2829 * @data: data to pass to @function.
2831 * Adds a function to be called whenever there are no higher priority
2832 * events pending to the default main loop. The function is given the
2833 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
2834 * returns FALSE it is automatically removed from the list of event
2835 * sources and will not be called again.
2837 * Return value: the id of the event source.
2840 g_idle_add (GSourceFunc function,
2843 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
2847 * g_idle_remove_by_data:
2848 * @data: the data for the idle source's callback.
2850 * Removes the idle function with the given data.
2852 * Return value: %TRUE if an idle source was found and removed.
2855 g_idle_remove_by_data (gpointer data)
2857 return g_source_remove_by_funcs_user_data (&idle_funcs, data);