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)
76 #ifdef G_THREADS_ENABLED
77 typedef struct _GMainWaiter GMainWaiter;
88 #ifdef G_THREADS_ENABLED
89 /* The following lock is used for both the list of sources
90 * and the list of poll records
101 GPtrArray *pending_dispatches;
102 gint timeout; /* Timeout for current iteration */
105 GSource *source_list;
106 gint in_check_or_prepare;
108 GPollRec *poll_records;
109 GPollRec *poll_free_list;
110 GMemChunk *poll_chunk;
111 guint n_poll_records;
112 GPollFD *cached_poll_array;
113 guint cached_poll_array_size;
115 #ifdef G_THREADS_ENABLED
117 /* this pipe is used to wake up the main loop when a source is added.
119 gint wake_up_pipe[2];
120 #else /* G_OS_WIN32 */
121 HANDLE wake_up_semaphore;
122 #endif /* G_OS_WIN32 */
125 gboolean poll_waiting;
127 /* Flag indicating whether the set of fd's changed during a poll */
128 gboolean poll_changed;
129 #endif /* G_THREADS_ENABLED */
133 GTimeVal current_time;
134 gboolean time_is_current;
137 struct _GSourceCallback
142 GDestroyNotify notify;
147 GMainContext *context;
152 struct _GTimeoutSource
166 #ifdef G_THREADS_ENABLED
167 #define LOCK_CONTEXT(context) g_static_mutex_lock (&context->mutex)
168 #define UNLOCK_CONTEXT(context) g_static_mutex_unlock (&context->mutex)
169 #define G_THREAD_SELF g_thread_self ()
171 #define LOCK_CONTEXT(context) (void)0
172 #define UNLOCK_CONTEXT(context) (void)0
173 #define G_THREAD_SELF NULL
176 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
178 #define SOURCE_UNREF(source, context) \
180 if ((source)->ref_count > 1) \
181 (source)->ref_count--; \
183 g_source_unref_internal ((source), (context), TRUE); \
187 /* Forward declarations */
189 static void g_source_unref_internal (GSource *source,
190 GMainContext *context,
192 static void g_source_destroy_internal (GSource *source,
193 GMainContext *context,
195 static void g_main_context_poll (GMainContext *context,
200 static void g_main_context_add_poll_unlocked (GMainContext *context,
203 static void g_main_context_remove_poll_unlocked (GMainContext *context,
205 static void g_main_context_wakeup_unlocked (GMainContext *context);
207 static gboolean g_timeout_prepare (GSource *source,
209 static gboolean g_timeout_check (GSource *source);
210 static gboolean g_timeout_dispatch (GSource *source,
211 GSourceFunc callback,
213 static gboolean g_idle_prepare (GSource *source,
215 static gboolean g_idle_check (GSource *source);
216 static gboolean g_idle_dispatch (GSource *source,
217 GSourceFunc callback,
220 G_LOCK_DEFINE_STATIC (main_loop);
221 static GMainContext *default_main_context;
223 static GSourceFuncs timeout_funcs =
231 static GSourceFuncs idle_funcs =
240 /* SunOS has poll, but doesn't provide a prototype. */
241 # if defined (sun) && !defined (__SVR4)
242 extern gint poll (GPollFD *ufds, guint nfsd, gint timeout);
244 #else /* !HAVE_POLL */
249 g_poll (GPollFD *fds,
253 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
254 gboolean poll_msgs = FALSE;
261 for (f = fds; f < &fds[nfds]; ++f)
264 if (f->events & G_IO_IN)
266 if (f->fd == G_WIN32_MSG_HANDLE)
270 #ifdef G_MAIN_POLL_DEBUG
271 g_print ("g_poll: waiting for %#x\n", f->fd);
273 handles[nhandles++] = (HANDLE) f->fd;
283 /* Waiting for messages, and maybe events
284 * -> First PeekMessage
286 #ifdef G_MAIN_POLL_DEBUG
287 g_print ("PeekMessage\n");
289 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
290 ready = WAIT_OBJECT_0 + nhandles;
295 /* Waiting just for messages */
296 if (timeout == INFINITE)
301 #ifdef G_MAIN_POLL_DEBUG
302 g_print ("WaitMessage\n");
305 g_warning (G_STRLOC ": WaitMessage() failed");
306 ready = WAIT_OBJECT_0 + nhandles;
308 else if (timeout == 0)
310 /* Waiting just for messages, zero timeout.
311 * If we got here, there was no message
313 ready = WAIT_TIMEOUT;
317 /* Waiting just for messages, some timeout
318 * -> Set a timer, wait for message,
319 * kill timer, use PeekMessage
321 timer = SetTimer (NULL, 0, timeout, NULL);
323 g_warning (G_STRLOC ": SetTimer() failed");
326 #ifdef G_MAIN_POLL_DEBUG
327 g_print ("WaitMessage\n");
330 KillTimer (NULL, timer);
331 #ifdef G_MAIN_POLL_DEBUG
332 g_print ("PeekMessage\n");
334 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE)
335 && msg.message != WM_TIMER)
336 ready = WAIT_OBJECT_0;
338 ready = WAIT_TIMEOUT;
344 /* Wait for either message or event
345 * -> Use MsgWaitForMultipleObjects
347 #ifdef G_MAIN_POLL_DEBUG
348 g_print ("MsgWaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
350 ready = MsgWaitForMultipleObjects (nhandles, handles, FALSE,
351 timeout, QS_ALLINPUT);
353 if (ready == WAIT_FAILED)
354 g_warning (G_STRLOC ": MsgWaitForMultipleObjects() failed");
358 else if (nhandles == 0)
360 /* Wait for nothing (huh?) */
365 /* Wait for just events
366 * -> Use WaitForMultipleObjects
368 #ifdef G_MAIN_POLL_DEBUG
369 g_print ("WaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
371 ready = WaitForMultipleObjects (nhandles, handles, FALSE, timeout);
372 if (ready == WAIT_FAILED)
373 g_warning (G_STRLOC ": WaitForMultipleObjects() failed");
376 #ifdef G_MAIN_POLL_DEBUG
377 g_print ("wait returns %d%s\n",
379 (ready == WAIT_FAILED ? " (WAIT_FAILED)" :
380 (ready == WAIT_TIMEOUT ? " (WAIT_TIMEOUT)" :
381 (poll_msgs && ready == WAIT_OBJECT_0 + nhandles ? " (msg)" : ""))));
383 for (f = fds; f < &fds[nfds]; ++f)
386 if (ready == WAIT_FAILED)
388 else if (ready == WAIT_TIMEOUT)
390 else if (poll_msgs && ready == WAIT_OBJECT_0 + nhandles)
392 for (f = fds; f < &fds[nfds]; ++f)
395 if (f->events & G_IO_IN)
396 if (f->fd == G_WIN32_MSG_HANDLE)
397 f->revents |= G_IO_IN;
400 #if TEST_WITHOUT_THIS
401 else if (ready >= WAIT_OBJECT_0 && ready < WAIT_OBJECT_0 + nhandles)
402 for (f = fds; f < &fds[nfds]; ++f)
404 if ((f->events & G_IO_IN)
405 && f->fd == (gint) handles[ready - WAIT_OBJECT_0])
407 f->revents |= G_IO_IN;
408 #ifdef G_MAIN_POLL_DEBUG
409 g_print ("g_poll: got event %#x\n", f->fd);
412 ResetEvent ((HANDLE) f->fd);
421 #else /* !G_OS_WIN32 */
423 /* The following implementation of poll() comes from the GNU C Library.
424 * Copyright (C) 1994, 1996, 1997 Free Software Foundation, Inc.
427 #include <string.h> /* for bzero on BSD systems */
429 #ifdef HAVE_SYS_SELECT_H
430 #include <sys/select.h>
431 #endif /* HAVE_SYS_SELECT_H */
435 #endif /* G_OS_BEOS */
438 # define SELECT_MASK fd_set
439 #else /* !NO_FD_SET */
441 typedef long fd_mask;
444 # define SELECT_MASK void
446 # define SELECT_MASK int
447 # endif /* !_IBMR2 */
448 #endif /* !NO_FD_SET */
451 g_poll (GPollFD *fds,
456 SELECT_MASK rset, wset, xset;
465 for (f = fds; f < &fds[nfds]; ++f)
468 if (f->events & G_IO_IN)
469 FD_SET (f->fd, &rset);
470 if (f->events & G_IO_OUT)
471 FD_SET (f->fd, &wset);
472 if (f->events & G_IO_PRI)
473 FD_SET (f->fd, &xset);
474 if (f->fd > maxfd && (f->events & (G_IO_IN|G_IO_OUT|G_IO_PRI)))
478 tv.tv_sec = timeout / 1000;
479 tv.tv_usec = (timeout % 1000) * 1000;
481 ready = select (maxfd + 1, &rset, &wset, &xset,
482 timeout == -1 ? NULL : &tv);
484 for (f = fds; f < &fds[nfds]; ++f)
489 if (FD_ISSET (f->fd, &rset))
490 f->revents |= G_IO_IN;
491 if (FD_ISSET (f->fd, &wset))
492 f->revents |= G_IO_OUT;
493 if (FD_ISSET (f->fd, &xset))
494 f->revents |= G_IO_PRI;
501 #endif /* !G_OS_WIN32 */
503 #endif /* !HAVE_POLL */
506 * g_main_context_ref:
507 * @loop: a #GMainContext
509 * Increases the reference count on a #GMainContext object by one.
512 g_main_context_ref (GMainContext *context)
514 g_return_if_fail (context != NULL);
515 g_return_if_fail (context->ref_count > 0);
517 LOCK_CONTEXT (context);
519 context->ref_count++;
521 UNLOCK_CONTEXT (context);
525 g_main_context_unref_and_unlock (GMainContext *context)
529 context->ref_count--;
531 if (context->ref_count != 0)
533 UNLOCK_CONTEXT (context);
537 source = context->source_list;
540 GSource *next = source->next;
541 g_source_destroy_internal (source, context, TRUE);
544 UNLOCK_CONTEXT (context);
546 #ifdef G_THREADS_ENABLED
547 g_static_mutex_free (&context->mutex);
550 g_ptr_array_free (context->pending_dispatches, TRUE);
551 g_free (context->cached_poll_array);
553 g_mem_chunk_destroy (context->poll_chunk);
555 #ifdef G_THREADS_ENABLED
556 if (g_thread_supported())
559 close (context->wake_up_pipe[0]);
560 close (context->wake_up_pipe[1]);
562 CloseHandle (context->wake_up_semaphore);
571 * g_main_context_unref:
572 * @loop: a #GMainContext
574 * Decreases the reference count on a #GMainContext object by one. If
575 * the result is zero, free the context and free all associated memory.
578 g_main_context_unref (GMainContext *context)
580 g_return_if_fail (context != NULL);
581 g_return_if_fail (context->ref_count > 0);
583 LOCK_CONTEXT (context);
584 g_main_context_unref_and_unlock (context);
588 * g_main_context_new:
590 * Creates a new #GMainContext strcuture
592 * Return value: the new #GMainContext
595 g_main_context_new ()
597 GMainContext *context = g_new0 (GMainContext, 1);
599 #ifdef G_THREADS_ENABLED
600 g_static_mutex_init (&context->mutex);
602 context->owner = NULL;
603 context->waiters = NULL;
606 context->ref_count = 1;
608 context->next_id = 1;
610 context->source_list = NULL;
613 context->poll_func = (GPollFunc)poll;
615 context->poll_func = g_poll;
618 context->cached_poll_array = NULL;
619 context->cached_poll_array_size = 0;
621 context->pending_dispatches = g_ptr_array_new ();
623 context->time_is_current = FALSE;
625 #ifdef G_THREADS_ENABLED
626 if (g_thread_supported ())
629 if (pipe (context->wake_up_pipe) < 0)
630 g_error ("Cannot create pipe main loop wake-up: %s\n",
633 context->wake_up_rec.fd = context->wake_up_pipe[0];
634 context->wake_up_rec.events = G_IO_IN;
635 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
637 context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
638 if (context->wake_up_semaphore == NULL)
639 g_error ("Cannot create wake-up semaphore: %s",
640 g_win32_error_message (GetLastError ()));
641 context->wake_up_rec.fd = (gint) context->wake_up_semaphore;
642 context->wake_up_rec.events = G_IO_IN;
643 #ifdef G_MAIN_POLL_DEBUG
644 g_print ("wake-up semaphore: %#x\n", (guint) context->wake_up_semaphore);
646 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
655 * g_main_context_default:
657 * Return the default main context. This is the main context used
658 * for main loop functions when a main loop is not explicitly
661 * Return value: the default main context.
664 g_main_context_default (void)
670 if (!default_main_context)
671 default_main_context = g_main_context_new ();
673 G_UNLOCK (main_loop);
675 return default_main_context;
678 /* Hooks for adding to the main loop */
682 * @source_funcs: structure containing functions that implement
683 * the sources behavior.
684 * @struct_size: size of the #GSource structure to create
686 * Create a new GSource structure. The size is specified to
687 * allow creating structures derived from GSource that contain
688 * additional data. The size passed in must be at least
691 * The source will not initially be associated with any #GMainContext
692 * and must be added to one with g_source_add() before it will be
695 * Return value: the newly create #GSource
698 g_source_new (GSourceFuncs *source_funcs,
703 g_return_val_if_fail (source_funcs != NULL, NULL);
704 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
706 source = (GSource*) g_malloc0 (struct_size);
708 source->source_funcs = source_funcs;
709 source->ref_count = 1;
711 source->priority = G_PRIORITY_DEFAULT;
713 source->flags = G_HOOK_FLAG_ACTIVE;
715 /* NULL/0 initialization for all other fields */
720 /* Holds context's lock
723 g_source_list_add (GSource *source,
724 GMainContext *context)
726 GSource *tmp_source, *last_source;
729 tmp_source = context->source_list;
730 while (tmp_source && tmp_source->priority <= source->priority)
732 last_source = tmp_source;
733 tmp_source = tmp_source->next;
736 source->next = tmp_source;
738 tmp_source->prev = source;
740 source->prev = last_source;
742 last_source->next = source;
744 context->source_list = source;
747 /* Holds context's lock
750 g_source_list_remove (GSource *source,
751 GMainContext *context)
754 source->prev->next = source->next;
756 context->source_list = source->next;
759 source->next->prev = source->prev;
767 * @source: a #GSource
768 * @context: a #GMainContext (if %NULL, the default context will be used)
770 * Adds a #GSource to a @context so that it will be executed within
773 * Return value: the ID for the source within the #GMainContext
776 g_source_attach (GSource *source,
777 GMainContext *context)
782 g_return_val_if_fail (source->context == NULL, 0);
783 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
786 context = g_main_context_default ();
788 LOCK_CONTEXT (context);
790 source->context = context;
791 result = source->id = context->next_id++;
794 g_source_list_add (source, context);
796 tmp_list = source->poll_fds;
799 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
800 tmp_list = tmp_list->next;
803 #ifdef G_THREADS_ENABLED
804 /* Now wake up the main loop if it is waiting in the poll() */
805 g_main_context_wakeup_unlocked (context);
808 UNLOCK_CONTEXT (context);
814 g_source_destroy_internal (GSource *source,
815 GMainContext *context,
819 LOCK_CONTEXT (context);
821 if (!SOURCE_DESTROYED (source))
824 gpointer old_cb_data;
825 GSourceCallbackFuncs *old_cb_funcs;
827 source->flags &= ~G_HOOK_FLAG_ACTIVE;
829 old_cb_data = source->callback_data;
830 old_cb_funcs = source->callback_funcs;
832 source->callback_data = NULL;
833 source->callback_funcs = NULL;
837 UNLOCK_CONTEXT (context);
838 old_cb_funcs->unref (old_cb_data);
839 LOCK_CONTEXT (context);
842 tmp_list = source->poll_fds;
845 g_main_context_remove_poll_unlocked (context, tmp_list->data);
846 tmp_list = tmp_list->next;
849 g_source_unref_internal (source, context, TRUE);
853 UNLOCK_CONTEXT (context);
858 * @source: a #GSource
860 * Remove a source from its #GMainContext, if any, and mark it as
861 * destroyed. The source cannot be subsequently added to another
865 g_source_destroy (GSource *source)
867 GMainContext *context;
869 g_return_if_fail (source != NULL);
871 context = source->context;
874 g_source_destroy_internal (source, context, FALSE);
876 source->flags &= ~G_HOOK_FLAG_ACTIVE;
881 * @source: a #GSource
883 * Return the numeric ID for a particular source. The ID of a source
884 * is unique within a particular main loop context. The reverse
885 * mapping from ID to source is done by g_main_context_find_source_by_id().
887 * Return value: the ID for the source
890 g_source_get_id (GSource *source)
894 g_return_val_if_fail (source != NULL, 0);
895 g_return_val_if_fail (source->context != NULL, 0);
897 LOCK_CONTEXT (source->context);
899 UNLOCK_CONTEXT (source->context);
905 * g_source_get_context:
906 * @source: a #GSource
908 * Get the #GMainContext with which the source is associated.
909 * Calling this function on a destroyed source is an error.
911 * Return value: the #GMainContext with which the source is associated,
912 * or %NULL if the context has not yet been added
916 g_source_get_context (GSource *source)
918 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
920 return source->context;
926 * @fd: a #GPollFD structure holding information about a file
927 * descriptor to watch.
929 * Add a file descriptor to the set of file descriptors polled for
930 * this source. This is usually combined with g_source_new() to add an
931 * event source. The event source's check function will typically test
932 * the revents field in the #GPollFD struct and return %TRUE if events need
936 g_source_add_poll (GSource *source,
939 GMainContext *context;
941 g_return_if_fail (source != NULL);
942 g_return_if_fail (fd != NULL);
943 g_return_if_fail (!SOURCE_DESTROYED (source));
945 context = source->context;
948 LOCK_CONTEXT (context);
950 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
954 g_main_context_add_poll_unlocked (context, source->priority, fd);
955 UNLOCK_CONTEXT (context);
960 * g_source_remove_poll:
962 * @fd: a #GPollFD structure previously passed to g_source_poll.
964 * Remove a file descriptor from the set of file descriptors polled for
968 g_source_remove_poll (GSource *source,
971 GMainContext *context;
973 g_return_if_fail (source != NULL);
974 g_return_if_fail (fd != NULL);
975 g_return_if_fail (!SOURCE_DESTROYED (source));
977 context = source->context;
980 LOCK_CONTEXT (context);
982 source->poll_fds = g_slist_remove (source->poll_fds, fd);
986 g_main_context_remove_poll_unlocked (context, fd);
987 UNLOCK_CONTEXT (context);
992 * g_source_set_callback_indirect:
993 * @source: the source
994 * @callback_data: pointer to callback data "object"
995 * @callback_funcs: functions for reference counting callback_data
996 * and getting the callback and data
998 * Set the callback function storing the data as a refcounted callback
999 * "object". This is used to implement g_source_set_callback_closure()
1000 * and internally. Note that calling g_source_set_callback_indirect() assumes
1001 * an initial reference count on @callback_data, and thus
1002 * @callback_funcs->unref will eventually be called once more
1003 * than @callback_funcs->ref.
1006 g_source_set_callback_indirect (GSource *source,
1007 gpointer callback_data,
1008 GSourceCallbackFuncs *callback_funcs)
1010 GMainContext *context;
1011 gpointer old_cb_data;
1012 GSourceCallbackFuncs *old_cb_funcs;
1014 g_return_if_fail (source != NULL);
1015 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1017 context = source->context;
1020 LOCK_CONTEXT (context);
1022 old_cb_data = source->callback_data;
1023 old_cb_funcs = source->callback_funcs;
1025 source->callback_data = callback_data;
1026 source->callback_funcs = callback_funcs;
1029 UNLOCK_CONTEXT (context);
1032 old_cb_funcs->unref (old_cb_data);
1036 g_source_callback_ref (gpointer cb_data)
1038 GSourceCallback *callback = cb_data;
1040 callback->ref_count++;
1045 g_source_callback_unref (gpointer cb_data)
1047 GSourceCallback *callback = cb_data;
1049 callback->ref_count--;
1050 if (callback->ref_count == 0)
1052 if (callback->notify)
1053 callback->notify (callback->data);
1059 g_source_callback_get (gpointer cb_data,
1063 GSourceCallback *callback = cb_data;
1065 *func = callback->func;
1066 *data = callback->data;
1069 static GSourceCallbackFuncs g_source_callback_funcs = {
1070 g_source_callback_ref,
1071 g_source_callback_unref,
1072 g_source_callback_get,
1076 * g_source_set_callback:
1077 * @source: the source
1078 * @func: a callback function
1079 * @data: the data to pass to callback function
1080 * @notify: a function to call when @data is no longer in use, or %NULL.
1082 * Set the callback function for a source.
1085 g_source_set_callback (GSource *source,
1088 GDestroyNotify notify)
1090 GSourceCallback *new_callback;
1092 g_return_if_fail (source != NULL);
1094 new_callback = g_new (GSourceCallback, 1);
1096 new_callback->ref_count = 1;
1097 new_callback->func = func;
1098 new_callback->data = data;
1099 new_callback->notify = notify;
1101 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1105 * g_source_set_priority:
1106 * @source: a #GSource
1107 * @priority: the new priority.
1109 * Set the priority of a source. While the main loop is being
1110 * run, a source will
1113 g_source_set_priority (GSource *source,
1117 GMainContext *context;
1119 g_return_if_fail (source != NULL);
1121 context = source->context;
1124 LOCK_CONTEXT (context);
1126 source->priority = priority;
1130 source->next = NULL;
1131 source->prev = NULL;
1133 tmp_list = source->poll_fds;
1136 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1137 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1139 tmp_list = tmp_list->next;
1142 UNLOCK_CONTEXT (source->context);
1147 * g_source_get_priority:
1148 * @source: a #GSource
1150 * Gets the priority of a surce
1152 * Return value: the priority of the source
1155 g_source_get_priority (GSource *source)
1157 g_return_val_if_fail (source != NULL, 0);
1159 return source->priority;
1163 * g_source_set_can_recurse:
1164 * @source: a #GSource
1165 * @can_recurse: whether recursion is allowed for this source
1167 * Sets whether a source can be called recursively. If @can_recurse is
1168 * %TRUE, then while the source is being dispatched then this source
1169 * will be processed normally. Otherwise, all processing of this
1170 * source is blocked until the dispatch function returns.
1173 g_source_set_can_recurse (GSource *source,
1174 gboolean can_recurse)
1176 GMainContext *context;
1178 g_return_if_fail (source != NULL);
1180 context = source->context;
1183 LOCK_CONTEXT (context);
1186 source->flags |= G_SOURCE_CAN_RECURSE;
1188 source->flags &= ~G_SOURCE_CAN_RECURSE;
1191 UNLOCK_CONTEXT (context);
1195 * g_source_get_can_recurse:
1196 * @source: a #GSource
1198 * Checks whether a source is allowed to be called recursively.
1199 * see g_source_set_can_recurse.
1201 * Return value: whether recursion is allowed.
1204 g_source_get_can_recurse (GSource *source)
1206 g_return_val_if_fail (source != NULL, FALSE);
1208 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1213 * @source: a #GSource
1215 * Increases the reference count on a source by one.
1217 * Return value: @source
1220 g_source_ref (GSource *source)
1222 GMainContext *context;
1224 g_return_val_if_fail (source != NULL, NULL);
1226 context = source->context;
1229 LOCK_CONTEXT (context);
1231 source->ref_count++;
1234 UNLOCK_CONTEXT (context);
1239 /* g_source_unref() but possible to call within context lock
1242 g_source_unref_internal (GSource *source,
1243 GMainContext *context,
1246 gpointer old_cb_data = NULL;
1247 GSourceCallbackFuncs *old_cb_funcs = NULL;
1249 g_return_if_fail (source != NULL);
1251 if (!have_lock && context)
1252 LOCK_CONTEXT (context);
1254 source->ref_count--;
1255 if (source->ref_count == 0)
1257 old_cb_data = source->callback_data;
1258 old_cb_funcs = source->callback_funcs;
1260 source->callback_data = NULL;
1261 source->callback_funcs = NULL;
1263 if (context && !SOURCE_DESTROYED (source))
1265 g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1266 source->ref_count++;
1269 g_source_list_remove (source, context);
1271 if (source->source_funcs->finalize)
1272 source->source_funcs->finalize (source);
1274 g_slist_free (source->poll_fds);
1275 source->poll_fds = NULL;
1279 if (!have_lock && context)
1280 UNLOCK_CONTEXT (context);
1285 UNLOCK_CONTEXT (context);
1287 old_cb_funcs->unref (old_cb_data);
1290 LOCK_CONTEXT (context);
1296 * @source: a #GSource
1298 * Decreases the reference count of a source by one. If the
1299 * resulting reference count is zero the source and associated
1300 * memory will be destroyed.
1303 g_source_unref (GSource *source)
1305 g_return_if_fail (source != NULL);
1307 g_source_unref_internal (source, source->context, FALSE);
1311 * g_main_context_find_source_by_id:
1312 * @context: a #GMainContext (if %NULL, the default context will be used)
1313 * @id: the source ID, as returned by g_source_get_id()
1315 * Finds a #GSource given a pair of context and ID
1317 * Return value: the #GSource if found, otherwise, %NULL
1320 g_main_context_find_source_by_id (GMainContext *context,
1325 g_return_val_if_fail (id > 0, FALSE);
1327 if (context == NULL)
1328 context = g_main_context_default ();
1330 LOCK_CONTEXT (context);
1332 source = context->source_list;
1335 if (!SOURCE_DESTROYED (source) &&
1338 source = source->next;
1341 UNLOCK_CONTEXT (context);
1347 * g_main_context_find_source_by_funcs_user_data:
1348 * @context: a #GMainContext (if %NULL, the default context will be used).
1349 * @funcs: the @source_funcs passed to g_source_new().
1350 * @user_data: the user data from the callback.
1352 * Finds a source with the given source functions and user data. If
1353 * multiple sources exist with the same source function and user data,
1354 * the first one found will be returned.
1356 * Return value: the source, if one was found, otherwise %NULL
1359 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1360 GSourceFuncs *funcs,
1365 g_return_val_if_fail (funcs != NULL, FALSE);
1367 if (context == NULL)
1368 context = g_main_context_default ();
1370 LOCK_CONTEXT (context);
1372 source = context->source_list;
1375 if (!SOURCE_DESTROYED (source) &&
1376 source->source_funcs == funcs &&
1377 source->callback_data == user_data)
1379 source = source->next;
1382 UNLOCK_CONTEXT (context);
1388 * g_main_context_find_source_by_user_data:
1389 * @context: a #GMainContext
1390 * @user_data: the user_data for the callback.
1392 * Finds a source with the given user data for the callback. If
1393 * multiple sources exist with the same user data, the first
1394 * one found will be returned.
1396 * Return value: the source, if one was found, otherwise %NULL
1399 g_main_context_find_source_by_user_data (GMainContext *context,
1404 if (context == NULL)
1405 context = g_main_context_default ();
1407 LOCK_CONTEXT (context);
1409 source = context->source_list;
1412 if (!SOURCE_DESTROYED (source) &&
1413 source->callback_data == user_data)
1415 source = source->next;
1418 UNLOCK_CONTEXT (context);
1425 * @tag: the id of the source to remove.
1427 * Removes the source with the given id from the default main
1428 * context. The id of a #GSource is given by g_source_get_id(),
1429 * or will be returned by the functions g_source_attach(),
1430 * g_idle_add(), g_idle_add_full(), g_timeout_add(),
1431 * g_timeout_add_full(), g_io_add_watch, and g_io_add_watch_full().
1433 * See also g_source_destroy().
1435 * Return value: %TRUE if the source was found and removed.
1438 g_source_remove (guint tag)
1442 g_return_val_if_fail (tag > 0, FALSE);
1444 source = g_main_context_find_source_by_id (NULL, tag);
1446 g_source_destroy (source);
1448 return source != NULL;
1452 * g_source_remove_by_user_data:
1453 * @user_data: the user_data for the callback.
1455 * Removes a source from the default main loop context given the user
1456 * data for the callback. If multiple sources exist with the same user
1457 * data, only one will be destroyed.
1459 * Return value: %TRUE if a source was found and removed.
1462 g_source_remove_by_user_data (gpointer user_data)
1466 source = g_main_context_find_source_by_user_data (NULL, user_data);
1469 g_source_destroy (source);
1477 * g_source_remove_by_funcs_user_data:
1478 * @funcs: The @source_funcs passed to g_source_new()
1479 * @user_data: the user data for the callback
1481 * Removes a source from the default main loop context given the
1482 * source functions and user data. If multiple sources exist with the
1483 * same source functions and user data, only one will be destroyed.
1485 * Return value: %TRUE if a source was found and removed.
1488 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1493 g_return_val_if_fail (funcs != NULL, FALSE);
1495 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1498 g_source_destroy (source);
1506 * g_get_current_time:
1507 * @result: #GTimeVal structure in which to store current time.
1509 * Equivalent to Unix's <function>gettimeofday()</function>, but portable
1512 g_get_current_time (GTimeVal *result)
1517 g_return_if_fail (result != NULL);
1519 /*this is required on alpha, there the timeval structs are int's
1520 not longs and a cast only would fail horribly*/
1521 gettimeofday (&r, NULL);
1522 result->tv_sec = r.tv_sec;
1523 result->tv_usec = r.tv_usec;
1525 /* Avoid calling time() except for the first time.
1526 * GetTickCount() should be pretty fast and low-level?
1527 * I could also use ftime() but it seems unnecessarily overheady.
1529 static DWORD start_tick = 0;
1530 static time_t start_time;
1533 g_return_if_fail (result != NULL);
1535 if (start_tick == 0)
1537 start_tick = GetTickCount ();
1541 tick = GetTickCount ();
1543 result->tv_sec = (tick - start_tick) / 1000 + start_time;
1544 result->tv_usec = ((tick - start_tick) % 1000) * 1000;
1548 /* Running the main loop */
1550 /* HOLDS: context's lock */
1552 g_main_dispatch (GMainContext *context)
1556 for (i = 0; i < context->pending_dispatches->len; i++)
1558 GSource *source = context->pending_dispatches->pdata[i];
1560 context->pending_dispatches->pdata[i] = NULL;
1563 source->flags &= ~G_SOURCE_READY;
1565 if (!SOURCE_DESTROYED (source))
1567 gboolean was_in_call;
1568 gpointer user_data = NULL;
1569 GSourceFunc callback = NULL;
1570 GSourceCallbackFuncs *cb_funcs;
1572 gboolean need_destroy;
1574 gboolean (*dispatch) (GSource *,
1578 dispatch = source->source_funcs->dispatch;
1579 cb_funcs = source->callback_funcs;
1580 cb_data = source->callback_data;
1583 cb_funcs->ref (cb_data);
1585 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
1586 source->flags |= G_HOOK_FLAG_IN_CALL;
1588 UNLOCK_CONTEXT (context);
1591 cb_funcs->get (cb_data, &callback, &user_data);
1593 need_destroy = ! dispatch (source,
1596 LOCK_CONTEXT (context);
1599 cb_funcs->unref (cb_data);
1602 source->flags &= ~G_HOOK_FLAG_IN_CALL;
1604 /* Note: this depends on the fact that we can't switch
1605 * sources from one main context to another
1607 if (need_destroy && !SOURCE_DESTROYED (source))
1609 g_assert (source->context == context);
1610 g_source_destroy_internal (source, context, TRUE);
1614 SOURCE_UNREF (source, context);
1617 g_ptr_array_set_size (context->pending_dispatches, 0);
1620 /* Holds context's lock */
1621 static inline GSource *
1622 next_valid_source (GMainContext *context,
1625 GSource *new_source = source ? source->next : context->source_list;
1629 if (!SOURCE_DESTROYED (new_source))
1631 new_source->ref_count++;
1635 new_source = new_source->next;
1639 SOURCE_UNREF (source, context);
1645 * g_main_context_acquire:
1646 * @context: a #GMainContext
1648 * Tries to become the owner of the specified context.
1649 * If some other context is the owner of the context,
1650 * returns %FALSE immediately. Ownership is properly
1651 * recursive: the owner can require ownership again
1652 * and will release ownership when g_main_context_release()
1653 * is called as many times as g_main_context_acquire().
1655 * You must be the owner of a context before you
1656 * can call g_main_context_prepare(), g_main_context_query(),
1657 * g_main_context_check(), g_main_context_dispatch().
1659 * Return value: %TRUE if the operation succeeded, and
1660 * this thread is now the owner of @context.
1663 g_main_context_acquire (GMainContext *context)
1665 #ifdef G_THREAD_ENABLED
1666 gboolean result = FALSE;
1667 GThread *self = G_THREAD_SELF;
1669 if (context == NULL)
1670 context = g_main_context_default ();
1672 LOCK_CONTEXT (context);
1674 if (!context->owner)
1676 context->owner = self;
1677 g_assert (context->owner_count == 0);
1680 if (context->owner == self)
1682 context->owner_count++;
1686 UNLOCK_CONTEXT (context);
1689 #else /* !G_THREAD_ENABLED */
1691 #endif /* G_THREAD_ENABLED */
1695 * g_main_context_release:
1696 * @context: a #GMainContext
1698 * Release ownership of a context previously acquired by this thread
1699 * with g_main_context_acquire(). If the context was acquired multiple
1700 * times, the only release ownership when g_main_context_release()
1701 * is called as many times as it was acquired.
1704 g_main_context_release (GMainContext *context)
1706 #ifdef G_THREAD_ENABLED
1707 if (context == NULL)
1708 context = g_main_context_default ();
1710 LOCK_CONTEXT (context);
1712 context->owner_count--;
1713 if (context->owner_count == 0)
1715 context->owner = NULL;
1717 if (context->waiters)
1719 GMainWaiter *waiter = context->waiters->data;
1720 gboolean loop_internal_waiter =
1721 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
1722 context->waiters = g_slist_delete_link (context->waiters,
1724 if (!loop_internal_waiter)
1725 g_mutex_lock (waiter->mutex);
1727 g_cond_signal (waiter->cond);
1729 if (!loop_internal_waiter)
1730 g_mutex_unlock (waiter->mutex);
1734 UNLOCK_CONTEXT (context);
1737 #endif /* G_THREAD_ENABLED */
1741 * g_main_context_wait:
1742 * @context: a #GMainContext
1743 * @cond: a condition variable
1744 * @mutex: a mutex, currently held
1746 * Tries to become the owner of the specified context,
1747 * as with g_main_context_acquire. But if another thread
1748 * is the owner, atomically drop @mutex and wait on
1749 * @cond until wait until that owner releases
1750 * ownership or until @cond is signaled, then
1751 * try again (once) to become the owner.
1753 * Return value: %TRUE if the operation succeeded, and
1754 * this thread is now the owner of @context.
1757 g_main_context_wait (GMainContext *context,
1761 #ifdef G_THREAD_ENABLED
1762 gboolean result = FALSE;
1763 GThread *self = G_THREAD_SELF;
1764 gboolean loop_internal_waiter;
1766 if (context == NULL)
1767 context = g_main_context_default ();
1769 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
1771 if (!loop_internal_waiter)
1772 LOCK_CONTEXT (context);
1774 if (context->owner && context->owner != self)
1779 waiter.mutex = mutex;
1781 context->waiters = g_slist_append (context->waiters, &waiter);
1783 if (!loop_internal_waiter)
1784 UNLOCK_CONTEXT (context);
1785 g_cond_wait (cond, mutex);
1786 if (!loop_internal_waiter)
1787 LOCK_CONTEXT (context);
1789 context->waiters = g_slist_remove (context->waiters, &waiter);
1792 if (!context->owner)
1794 context->owner = self;
1795 g_assert (context->owner_count == 0);
1798 if (context->owner == self)
1800 context->owner_count++;
1804 if (!loop_internal_waiter)
1805 UNLOCK_CONTEXT (context);
1808 #else /* !G_THREAD_ENABLED */
1810 #endif /* G_THREAD_ENABLED */
1814 * g_main_context_prepare:
1815 * @context: a #GMainContext
1816 * @priority: location to store priority of highest priority
1817 * source already ready.
1819 * Prepares to poll sources within a main loop. The resulting information
1820 * for polling is determined by calling g_main_context_query ().
1822 * Return value: %TRUE if some source is ready to be dispatched
1826 g_main_context_prepare (GMainContext *context,
1830 gint current_priority = G_MAXINT;
1833 if (context == NULL)
1834 context = g_main_context_default ();
1836 LOCK_CONTEXT (context);
1838 context->time_is_current = FALSE;
1840 if (context->in_check_or_prepare)
1842 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
1843 "prepare() member.");
1844 UNLOCK_CONTEXT (context);
1848 #ifdef G_THREADS_ENABLED
1849 if (context->poll_waiting)
1851 g_warning("g_main_context_prepare(): main loop already active in another thread");
1852 UNLOCK_CONTEXT (context);
1856 context->poll_waiting = TRUE;
1857 #endif /* G_THREADS_ENABLED */
1860 /* If recursing, finish up current dispatch, before starting over */
1861 if (context->pending_dispatches)
1864 g_main_dispatch (context, ¤t_time);
1866 UNLOCK_CONTEXT (context);
1871 /* If recursing, clear list of pending dispatches */
1872 g_ptr_array_set_size (context->pending_dispatches, 0);
1874 /* Prepare all sources */
1876 context->timeout = -1;
1878 source = next_valid_source (context, NULL);
1881 gint source_timeout = -1;
1883 if ((n_ready > 0) && (source->priority > current_priority))
1885 SOURCE_UNREF (source, context);
1888 if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
1891 if (!(source->flags & G_SOURCE_READY))
1894 gboolean (*prepare) (GSource *source,
1897 prepare = source->source_funcs->prepare;
1898 context->in_check_or_prepare++;
1899 UNLOCK_CONTEXT (context);
1901 result = (*prepare) (source, &source_timeout);
1903 LOCK_CONTEXT (context);
1904 context->in_check_or_prepare--;
1907 source->flags |= G_SOURCE_READY;
1910 if (source->flags & G_SOURCE_READY)
1913 current_priority = source->priority;
1914 context->timeout = 0;
1917 if (source_timeout >= 0)
1919 if (context->timeout < 0)
1920 context->timeout = source_timeout;
1922 context->timeout = MIN (context->timeout, source_timeout);
1926 source = next_valid_source (context, source);
1929 UNLOCK_CONTEXT (context);
1932 *priority = current_priority;
1934 return (n_ready > 0);
1938 * g_main_context_query:
1939 * @context: a #GMainContext
1940 * @max_priority: maximum priority source to check
1941 * @timeout: location to store timeout to be used in polling
1942 * @fds: location to store #GPollFD records that need to be polled.
1943 * @n_fds: length of @fds.
1945 * Determines information necessary to poll this main loop.
1950 g_main_context_query (GMainContext *context,
1959 LOCK_CONTEXT (context);
1961 pollrec = context->poll_records;
1963 while (pollrec && max_priority >= pollrec->priority)
1965 if (pollrec->fd->events)
1969 fds[n_poll].fd = pollrec->fd->fd;
1970 /* In direct contradiction to the Unix98 spec, IRIX runs into
1971 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
1972 * flags in the events field of the pollfd while it should
1973 * just ignoring them. So we mask them out here.
1975 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
1976 fds[n_poll].revents = 0;
1981 pollrec = pollrec->next;
1984 #ifdef G_THREADS_ENABLED
1985 context->poll_changed = FALSE;
1990 *timeout = context->timeout;
1992 context->time_is_current = FALSE;
1995 UNLOCK_CONTEXT (context);
2001 * g_main_context_check:
2002 * @context: a #GMainContext
2003 * @max_priority: the maximum numerical priority of sources to check
2004 * @fds: array of #GPollFD's that was passed to the last call to
2005 * g_main_context_query()
2006 * @n_fds: return value of g_main_context_query()
2008 * Pass the results of polling back to the main loop.
2010 * Return value: %TRUE if some sources are ready to be dispatched.
2013 g_main_context_check (GMainContext *context,
2023 LOCK_CONTEXT (context);
2025 if (context->in_check_or_prepare)
2027 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2028 "prepare() member.");
2029 UNLOCK_CONTEXT (context);
2033 #ifdef G_THREADS_ENABLED
2034 if (!context->poll_waiting)
2038 read (context->wake_up_pipe[0], &c, 1);
2042 context->poll_waiting = FALSE;
2044 /* If the set of poll file descriptors changed, bail out
2045 * and let the main loop rerun
2047 if (context->poll_changed)
2049 UNLOCK_CONTEXT (context);
2052 #endif /* G_THREADS_ENABLED */
2054 pollrec = context->poll_records;
2058 if (pollrec->fd->events)
2060 pollrec->fd->revents = fds[i].revents;
2063 pollrec = pollrec->next;
2066 source = next_valid_source (context, NULL);
2069 if ((n_ready > 0) && (source->priority > max_priority))
2071 SOURCE_UNREF (source, context);
2074 if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
2077 if (!(source->flags & G_SOURCE_READY))
2080 gboolean (*check) (GSource *source);
2082 check = source->source_funcs->check;
2084 context->in_check_or_prepare++;
2085 UNLOCK_CONTEXT (context);
2087 result = (*check) (source);
2089 LOCK_CONTEXT (context);
2090 context->in_check_or_prepare--;
2093 source->flags |= G_SOURCE_READY;
2096 if (source->flags & G_SOURCE_READY)
2098 source->ref_count++;
2099 g_ptr_array_add (context->pending_dispatches, source);
2105 source = next_valid_source (context, source);
2108 UNLOCK_CONTEXT (context);
2114 * g_main_context_dispatch:
2115 * @context: a #GMainContext
2117 * Dispatch all pending sources()
2120 g_main_context_dispatch (GMainContext *context)
2122 LOCK_CONTEXT (context);
2124 if (context->pending_dispatches->len > 0)
2126 g_main_dispatch (context);
2129 UNLOCK_CONTEXT (context);
2132 /* HOLDS context lock */
2134 g_main_context_iterate (GMainContext *context,
2141 gboolean some_ready;
2142 gint nfds, allocated_nfds;
2143 GPollFD *fds = NULL;
2145 UNLOCK_CONTEXT (context);
2147 #ifdef G_THREADS_ENABLED
2148 if (!g_main_context_acquire (context))
2150 gboolean got_ownership;
2152 g_return_val_if_fail (g_thread_supported (), FALSE);
2157 LOCK_CONTEXT (context);
2160 context->cond = g_cond_new ();
2162 got_ownership = g_main_context_wait (context,
2164 g_static_mutex_get_mutex (&context->mutex));
2168 UNLOCK_CONTEXT (context);
2173 LOCK_CONTEXT (context);
2174 #endif /* G_THREADS_ENABLED */
2176 if (!context->cached_poll_array)
2178 context->cached_poll_array_size = context->n_poll_records;
2179 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2182 allocated_nfds = context->cached_poll_array_size;
2183 fds = context->cached_poll_array;
2185 UNLOCK_CONTEXT (context);
2187 some_ready = g_main_context_prepare (context, &max_priority);
2189 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
2190 allocated_nfds)) > allocated_nfds)
2192 LOCK_CONTEXT (context);
2194 context->cached_poll_array_size = allocated_nfds = nfds;
2195 context->cached_poll_array = fds = g_new (GPollFD, nfds);
2196 UNLOCK_CONTEXT (context);
2202 g_main_context_poll (context, timeout, max_priority, fds, nfds);
2204 g_main_context_check (context, max_priority, fds, nfds);
2207 g_main_context_dispatch (context);
2209 #ifdef G_THREADS_ENABLED
2210 g_main_context_release (context);
2211 #endif /* G_THREADS_ENABLED */
2213 LOCK_CONTEXT (context);
2219 * g_main_context_pending:
2220 * @context: a #GMainContext (if %NULL, the default context will be used)
2222 * Check if any sources have pending events for the given context.
2224 * Return value: %TRUE if events are pending.
2227 g_main_context_pending (GMainContext *context)
2232 context = g_main_context_default();
2234 LOCK_CONTEXT (context);
2235 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
2236 UNLOCK_CONTEXT (context);
2242 * g_main_context_iteration:
2243 * @context: a #GMainContext (if %NULL, the default context will be used)
2244 * @may_block: whether the call may block.
2246 * Run a single iteration for the given main loop. This involves
2247 * checking to see if any event sources are ready to be processed,
2248 * then if no events sources are ready and @may_block is %TRUE, waiting
2249 * for a source to become ready, then dispatching the highest priority
2250 * events sources that are ready. Note that even when @may_block is %TRUE,
2251 * it is still possible for g_main_context_iteration() to return
2252 * %FALSE, since the the wait may be interrupted for other
2253 * reasons than an event source becoming ready.
2255 * Return value: %TRUE if events were dispatched.
2258 g_main_context_iteration (GMainContext *context, gboolean may_block)
2263 context = g_main_context_default();
2265 LOCK_CONTEXT (context);
2266 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
2267 UNLOCK_CONTEXT (context);
2274 * @context: a #GMainContext (if %NULL, the default context will be used).
2275 * @is_running: set to TRUE to indicate that the loop is running. This
2276 * is not very important since calling g_main_run() will set this to
2279 * Create a new #GMainLoop structure
2284 g_main_loop_new (GMainContext *context,
2285 gboolean is_running)
2290 context = g_main_context_default();
2292 g_main_context_ref (context);
2294 loop = g_new0 (GMainLoop, 1);
2295 loop->context = context;
2296 loop->is_running = is_running != FALSE;
2297 loop->ref_count = 1;
2304 * @loop: a #GMainLoop
2306 * Increase the reference count on a #GMainLoop object by one.
2308 * Return value: @loop
2311 g_main_loop_ref (GMainLoop *loop)
2313 g_return_val_if_fail (loop != NULL, NULL);
2314 g_return_val_if_fail (loop->ref_count > 0, NULL);
2316 LOCK_CONTEXT (loop->context);
2318 UNLOCK_CONTEXT (loop->context);
2324 g_main_loop_unref_and_unlock (GMainLoop *loop)
2327 if (loop->ref_count == 0)
2329 /* When the ref_count is 0, there can be nobody else using the
2330 * loop, so it is safe to unlock before destroying.
2332 g_main_context_unref_and_unlock (loop->context);
2336 UNLOCK_CONTEXT (loop->context);
2340 * g_main_loop_unref:
2341 * @loop: a #GMainLoop
2343 * Decreases the reference count on a #GMainLoop object by one. If
2344 * the result is zero, free the loop and free all associated memory.
2347 g_main_loop_unref (GMainLoop *loop)
2349 g_return_if_fail (loop != NULL);
2350 g_return_if_fail (loop->ref_count > 0);
2352 LOCK_CONTEXT (loop->context);
2354 g_main_loop_unref_and_unlock (loop);
2359 * @loop: a #GMainLoop
2361 * Run a main loop until g_main_quit() is called on the loop.
2362 * If this is called for the thread of the loop's #GMainContext,
2363 * it will process events from the loop, otherwise it will
2367 g_main_loop_run (GMainLoop *loop)
2369 GThread *self = G_THREAD_SELF;
2371 g_return_if_fail (loop != NULL);
2372 g_return_if_fail (loop->ref_count > 0);
2374 #ifdef G_THREADS_ENABLED
2375 if (!g_main_context_acquire (loop->context))
2377 gboolean got_ownership = FALSE;
2379 /* Another thread owns this context */
2380 if (!g_thread_supported ())
2382 g_warning ("g_main_loop_run() was called from second thread but"
2383 "g_thread_init() was never called.");
2387 LOCK_CONTEXT (loop->context);
2391 if (!loop->is_running)
2392 loop->is_running = TRUE;
2394 if (!loop->context->cond)
2395 loop->context->cond = g_cond_new ();
2397 while (loop->is_running || !got_ownership)
2398 got_ownership = g_main_context_wait (loop->context,
2399 loop->context->cond,
2400 g_static_mutex_get_mutex (&loop->context->mutex));
2402 if (!loop->is_running)
2404 UNLOCK_CONTEXT (loop->context);
2406 g_main_context_release (loop->context);
2407 g_main_loop_unref (loop);
2411 g_assert (got_ownership);
2414 LOCK_CONTEXT (loop->context);
2415 #endif /* G_THREADS_ENABLED */
2417 if (loop->context->in_check_or_prepare)
2419 g_warning ("g_main_run(): called recursively from within a source's check() or "
2420 "prepare() member, iteration not possible.");
2425 loop->is_running = TRUE;
2426 while (loop->is_running)
2427 g_main_context_iterate (loop->context, TRUE, TRUE, self);
2429 #ifdef G_THREADS_ENABLED
2430 g_main_context_release (loop->context);
2431 #endif /* G_THREADS_ENABLED */
2433 g_main_loop_unref_and_unlock (loop);
2438 * @loop: a #GMainLoop
2440 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
2441 * for the loop will return.
2444 g_main_loop_quit (GMainLoop *loop)
2446 g_return_if_fail (loop != NULL);
2447 g_return_if_fail (loop->ref_count > 0);
2449 LOCK_CONTEXT (loop->context);
2450 loop->is_running = FALSE;
2451 g_main_context_wakeup_unlocked (loop->context);
2453 if (loop->context->cond)
2454 g_cond_broadcast (loop->context->cond);
2455 UNLOCK_CONTEXT (loop->context);
2459 * g_main_loop_is_running:
2460 * @loop: a #GMainLoop.
2462 * Check to see if the main loop is currently being run via g_main_run()
2464 * Return value: %TRUE if the mainloop is currently being run.
2467 g_main_loop_is_running (GMainLoop *loop)
2469 g_return_val_if_fail (loop != NULL, FALSE);
2470 g_return_val_if_fail (loop->ref_count > 0, FALSE);
2472 return loop->is_running;
2476 * g_main_loop_get_context:
2477 * @loop: a #GMainLoop.
2479 * Returns the #GMainContext of @loop.
2481 * Return value: the #GMainContext of @loop
2484 g_main_loop_get_context (GMainLoop *loop)
2486 g_return_val_if_fail (loop != NULL, NULL);
2487 g_return_val_if_fail (loop->ref_count > 0, NULL);
2489 return loop->context;
2492 /* HOLDS: context's lock */
2494 g_main_context_poll (GMainContext *context,
2500 #ifdef G_MAIN_POLL_DEBUG
2506 GPollFunc poll_func;
2508 if (n_fds || timeout != 0)
2510 #ifdef G_MAIN_POLL_DEBUG
2511 g_print ("g_main_poll(%d) timeout: %d\n", n_fds, timeout);
2512 poll_timer = g_timer_new ();
2515 LOCK_CONTEXT (context);
2517 poll_func = context->poll_func;
2519 UNLOCK_CONTEXT (context);
2520 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
2521 g_warning ("poll(2) failed due to: %s.",
2522 g_strerror (errno));
2524 #ifdef G_MAIN_POLL_DEBUG
2525 LOCK_CONTEXT (context);
2527 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
2530 g_timer_elapsed (poll_timer, NULL));
2531 g_timer_destroy (poll_timer);
2532 pollrec = context->poll_records;
2536 if (pollrec->fd->events)
2540 g_print (" [%d:", fds[i].fd);
2541 if (fds[i].revents & G_IO_IN)
2543 if (fds[i].revents & G_IO_OUT)
2545 if (fds[i].revents & G_IO_PRI)
2547 if (fds[i].revents & G_IO_ERR)
2549 if (fds[i].revents & G_IO_HUP)
2551 if (fds[i].revents & G_IO_NVAL)
2557 pollrec = pollrec->next;
2561 UNLOCK_CONTEXT (context);
2563 } /* if (n_fds || timeout != 0) */
2567 * g_main_context_add_poll:
2568 * @context: a #GMainContext (or %NULL for the default context)
2569 * @fd: a #GPollFD structure holding information about a file
2570 * descriptor to watch.
2571 * @priority: the priority for this file descriptor which should be
2572 * the same as the priority used for g_source_attach() to ensure that the
2573 * file descriptor is polled whenever the results may be needed.
2575 * Add a file descriptor to the set of file descriptors polled * for
2576 * this context. This will very seldom be used directly. Instead
2577 * a typical event source will use g_source_add_poll() instead.
2580 g_main_context_add_poll (GMainContext *context,
2585 context = g_main_context_default ();
2587 g_return_if_fail (context->ref_count > 0);
2588 g_return_if_fail (fd);
2590 LOCK_CONTEXT (context);
2591 g_main_context_add_poll_unlocked (context, priority, fd);
2592 UNLOCK_CONTEXT (context);
2595 /* HOLDS: main_loop_lock */
2597 g_main_context_add_poll_unlocked (GMainContext *context,
2601 GPollRec *lastrec, *pollrec, *newrec;
2603 if (!context->poll_chunk)
2604 context->poll_chunk = g_mem_chunk_create (GPollRec, 32, G_ALLOC_ONLY);
2606 if (context->poll_free_list)
2608 newrec = context->poll_free_list;
2609 context->poll_free_list = newrec->next;
2612 newrec = g_chunk_new (GPollRec, context->poll_chunk);
2614 /* This file descriptor may be checked before we ever poll */
2617 newrec->priority = priority;
2620 pollrec = context->poll_records;
2621 while (pollrec && priority >= pollrec->priority)
2624 pollrec = pollrec->next;
2628 lastrec->next = newrec;
2630 context->poll_records = newrec;
2632 newrec->next = pollrec;
2634 context->n_poll_records++;
2635 if (context->cached_poll_array &&
2636 context->cached_poll_array_size < context->n_poll_records)
2638 g_free (context->cached_poll_array);
2639 context->cached_poll_array = NULL;
2642 #ifdef G_THREADS_ENABLED
2643 context->poll_changed = TRUE;
2645 /* Now wake up the main loop if it is waiting in the poll() */
2646 g_main_context_wakeup_unlocked (context);
2651 * g_main_context_remove_poll:
2652 * @context:a #GMainContext
2653 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
2655 * Remove file descriptor from the set of file descriptors to be
2656 * polled for a particular context.
2659 g_main_context_remove_poll (GMainContext *context,
2663 context = g_main_context_default ();
2665 g_return_if_fail (context->ref_count > 0);
2666 g_return_if_fail (fd);
2668 LOCK_CONTEXT (context);
2669 g_main_context_remove_poll_unlocked (context, fd);
2670 UNLOCK_CONTEXT (context);
2674 g_main_context_remove_poll_unlocked (GMainContext *context,
2677 GPollRec *pollrec, *lastrec;
2680 pollrec = context->poll_records;
2684 if (pollrec->fd == fd)
2686 if (lastrec != NULL)
2687 lastrec->next = pollrec->next;
2689 context->poll_records = pollrec->next;
2691 #ifdef ENABLE_GC_FRIENDLY
2693 #endif /* ENABLE_GC_FRIENDLY */
2695 pollrec->next = context->poll_free_list;
2696 context->poll_free_list = pollrec;
2698 context->n_poll_records--;
2702 pollrec = pollrec->next;
2705 #ifdef G_THREADS_ENABLED
2706 context->poll_changed = TRUE;
2708 /* Now wake up the main loop if it is waiting in the poll() */
2709 g_main_context_wakeup_unlocked (context);
2714 * g_source_get_current_time:
2715 * @source: a #GSource
2716 * @timeval: #GTimeVal structure in which to store current time.
2718 * Gets the "current time" to be used when checking
2719 * this source. The advantage of calling this function over
2720 * calling g_get_current_time() directly is that when
2721 * checking multiple sources, GLib can cache a single value
2722 * instead of having to repeatedly get the system time.
2725 g_source_get_current_time (GSource *source,
2728 GMainContext *context;
2730 g_return_if_fail (source->context != NULL);
2732 context = source->context;
2734 LOCK_CONTEXT (context);
2736 if (!context->time_is_current)
2738 g_get_current_time (&context->current_time);
2739 context->time_is_current = TRUE;
2742 *timeval = context->current_time;
2744 UNLOCK_CONTEXT (context);
2748 * g_main_context_set_poll_func:
2749 * @context: a #GMainContext
2750 * @func: the function to call to poll all file descriptors
2752 * Sets the function to use to handle polling of file descriptors. It
2753 * will be used instead of the poll() system call (or GLib's
2754 * replacement function, which is used where poll() isn't available).
2756 * This function could possibly be used to integrate the GLib event
2757 * loop with an external event loop.
2760 g_main_context_set_poll_func (GMainContext *context,
2764 context = g_main_context_default ();
2766 g_return_if_fail (context->ref_count > 0);
2768 LOCK_CONTEXT (context);
2771 context->poll_func = func;
2775 context->poll_func = (GPollFunc) poll;
2777 context->poll_func = (GPollFunc) g_poll;
2781 UNLOCK_CONTEXT (context);
2785 * g_main_context_get_poll_func:
2786 * @context: a #GMainContext
2788 * Gets the poll function set by g_main_context_set_poll_func()
2790 * Return value: the poll function
2793 g_main_context_get_poll_func (GMainContext *context)
2798 context = g_main_context_default ();
2800 g_return_val_if_fail (context->ref_count > 0, NULL);
2802 LOCK_CONTEXT (context);
2803 result = context->poll_func;
2804 UNLOCK_CONTEXT (context);
2809 /* HOLDS: context's lock */
2810 /* Wake the main loop up from a poll() */
2812 g_main_context_wakeup_unlocked (GMainContext *context)
2814 #ifdef G_THREADS_ENABLED
2815 if (g_thread_supported() && context->poll_waiting)
2817 context->poll_waiting = FALSE;
2819 write (context->wake_up_pipe[1], "A", 1);
2821 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
2828 * g_main_context_wakeup:
2829 * @context: a #GMainContext
2831 * If @context is currently waiting in a poll(), interrupt
2832 * the poll(), and continue the iteration process.
2835 g_main_context_wakeup (GMainContext *context)
2838 context = g_main_context_default ();
2840 g_return_if_fail (context->ref_count > 0);
2842 LOCK_CONTEXT (context);
2843 g_main_context_wakeup_unlocked (context);
2844 UNLOCK_CONTEXT (context);
2850 g_timeout_set_expiration (GTimeoutSource *timeout_source,
2851 GTimeVal *current_time)
2853 guint seconds = timeout_source->interval / 1000;
2854 guint msecs = timeout_source->interval - seconds * 1000;
2856 timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
2857 timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
2858 if (timeout_source->expiration.tv_usec >= 1000000)
2860 timeout_source->expiration.tv_usec -= 1000000;
2861 timeout_source->expiration.tv_sec++;
2866 g_timeout_prepare (GSource *source,
2871 GTimeVal current_time;
2873 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2875 g_source_get_current_time (source, ¤t_time);
2877 sec = timeout_source->expiration.tv_sec - current_time.tv_sec;
2878 msec = (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000;
2880 /* We do the following in a rather convoluted fashion to deal with
2881 * the fact that we don't have an integral type big enough to hold
2882 * the difference of two timevals in millseconds.
2884 if (sec < 0 || (sec == 0 && msec < 0))
2888 glong interval_sec = timeout_source->interval / 1000;
2889 glong interval_msec = timeout_source->interval % 1000;
2897 if (sec > interval_sec ||
2898 (sec == interval_sec && msec > interval_msec))
2900 /* The system time has been set backwards, so we
2901 * reset the expiration time to now + timeout_source->interval;
2902 * this at least avoids hanging for long periods of time.
2904 g_timeout_set_expiration (timeout_source, ¤t_time);
2905 msec = timeout_source->interval;
2913 *timeout = (gint)msec;
2919 g_timeout_check (GSource *source)
2921 GTimeVal current_time;
2922 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2924 g_source_get_current_time (source, ¤t_time);
2926 return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
2927 ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
2928 (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
2932 g_timeout_dispatch (GSource *source,
2933 GSourceFunc callback,
2936 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2940 g_warning ("Timeout source dispatched without callback\n"
2941 "You must call g_source_set_callback().");
2945 if (callback (user_data))
2947 GTimeVal current_time;
2949 g_source_get_current_time (source, ¤t_time);
2950 g_timeout_set_expiration (timeout_source, ¤t_time);
2959 * g_timeout_source_new:
2960 * @interval: the timeout interval in milliseconds.
2962 * Create a new timeout source.
2964 * The source will not initially be associated with any #GMainContext
2965 * and must be added to one with g_source_attach() before it will be
2968 * Return value: the newly create timeout source
2971 g_timeout_source_new (guint interval)
2973 GSource *source = g_source_new (&timeout_funcs, sizeof (GTimeoutSource));
2974 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2975 GTimeVal current_time;
2977 timeout_source->interval = interval;
2979 g_get_current_time (¤t_time);
2980 g_timeout_set_expiration (timeout_source, ¤t_time);
2986 * g_timeout_add_full:
2987 * @priority: the priority of the idle source. Typically this will be in the
2988 * range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
2989 * @interval: the time between calls to the function, in milliseconds
2990 * (1/1000ths of a second.)
2991 * @function: function to call
2992 * @data: data to pass to @function
2993 * @notify: function to call when the idle is removed, or %NULL
2995 * Sets a function to be called at regular intervals, with the given
2996 * priority. The function is called repeatedly until it returns
2997 * FALSE, at which point the timeout is automatically destroyed and
2998 * the function will not be called again. The @notify function is
2999 * called when the timeout is destroyed. The first call to the
3000 * function will be at the end of the first @interval.
3002 * Note that timeout functions may be delayed, due to the processing of other
3003 * event sources. Thus they should not be relied on for precise timing.
3004 * After each call to the timeout function, the time of the next
3005 * timeout is recalculated based on the current time and the given interval
3006 * (it does not try to 'catch up' time lost in delays).
3008 * Return value: the id of event source.
3011 g_timeout_add_full (gint priority,
3013 GSourceFunc function,
3015 GDestroyNotify notify)
3020 g_return_val_if_fail (function != NULL, 0);
3022 source = g_timeout_source_new (interval);
3024 if (priority != G_PRIORITY_DEFAULT)
3025 g_source_set_priority (source, priority);
3027 g_source_set_callback (source, function, data, notify);
3028 id = g_source_attach (source, NULL);
3029 g_source_unref (source);
3036 * @interval: the time between calls to the function, in milliseconds
3037 * (1/1000ths of a second.)
3038 * @function: function to call
3039 * @data: data to pass to @function
3041 * Sets a function to be called at regular intervals, with the default
3042 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
3043 * until it returns FALSE, at which point the timeout is automatically
3044 * destroyed and the function will not be called again. The @notify
3045 * function is called when the timeout is destroyed. The first call
3046 * to the function will be at the end of the first @interval.
3048 * Note that timeout functions may be delayed, due to the processing of other
3049 * event sources. Thus they should not be relied on for precise timing.
3050 * After each call to the timeout function, the time of the next
3051 * timeout is recalculated based on the current time and the given interval
3052 * (it does not try to 'catch up' time lost in delays).
3054 * Return value: the id of event source.
3057 g_timeout_add (guint32 interval,
3058 GSourceFunc function,
3061 return g_timeout_add_full (G_PRIORITY_DEFAULT,
3062 interval, function, data, NULL);
3065 /* Idle functions */
3068 g_idle_prepare (GSource *source,
3077 g_idle_check (GSource *source)
3083 g_idle_dispatch (GSource *source,
3084 GSourceFunc callback,
3089 g_warning ("Idle source dispatched without callback\n"
3090 "You must call g_source_set_callback().");
3094 return callback (user_data);
3098 * g_idle_source_new:
3100 * Create a new idle source.
3102 * The source will not initially be associated with any #GMainContext
3103 * and must be added to one with g_source_attach() before it will be
3106 * Return value: the newly created idle source
3109 g_idle_source_new (void)
3111 return g_source_new (&idle_funcs, sizeof (GSource));
3116 * @priority: the priority of the idle source. Typically this will be in the
3117 * range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3118 * @function: function to call
3119 * @data: data to pass to @function
3120 * @notify: function to call when the idle is removed, or %NULL
3122 * Adds a function to be called whenever there are no higher priority
3123 * events pending. If the function returns FALSE it is automatically
3124 * removed from the list of event sources and will not be called again.
3126 * Return value: the id of the event source.
3129 g_idle_add_full (gint priority,
3130 GSourceFunc function,
3132 GDestroyNotify notify)
3137 g_return_val_if_fail (function != NULL, 0);
3139 source = g_idle_source_new ();
3141 if (priority != G_PRIORITY_DEFAULT)
3142 g_source_set_priority (source, priority);
3144 g_source_set_callback (source, function, data, notify);
3145 id = g_source_attach (source, NULL);
3146 g_source_unref (source);
3153 * @function: function to call
3154 * @data: data to pass to @function.
3156 * Adds a function to be called whenever there are no higher priority
3157 * events pending to the default main loop. The function is given the
3158 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
3159 * returns FALSE it is automatically removed from the list of event
3160 * sources and will not be called again.
3162 * Return value: the id of the event source.
3165 g_idle_add (GSourceFunc function,
3168 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
3172 * g_idle_remove_by_data:
3173 * @data: the data for the idle source's callback.
3175 * Removes the idle function with the given data.
3177 * Return value: %TRUE if an idle source was found and removed.
3180 g_idle_remove_by_data (gpointer data)
3182 return g_source_remove_by_funcs_user_data (&idle_funcs, data);