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;
222 static GSList *main_contexts_without_pipe = NULL;
224 #if defined(G_PLATFORM_WIN32) && defined(__GNUC__)
225 __declspec(dllexport)
227 GSourceFuncs g_timeout_funcs =
235 #if defined(G_PLATFORM_WIN32) && defined(__GNUC__)
236 __declspec(dllexport)
238 GSourceFuncs g_idle_funcs =
247 /* SunOS has poll, but doesn't provide a prototype. */
248 # if defined (sun) && !defined (__SVR4)
249 extern gint poll (GPollFD *ufds, guint nfsd, gint timeout);
251 #else /* !HAVE_POLL */
256 g_poll (GPollFD *fds,
260 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
261 gboolean poll_msgs = FALSE;
268 for (f = fds; f < &fds[nfds]; ++f)
271 if (f->events & G_IO_IN)
273 if (f->fd == G_WIN32_MSG_HANDLE)
277 #ifdef G_MAIN_POLL_DEBUG
278 g_print ("g_poll: waiting for %#x\n", f->fd);
280 handles[nhandles++] = (HANDLE) f->fd;
290 /* Waiting for messages, and maybe events
291 * -> First PeekMessage
293 #ifdef G_MAIN_POLL_DEBUG
294 g_print ("PeekMessage\n");
296 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
297 ready = WAIT_OBJECT_0 + nhandles;
302 /* Waiting just for messages */
303 if (timeout == INFINITE)
308 #ifdef G_MAIN_POLL_DEBUG
309 g_print ("WaitMessage\n");
312 g_warning (G_STRLOC ": WaitMessage() failed");
313 ready = WAIT_OBJECT_0 + nhandles;
315 else if (timeout == 0)
317 /* Waiting just for messages, zero timeout.
318 * If we got here, there was no message
320 ready = WAIT_TIMEOUT;
324 /* Waiting just for messages, some timeout
325 * -> Set a timer, wait for message,
326 * kill timer, use PeekMessage
328 timer = SetTimer (NULL, 0, timeout, NULL);
330 g_warning (G_STRLOC ": SetTimer() failed");
333 #ifdef G_MAIN_POLL_DEBUG
334 g_print ("WaitMessage\n");
337 KillTimer (NULL, timer);
338 #ifdef G_MAIN_POLL_DEBUG
339 g_print ("PeekMessage\n");
341 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE)
342 && msg.message != WM_TIMER)
343 ready = WAIT_OBJECT_0;
345 ready = WAIT_TIMEOUT;
351 /* Wait for either message or event
352 * -> Use MsgWaitForMultipleObjects
354 #ifdef G_MAIN_POLL_DEBUG
355 g_print ("MsgWaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
357 ready = MsgWaitForMultipleObjects (nhandles, handles, FALSE,
358 timeout, QS_ALLINPUT);
360 if (ready == WAIT_FAILED)
361 g_warning (G_STRLOC ": MsgWaitForMultipleObjects() failed");
365 else if (nhandles == 0)
367 /* Wait for nothing (huh?) */
372 /* Wait for just events
373 * -> Use WaitForMultipleObjects
375 #ifdef G_MAIN_POLL_DEBUG
376 g_print ("WaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
378 ready = WaitForMultipleObjects (nhandles, handles, FALSE, timeout);
379 if (ready == WAIT_FAILED)
380 g_warning (G_STRLOC ": WaitForMultipleObjects() failed");
383 #ifdef G_MAIN_POLL_DEBUG
384 g_print ("wait returns %d%s\n",
386 (ready == WAIT_FAILED ? " (WAIT_FAILED)" :
387 (ready == WAIT_TIMEOUT ? " (WAIT_TIMEOUT)" :
388 (poll_msgs && ready == WAIT_OBJECT_0 + nhandles ? " (msg)" : ""))));
390 for (f = fds; f < &fds[nfds]; ++f)
393 if (ready == WAIT_FAILED)
395 else if (ready == WAIT_TIMEOUT)
397 else if (poll_msgs && ready == WAIT_OBJECT_0 + nhandles)
399 for (f = fds; f < &fds[nfds]; ++f)
402 if (f->events & G_IO_IN)
403 if (f->fd == G_WIN32_MSG_HANDLE)
404 f->revents |= G_IO_IN;
407 #if 1 /* TEST_WITHOUT_THIS */
408 else if (ready >= WAIT_OBJECT_0 && ready < WAIT_OBJECT_0 + nhandles)
409 for (f = fds; f < &fds[nfds]; ++f)
411 if ((f->events & G_IO_IN)
412 && f->fd == (gint) handles[ready - WAIT_OBJECT_0])
414 f->revents |= G_IO_IN;
415 #ifdef G_MAIN_POLL_DEBUG
416 g_print ("g_poll: got event %#x\n", f->fd);
419 ResetEvent ((HANDLE) f->fd);
428 #else /* !G_OS_WIN32 */
430 /* The following implementation of poll() comes from the GNU C Library.
431 * Copyright (C) 1994, 1996, 1997 Free Software Foundation, Inc.
434 #include <string.h> /* for bzero on BSD systems */
436 #ifdef HAVE_SYS_SELECT_H
437 #include <sys/select.h>
438 #endif /* HAVE_SYS_SELECT_H */
442 #endif /* G_OS_BEOS */
445 # define SELECT_MASK fd_set
446 #else /* !NO_FD_SET */
448 typedef long fd_mask;
451 # define SELECT_MASK void
453 # define SELECT_MASK int
454 # endif /* !_IBMR2 */
455 #endif /* !NO_FD_SET */
458 g_poll (GPollFD *fds,
463 SELECT_MASK rset, wset, xset;
472 for (f = fds; f < &fds[nfds]; ++f)
475 if (f->events & G_IO_IN)
476 FD_SET (f->fd, &rset);
477 if (f->events & G_IO_OUT)
478 FD_SET (f->fd, &wset);
479 if (f->events & G_IO_PRI)
480 FD_SET (f->fd, &xset);
481 if (f->fd > maxfd && (f->events & (G_IO_IN|G_IO_OUT|G_IO_PRI)))
485 tv.tv_sec = timeout / 1000;
486 tv.tv_usec = (timeout % 1000) * 1000;
488 ready = select (maxfd + 1, &rset, &wset, &xset,
489 timeout == -1 ? NULL : &tv);
491 for (f = fds; f < &fds[nfds]; ++f)
496 if (FD_ISSET (f->fd, &rset))
497 f->revents |= G_IO_IN;
498 if (FD_ISSET (f->fd, &wset))
499 f->revents |= G_IO_OUT;
500 if (FD_ISSET (f->fd, &xset))
501 f->revents |= G_IO_PRI;
508 #endif /* !G_OS_WIN32 */
510 #endif /* !HAVE_POLL */
513 * g_main_context_ref:
514 * @context: a #GMainContext
516 * Increases the reference count on a #GMainContext object by one.
519 g_main_context_ref (GMainContext *context)
521 g_return_if_fail (context != NULL);
522 g_return_if_fail (context->ref_count > 0);
524 LOCK_CONTEXT (context);
526 context->ref_count++;
528 UNLOCK_CONTEXT (context);
532 g_main_context_unref_and_unlock (GMainContext *context)
536 context->ref_count--;
538 if (context->ref_count != 0)
540 UNLOCK_CONTEXT (context);
544 source = context->source_list;
547 GSource *next = source->next;
548 g_source_destroy_internal (source, context, TRUE);
551 UNLOCK_CONTEXT (context);
553 #ifdef G_THREADS_ENABLED
554 g_static_mutex_free (&context->mutex);
557 g_ptr_array_free (context->pending_dispatches, TRUE);
558 g_free (context->cached_poll_array);
560 g_mem_chunk_destroy (context->poll_chunk);
562 #ifdef G_THREADS_ENABLED
563 if (g_thread_supported())
566 close (context->wake_up_pipe[0]);
567 close (context->wake_up_pipe[1]);
569 CloseHandle (context->wake_up_semaphore);
573 main_contexts_without_pipe = g_slist_remove (main_contexts_without_pipe,
581 * g_main_context_unref:
582 * @context: a #GMainContext
584 * Decreases the reference count on a #GMainContext object by one. If
585 * the result is zero, free the context and free all associated memory.
588 g_main_context_unref (GMainContext *context)
590 g_return_if_fail (context != NULL);
591 g_return_if_fail (context->ref_count > 0);
593 LOCK_CONTEXT (context);
594 g_main_context_unref_and_unlock (context);
597 #ifdef G_THREADS_ENABLED
599 g_main_context_init_pipe (GMainContext *context)
602 if (pipe (context->wake_up_pipe) < 0)
603 g_error ("Cannot create pipe main loop wake-up: %s\n",
606 context->wake_up_rec.fd = context->wake_up_pipe[0];
607 context->wake_up_rec.events = G_IO_IN;
609 context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
610 if (context->wake_up_semaphore == NULL)
611 g_error ("Cannot create wake-up semaphore: %s",
612 g_win32_error_message (GetLastError ()));
613 context->wake_up_rec.fd = (gint) context->wake_up_semaphore;
614 context->wake_up_rec.events = G_IO_IN;
615 # ifdef G_MAIN_POLL_DEBUG
616 g_print ("wake-up semaphore: %#x\n", (guint) context->wake_up_semaphore);
619 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
623 g_main_thread_init ()
625 GSList *curr = main_contexts_without_pipe;
628 g_main_context_init_pipe ((GMainContext *)curr->data);
631 g_slist_free (main_contexts_without_pipe);
632 main_contexts_without_pipe = NULL;
634 #endif /* G_THREADS_ENABLED */
637 * g_main_context_new:
639 * Creates a new #GMainContext strcuture
641 * Return value: the new #GMainContext
644 g_main_context_new ()
646 GMainContext *context = g_new0 (GMainContext, 1);
648 #ifdef G_THREADS_ENABLED
649 g_static_mutex_init (&context->mutex);
651 context->owner = NULL;
652 context->waiters = NULL;
655 context->ref_count = 1;
657 context->next_id = 1;
659 context->source_list = NULL;
662 context->poll_func = (GPollFunc)poll;
664 context->poll_func = g_poll;
667 context->cached_poll_array = NULL;
668 context->cached_poll_array_size = 0;
670 context->pending_dispatches = g_ptr_array_new ();
672 context->time_is_current = FALSE;
674 #ifdef G_THREADS_ENABLED
675 if (g_thread_supported ())
676 g_main_context_init_pipe (context);
678 main_contexts_without_pipe = g_slist_prepend (main_contexts_without_pipe,
686 * g_main_context_default:
688 * Returns the default main context. This is the main context used
689 * for main loop functions when a main loop is not explicitly
692 * Return value: the default main context.
695 g_main_context_default (void)
701 if (!default_main_context)
702 default_main_context = g_main_context_new ();
704 G_UNLOCK (main_loop);
706 return default_main_context;
709 /* Hooks for adding to the main loop */
713 * @source_funcs: structure containing functions that implement
714 * the sources behavior.
715 * @struct_size: size of the #GSource structure to create.
717 * Creates a new #GSource structure. The size is specified to
718 * allow creating structures derived from #GSource that contain
719 * additional data. The size passed in must be at least
720 * <literal>sizeof (GSource)</literal>.
722 * The source will not initially be associated with any #GMainContext
723 * and must be added to one with g_source_attach() before it will be
726 * Return value: the newly-created #GSource.
729 g_source_new (GSourceFuncs *source_funcs,
734 g_return_val_if_fail (source_funcs != NULL, NULL);
735 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
737 source = (GSource*) g_malloc0 (struct_size);
739 source->source_funcs = source_funcs;
740 source->ref_count = 1;
742 source->priority = G_PRIORITY_DEFAULT;
744 source->flags = G_HOOK_FLAG_ACTIVE;
746 /* NULL/0 initialization for all other fields */
751 /* Holds context's lock
754 g_source_list_add (GSource *source,
755 GMainContext *context)
757 GSource *tmp_source, *last_source;
760 tmp_source = context->source_list;
761 while (tmp_source && tmp_source->priority <= source->priority)
763 last_source = tmp_source;
764 tmp_source = tmp_source->next;
767 source->next = tmp_source;
769 tmp_source->prev = source;
771 source->prev = last_source;
773 last_source->next = source;
775 context->source_list = source;
778 /* Holds context's lock
781 g_source_list_remove (GSource *source,
782 GMainContext *context)
785 source->prev->next = source->next;
787 context->source_list = source->next;
790 source->next->prev = source->prev;
798 * @source: a #GSource
799 * @context: a #GMainContext (if %NULL, the default context will be used)
801 * Adds a #GSource to a @context so that it will be executed within
804 * Return value: the ID for the source within the #GMainContext
807 g_source_attach (GSource *source,
808 GMainContext *context)
813 g_return_val_if_fail (source->context == NULL, 0);
814 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
817 context = g_main_context_default ();
819 LOCK_CONTEXT (context);
821 source->context = context;
822 result = source->source_id = context->next_id++;
825 g_source_list_add (source, context);
827 tmp_list = source->poll_fds;
830 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
831 tmp_list = tmp_list->next;
834 #ifdef G_THREADS_ENABLED
835 /* Now wake up the main loop if it is waiting in the poll() */
836 g_main_context_wakeup_unlocked (context);
839 UNLOCK_CONTEXT (context);
845 g_source_destroy_internal (GSource *source,
846 GMainContext *context,
850 LOCK_CONTEXT (context);
852 if (!SOURCE_DESTROYED (source))
855 gpointer old_cb_data;
856 GSourceCallbackFuncs *old_cb_funcs;
858 source->flags &= ~G_HOOK_FLAG_ACTIVE;
860 old_cb_data = source->callback_data;
861 old_cb_funcs = source->callback_funcs;
863 source->callback_data = NULL;
864 source->callback_funcs = NULL;
868 UNLOCK_CONTEXT (context);
869 old_cb_funcs->unref (old_cb_data);
870 LOCK_CONTEXT (context);
873 tmp_list = source->poll_fds;
876 g_main_context_remove_poll_unlocked (context, tmp_list->data);
877 tmp_list = tmp_list->next;
880 g_source_unref_internal (source, context, TRUE);
884 UNLOCK_CONTEXT (context);
889 * @source: a #GSource
891 * Removes a source from its #GMainContext, if any, and mark it as
892 * destroyed. The source cannot be subsequently added to another
896 g_source_destroy (GSource *source)
898 GMainContext *context;
900 g_return_if_fail (source != NULL);
902 context = source->context;
905 g_source_destroy_internal (source, context, FALSE);
907 source->flags &= ~G_HOOK_FLAG_ACTIVE;
912 * @source: a #GSource
914 * Returns the numeric ID for a particular source. The ID of a source
915 * is unique within a particular main loop context. The reverse
916 * mapping from ID to source is done by g_main_context_find_source_by_id().
918 * Return value: the ID for the source
921 g_source_get_id (GSource *source)
925 g_return_val_if_fail (source != NULL, 0);
926 g_return_val_if_fail (source->context != NULL, 0);
928 LOCK_CONTEXT (source->context);
929 result = source->source_id;
930 UNLOCK_CONTEXT (source->context);
936 * g_source_get_context:
937 * @source: a #GSource
939 * Gets the #GMainContext with which the source is associated.
940 * Calling this function on a destroyed source is an error.
942 * Return value: the #GMainContext with which the source is associated,
943 * or %NULL if the context has not yet been added
947 g_source_get_context (GSource *source)
949 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
951 return source->context;
957 * @fd: a #GPollFD structure holding information about a file
958 * descriptor to watch.
960 * Adds a file descriptor to the set of file descriptors polled for
961 * this source. This is usually combined with g_source_new() to add an
962 * event source. The event source's check function will typically test
963 * the @revents field in the #GPollFD struct and return %TRUE if events need
967 g_source_add_poll (GSource *source,
970 GMainContext *context;
972 g_return_if_fail (source != NULL);
973 g_return_if_fail (fd != NULL);
974 g_return_if_fail (!SOURCE_DESTROYED (source));
976 context = source->context;
979 LOCK_CONTEXT (context);
981 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
985 g_main_context_add_poll_unlocked (context, source->priority, fd);
986 UNLOCK_CONTEXT (context);
991 * g_source_remove_poll:
993 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
995 * Removes a file descriptor from the set of file descriptors polled for
999 g_source_remove_poll (GSource *source,
1002 GMainContext *context;
1004 g_return_if_fail (source != NULL);
1005 g_return_if_fail (fd != NULL);
1006 g_return_if_fail (!SOURCE_DESTROYED (source));
1008 context = source->context;
1011 LOCK_CONTEXT (context);
1013 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1017 g_main_context_remove_poll_unlocked (context, fd);
1018 UNLOCK_CONTEXT (context);
1023 * g_source_set_callback_indirect:
1024 * @source: the source
1025 * @callback_data: pointer to callback data "object"
1026 * @callback_funcs: functions for reference counting @callback_data
1027 * and getting the callback and data
1029 * Sets the callback function storing the data as a refcounted callback
1030 * "object". This is used internally. Note that calling
1031 * g_source_set_callback_indirect() assumes
1032 * an initial reference count on @callback_data, and thus
1033 * @callback_funcs->unref will eventually be called once more
1034 * than @callback_funcs->ref.
1037 g_source_set_callback_indirect (GSource *source,
1038 gpointer callback_data,
1039 GSourceCallbackFuncs *callback_funcs)
1041 GMainContext *context;
1042 gpointer old_cb_data;
1043 GSourceCallbackFuncs *old_cb_funcs;
1045 g_return_if_fail (source != NULL);
1046 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1048 context = source->context;
1051 LOCK_CONTEXT (context);
1053 old_cb_data = source->callback_data;
1054 old_cb_funcs = source->callback_funcs;
1056 source->callback_data = callback_data;
1057 source->callback_funcs = callback_funcs;
1060 UNLOCK_CONTEXT (context);
1063 old_cb_funcs->unref (old_cb_data);
1067 g_source_callback_ref (gpointer cb_data)
1069 GSourceCallback *callback = cb_data;
1071 callback->ref_count++;
1076 g_source_callback_unref (gpointer cb_data)
1078 GSourceCallback *callback = cb_data;
1080 callback->ref_count--;
1081 if (callback->ref_count == 0)
1083 if (callback->notify)
1084 callback->notify (callback->data);
1090 g_source_callback_get (gpointer cb_data,
1095 GSourceCallback *callback = cb_data;
1097 *func = callback->func;
1098 *data = callback->data;
1101 static GSourceCallbackFuncs g_source_callback_funcs = {
1102 g_source_callback_ref,
1103 g_source_callback_unref,
1104 g_source_callback_get,
1108 * g_source_set_callback:
1109 * @source: the source
1110 * @func: a callback function
1111 * @data: the data to pass to callback function
1112 * @notify: a function to call when @data is no longer in use, or %NULL.
1114 * Sets the callback function for a source.
1117 g_source_set_callback (GSource *source,
1120 GDestroyNotify notify)
1122 GSourceCallback *new_callback;
1124 g_return_if_fail (source != NULL);
1126 new_callback = g_new (GSourceCallback, 1);
1128 new_callback->ref_count = 1;
1129 new_callback->func = func;
1130 new_callback->data = data;
1131 new_callback->notify = notify;
1133 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1137 * g_source_set_priority:
1138 * @source: a #GSource
1139 * @priority: the new priority.
1141 * Sets the priority of a source. While the main loop is being
1142 * run, a source will be dispatched if it is ready to be dispatched and no sources
1143 * at a higher (numerically smaller) priority are ready to be dispatched.
1146 g_source_set_priority (GSource *source,
1150 GMainContext *context;
1152 g_return_if_fail (source != NULL);
1154 context = source->context;
1157 LOCK_CONTEXT (context);
1159 source->priority = priority;
1163 source->next = NULL;
1164 source->prev = NULL;
1166 tmp_list = source->poll_fds;
1169 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1170 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1172 tmp_list = tmp_list->next;
1175 UNLOCK_CONTEXT (source->context);
1180 * g_source_get_priority:
1181 * @source: a #GSource
1183 * Gets the priority of a source.
1185 * Return value: the priority of the source
1188 g_source_get_priority (GSource *source)
1190 g_return_val_if_fail (source != NULL, 0);
1192 return source->priority;
1196 * g_source_set_can_recurse:
1197 * @source: a #GSource
1198 * @can_recurse: whether recursion is allowed for this source
1200 * Sets whether a source can be called recursively. If @can_recurse is
1201 * %TRUE, then while the source is being dispatched then this source
1202 * will be processed normally. Otherwise, all processing of this
1203 * source is blocked until the dispatch function returns.
1206 g_source_set_can_recurse (GSource *source,
1207 gboolean can_recurse)
1209 GMainContext *context;
1211 g_return_if_fail (source != NULL);
1213 context = source->context;
1216 LOCK_CONTEXT (context);
1219 source->flags |= G_SOURCE_CAN_RECURSE;
1221 source->flags &= ~G_SOURCE_CAN_RECURSE;
1224 UNLOCK_CONTEXT (context);
1228 * g_source_get_can_recurse:
1229 * @source: a #GSource
1231 * Checks whether a source is allowed to be called recursively.
1232 * see g_source_set_can_recurse().
1234 * Return value: whether recursion is allowed.
1237 g_source_get_can_recurse (GSource *source)
1239 g_return_val_if_fail (source != NULL, FALSE);
1241 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1246 * @source: a #GSource
1248 * Increases the reference count on a source by one.
1250 * Return value: @source
1253 g_source_ref (GSource *source)
1255 GMainContext *context;
1257 g_return_val_if_fail (source != NULL, NULL);
1259 context = source->context;
1262 LOCK_CONTEXT (context);
1264 source->ref_count++;
1267 UNLOCK_CONTEXT (context);
1272 /* g_source_unref() but possible to call within context lock
1275 g_source_unref_internal (GSource *source,
1276 GMainContext *context,
1279 gpointer old_cb_data = NULL;
1280 GSourceCallbackFuncs *old_cb_funcs = NULL;
1282 g_return_if_fail (source != NULL);
1284 if (!have_lock && context)
1285 LOCK_CONTEXT (context);
1287 source->ref_count--;
1288 if (source->ref_count == 0)
1290 old_cb_data = source->callback_data;
1291 old_cb_funcs = source->callback_funcs;
1293 source->callback_data = NULL;
1294 source->callback_funcs = NULL;
1296 if (context && !SOURCE_DESTROYED (source))
1298 g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1299 source->ref_count++;
1302 g_source_list_remove (source, context);
1304 if (source->source_funcs->finalize)
1305 source->source_funcs->finalize (source);
1307 g_slist_free (source->poll_fds);
1308 source->poll_fds = NULL;
1312 if (!have_lock && context)
1313 UNLOCK_CONTEXT (context);
1318 UNLOCK_CONTEXT (context);
1320 old_cb_funcs->unref (old_cb_data);
1323 LOCK_CONTEXT (context);
1329 * @source: a #GSource
1331 * Decreases the reference count of a source by one. If the
1332 * resulting reference count is zero the source and associated
1333 * memory will be destroyed.
1336 g_source_unref (GSource *source)
1338 g_return_if_fail (source != NULL);
1340 g_source_unref_internal (source, source->context, FALSE);
1344 * g_main_context_find_source_by_id:
1345 * @context: a #GMainContext (if %NULL, the default context will be used)
1346 * @source_id: the source ID, as returned by g_source_get_id()
1348 * Finds a #GSource given a pair of context and ID
1350 * Return value: the #GSource if found, otherwise, %NULL
1353 g_main_context_find_source_by_id (GMainContext *context,
1358 g_return_val_if_fail (source_id > 0, FALSE);
1360 if (context == NULL)
1361 context = g_main_context_default ();
1363 LOCK_CONTEXT (context);
1365 source = context->source_list;
1368 if (!SOURCE_DESTROYED (source) &&
1369 source->source_id == source_id)
1371 source = source->next;
1374 UNLOCK_CONTEXT (context);
1380 * g_main_context_find_source_by_funcs_user_data:
1381 * @context: a #GMainContext (if %NULL, the default context will be used).
1382 * @funcs: the @source_funcs passed to g_source_new().
1383 * @user_data: the user data from the callback.
1385 * Finds a source with the given source functions and user data. If
1386 * multiple sources exist with the same source function and user data,
1387 * the first one found will be returned.
1389 * Return value: the source, if one was found, otherwise %NULL
1392 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1393 GSourceFuncs *funcs,
1398 g_return_val_if_fail (funcs != NULL, FALSE);
1400 if (context == NULL)
1401 context = g_main_context_default ();
1403 LOCK_CONTEXT (context);
1405 source = context->source_list;
1408 if (!SOURCE_DESTROYED (source) &&
1409 source->source_funcs == funcs &&
1410 source->callback_funcs)
1412 GSourceFunc callback;
1413 gpointer callback_data;
1415 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1417 if (callback_data == user_data)
1420 source = source->next;
1423 UNLOCK_CONTEXT (context);
1429 * g_main_context_find_source_by_user_data:
1430 * @context: a #GMainContext
1431 * @user_data: the user_data for the callback.
1433 * Finds a source with the given user data for the callback. If
1434 * multiple sources exist with the same user data, the first
1435 * one found will be returned.
1437 * Return value: the source, if one was found, otherwise %NULL
1440 g_main_context_find_source_by_user_data (GMainContext *context,
1445 if (context == NULL)
1446 context = g_main_context_default ();
1448 LOCK_CONTEXT (context);
1450 source = context->source_list;
1453 if (!SOURCE_DESTROYED (source) &&
1454 source->callback_funcs)
1456 GSourceFunc callback;
1457 gpointer callback_data = NULL;
1459 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1461 if (callback_data == user_data)
1464 source = source->next;
1467 UNLOCK_CONTEXT (context);
1474 * @tag: the id of the source to remove.
1476 * Removes the source with the given id from the default main
1477 * context. The id of a #GSource is given by g_source_get_id(),
1478 * or will be returned by the functions g_source_attach(),
1479 * g_idle_add(), g_idle_add_full(), g_timeout_add(),
1480 * g_timeout_add_full(), g_io_add_watch, and g_io_add_watch_full().
1482 * See also g_source_destroy().
1484 * Return value: %TRUE if the source was found and removed.
1487 g_source_remove (guint tag)
1491 g_return_val_if_fail (tag > 0, FALSE);
1493 source = g_main_context_find_source_by_id (NULL, tag);
1495 g_source_destroy (source);
1497 return source != NULL;
1501 * g_source_remove_by_user_data:
1502 * @user_data: the user_data for the callback.
1504 * Removes a source from the default main loop context given the user
1505 * data for the callback. If multiple sources exist with the same user
1506 * data, only one will be destroyed.
1508 * Return value: %TRUE if a source was found and removed.
1511 g_source_remove_by_user_data (gpointer user_data)
1515 source = g_main_context_find_source_by_user_data (NULL, user_data);
1518 g_source_destroy (source);
1526 * g_source_remove_by_funcs_user_data:
1527 * @funcs: The @source_funcs passed to g_source_new()
1528 * @user_data: the user data for the callback
1530 * Removes a source from the default main loop context given the
1531 * source functions and user data. If multiple sources exist with the
1532 * same source functions and user data, only one will be destroyed.
1534 * Return value: %TRUE if a source was found and removed.
1537 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1542 g_return_val_if_fail (funcs != NULL, FALSE);
1544 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1547 g_source_destroy (source);
1555 * g_get_current_time:
1556 * @result: #GTimeVal structure in which to store current time.
1558 * Equivalent to the UNIX <function>gettimeofday()</function> function, but portable.
1561 g_get_current_time (GTimeVal *result)
1566 g_return_if_fail (result != NULL);
1568 /*this is required on alpha, there the timeval structs are int's
1569 not longs and a cast only would fail horribly*/
1570 gettimeofday (&r, NULL);
1571 result->tv_sec = r.tv_sec;
1572 result->tv_usec = r.tv_usec;
1574 /* Avoid calling time() except for the first time.
1575 * GetTickCount() should be pretty fast and low-level?
1576 * I could also use ftime() but it seems unnecessarily overheady.
1578 static DWORD start_tick = 0;
1579 static time_t start_time;
1582 g_return_if_fail (result != NULL);
1584 if (start_tick == 0)
1586 start_tick = GetTickCount ();
1590 tick = GetTickCount ();
1592 result->tv_sec = (tick - start_tick) / 1000 + start_time;
1593 result->tv_usec = ((tick - start_tick) % 1000) * 1000;
1597 /* Running the main loop */
1599 /* HOLDS: context's lock */
1601 g_main_dispatch (GMainContext *context)
1605 for (i = 0; i < context->pending_dispatches->len; i++)
1607 GSource *source = context->pending_dispatches->pdata[i];
1609 context->pending_dispatches->pdata[i] = NULL;
1612 source->flags &= ~G_SOURCE_READY;
1614 if (!SOURCE_DESTROYED (source))
1616 gboolean was_in_call;
1617 gpointer user_data = NULL;
1618 GSourceFunc callback = NULL;
1619 GSourceCallbackFuncs *cb_funcs;
1621 gboolean need_destroy;
1623 gboolean (*dispatch) (GSource *,
1627 dispatch = source->source_funcs->dispatch;
1628 cb_funcs = source->callback_funcs;
1629 cb_data = source->callback_data;
1632 cb_funcs->ref (cb_data);
1634 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
1635 source->flags |= G_HOOK_FLAG_IN_CALL;
1638 cb_funcs->get (cb_data, source, &callback, &user_data);
1640 UNLOCK_CONTEXT (context);
1642 need_destroy = ! dispatch (source,
1645 LOCK_CONTEXT (context);
1648 cb_funcs->unref (cb_data);
1651 source->flags &= ~G_HOOK_FLAG_IN_CALL;
1653 /* Note: this depends on the fact that we can't switch
1654 * sources from one main context to another
1656 if (need_destroy && !SOURCE_DESTROYED (source))
1658 g_assert (source->context == context);
1659 g_source_destroy_internal (source, context, TRUE);
1663 SOURCE_UNREF (source, context);
1666 g_ptr_array_set_size (context->pending_dispatches, 0);
1669 /* Holds context's lock */
1670 static inline GSource *
1671 next_valid_source (GMainContext *context,
1674 GSource *new_source = source ? source->next : context->source_list;
1678 if (!SOURCE_DESTROYED (new_source))
1680 new_source->ref_count++;
1684 new_source = new_source->next;
1688 SOURCE_UNREF (source, context);
1694 * g_main_context_acquire:
1695 * @context: a #GMainContext
1697 * Tries to become the owner of the specified context.
1698 * If some other context is the owner of the context,
1699 * returns %FALSE immediately. Ownership is properly
1700 * recursive: the owner can require ownership again
1701 * and will release ownership when g_main_context_release()
1702 * is called as many times as g_main_context_acquire().
1704 * You must be the owner of a context before you
1705 * can call g_main_context_prepare(), g_main_context_query(),
1706 * g_main_context_check(), g_main_context_dispatch().
1708 * Return value: %TRUE if the operation succeeded, and
1709 * this thread is now the owner of @context.
1712 g_main_context_acquire (GMainContext *context)
1714 #ifdef G_THREADS_ENABLED
1715 gboolean result = FALSE;
1716 GThread *self = G_THREAD_SELF;
1718 if (context == NULL)
1719 context = g_main_context_default ();
1721 LOCK_CONTEXT (context);
1723 if (!context->owner)
1725 context->owner = self;
1726 g_assert (context->owner_count == 0);
1729 if (context->owner == self)
1731 context->owner_count++;
1735 UNLOCK_CONTEXT (context);
1738 #else /* !G_THREADS_ENABLED */
1740 #endif /* G_THREADS_ENABLED */
1744 * g_main_context_release:
1745 * @context: a #GMainContext
1747 * Releases ownership of a context previously acquired by this thread
1748 * with g_main_context_acquire(). If the context was acquired multiple
1749 * times, the only release ownership when g_main_context_release()
1750 * is called as many times as it was acquired.
1753 g_main_context_release (GMainContext *context)
1755 #ifdef G_THREADS_ENABLED
1756 if (context == NULL)
1757 context = g_main_context_default ();
1759 LOCK_CONTEXT (context);
1761 context->owner_count--;
1762 if (context->owner_count == 0)
1764 context->owner = NULL;
1766 if (context->waiters)
1768 GMainWaiter *waiter = context->waiters->data;
1769 gboolean loop_internal_waiter =
1770 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
1771 context->waiters = g_slist_delete_link (context->waiters,
1773 if (!loop_internal_waiter)
1774 g_mutex_lock (waiter->mutex);
1776 g_cond_signal (waiter->cond);
1778 if (!loop_internal_waiter)
1779 g_mutex_unlock (waiter->mutex);
1783 UNLOCK_CONTEXT (context);
1784 #endif /* G_THREADS_ENABLED */
1788 * g_main_context_wait:
1789 * @context: a #GMainContext
1790 * @cond: a condition variable
1791 * @mutex: a mutex, currently held
1793 * Tries to become the owner of the specified context,
1794 * as with g_main_context_acquire(). But if another thread
1795 * is the owner, atomically drop @mutex and wait on @cond until
1796 * that owner releases ownership or until @cond is signaled, then
1797 * try again (once) to become the owner.
1799 * Return value: %TRUE if the operation succeeded, and
1800 * this thread is now the owner of @context.
1803 g_main_context_wait (GMainContext *context,
1807 #ifdef G_THREADS_ENABLED
1808 gboolean result = FALSE;
1809 GThread *self = G_THREAD_SELF;
1810 gboolean loop_internal_waiter;
1812 if (context == NULL)
1813 context = g_main_context_default ();
1815 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
1817 if (!loop_internal_waiter)
1818 LOCK_CONTEXT (context);
1820 if (context->owner && context->owner != self)
1825 waiter.mutex = mutex;
1827 context->waiters = g_slist_append (context->waiters, &waiter);
1829 if (!loop_internal_waiter)
1830 UNLOCK_CONTEXT (context);
1831 g_cond_wait (cond, mutex);
1832 if (!loop_internal_waiter)
1833 LOCK_CONTEXT (context);
1835 context->waiters = g_slist_remove (context->waiters, &waiter);
1838 if (!context->owner)
1840 context->owner = self;
1841 g_assert (context->owner_count == 0);
1844 if (context->owner == self)
1846 context->owner_count++;
1850 if (!loop_internal_waiter)
1851 UNLOCK_CONTEXT (context);
1854 #else /* !G_THREADS_ENABLED */
1856 #endif /* G_THREADS_ENABLED */
1860 * g_main_context_prepare:
1861 * @context: a #GMainContext
1862 * @priority: location to store priority of highest priority
1863 * source already ready.
1865 * Prepares to poll sources within a main loop. The resulting information
1866 * for polling is determined by calling g_main_context_query ().
1868 * Return value: %TRUE if some source is ready to be dispatched
1872 g_main_context_prepare (GMainContext *context,
1877 gint current_priority = G_MAXINT;
1880 if (context == NULL)
1881 context = g_main_context_default ();
1883 LOCK_CONTEXT (context);
1885 context->time_is_current = FALSE;
1887 if (context->in_check_or_prepare)
1889 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
1890 "prepare() member.");
1891 UNLOCK_CONTEXT (context);
1895 #ifdef G_THREADS_ENABLED
1896 if (context->poll_waiting)
1898 g_warning("g_main_context_prepare(): main loop already active in another thread");
1899 UNLOCK_CONTEXT (context);
1903 context->poll_waiting = TRUE;
1904 #endif /* G_THREADS_ENABLED */
1907 /* If recursing, finish up current dispatch, before starting over */
1908 if (context->pending_dispatches)
1911 g_main_dispatch (context, ¤t_time);
1913 UNLOCK_CONTEXT (context);
1918 /* If recursing, clear list of pending dispatches */
1920 for (i = 0; i < context->pending_dispatches->len; i++)
1922 if (context->pending_dispatches->pdata[i])
1923 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
1925 g_ptr_array_set_size (context->pending_dispatches, 0);
1927 /* Prepare all sources */
1929 context->timeout = -1;
1931 source = next_valid_source (context, NULL);
1934 gint source_timeout = -1;
1936 if ((n_ready > 0) && (source->priority > current_priority))
1938 SOURCE_UNREF (source, context);
1941 if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
1944 if (!(source->flags & G_SOURCE_READY))
1947 gboolean (*prepare) (GSource *source,
1950 prepare = source->source_funcs->prepare;
1951 context->in_check_or_prepare++;
1952 UNLOCK_CONTEXT (context);
1954 result = (*prepare) (source, &source_timeout);
1956 LOCK_CONTEXT (context);
1957 context->in_check_or_prepare--;
1960 source->flags |= G_SOURCE_READY;
1963 if (source->flags & G_SOURCE_READY)
1966 current_priority = source->priority;
1967 context->timeout = 0;
1970 if (source_timeout >= 0)
1972 if (context->timeout < 0)
1973 context->timeout = source_timeout;
1975 context->timeout = MIN (context->timeout, source_timeout);
1979 source = next_valid_source (context, source);
1982 UNLOCK_CONTEXT (context);
1985 *priority = current_priority;
1987 return (n_ready > 0);
1991 * g_main_context_query:
1992 * @context: a #GMainContext
1993 * @max_priority: maximum priority source to check
1994 * @timeout: location to store timeout to be used in polling
1995 * @fds: location to store #GPollFD records that need to be polled.
1996 * @n_fds: length of @fds.
1998 * Determines information necessary to poll this main loop.
2000 * Return value: the number of records actually stored in @fds,
2001 * or, if more than @n_fds records need to be stored, the number
2002 * of records that need to be stored.
2005 g_main_context_query (GMainContext *context,
2014 LOCK_CONTEXT (context);
2016 pollrec = context->poll_records;
2018 while (pollrec && max_priority >= pollrec->priority)
2020 if (pollrec->fd->events)
2024 fds[n_poll].fd = pollrec->fd->fd;
2025 /* In direct contradiction to the Unix98 spec, IRIX runs into
2026 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2027 * flags in the events field of the pollfd while it should
2028 * just ignoring them. So we mask them out here.
2030 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2031 fds[n_poll].revents = 0;
2036 pollrec = pollrec->next;
2039 #ifdef G_THREADS_ENABLED
2040 context->poll_changed = FALSE;
2045 *timeout = context->timeout;
2047 context->time_is_current = FALSE;
2050 UNLOCK_CONTEXT (context);
2056 * g_main_context_check:
2057 * @context: a #GMainContext
2058 * @max_priority: the maximum numerical priority of sources to check
2059 * @fds: array of #GPollFD's that was passed to the last call to
2060 * g_main_context_query()
2061 * @n_fds: return value of g_main_context_query()
2063 * Passes the results of polling back to the main loop.
2065 * Return value: %TRUE if some sources are ready to be dispatched.
2068 g_main_context_check (GMainContext *context,
2078 LOCK_CONTEXT (context);
2080 if (context->in_check_or_prepare)
2082 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2083 "prepare() member.");
2084 UNLOCK_CONTEXT (context);
2088 #ifdef G_THREADS_ENABLED
2089 if (!context->poll_waiting)
2093 read (context->wake_up_pipe[0], &c, 1);
2097 context->poll_waiting = FALSE;
2099 /* If the set of poll file descriptors changed, bail out
2100 * and let the main loop rerun
2102 if (context->poll_changed)
2104 UNLOCK_CONTEXT (context);
2107 #endif /* G_THREADS_ENABLED */
2109 pollrec = context->poll_records;
2113 if (pollrec->fd->events)
2115 pollrec->fd->revents = fds[i].revents;
2118 pollrec = pollrec->next;
2121 source = next_valid_source (context, NULL);
2124 if ((n_ready > 0) && (source->priority > max_priority))
2126 SOURCE_UNREF (source, context);
2129 if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
2132 if (!(source->flags & G_SOURCE_READY))
2135 gboolean (*check) (GSource *source);
2137 check = source->source_funcs->check;
2139 context->in_check_or_prepare++;
2140 UNLOCK_CONTEXT (context);
2142 result = (*check) (source);
2144 LOCK_CONTEXT (context);
2145 context->in_check_or_prepare--;
2148 source->flags |= G_SOURCE_READY;
2151 if (source->flags & G_SOURCE_READY)
2153 source->ref_count++;
2154 g_ptr_array_add (context->pending_dispatches, source);
2158 /* never dispatch sources with less priority than the first
2159 * one we choose to dispatch
2161 max_priority = source->priority;
2165 source = next_valid_source (context, source);
2168 UNLOCK_CONTEXT (context);
2174 * g_main_context_dispatch:
2175 * @context: a #GMainContext
2177 * Dispatches all pending sources.
2180 g_main_context_dispatch (GMainContext *context)
2182 LOCK_CONTEXT (context);
2184 if (context->pending_dispatches->len > 0)
2186 g_main_dispatch (context);
2189 UNLOCK_CONTEXT (context);
2192 /* HOLDS context lock */
2194 g_main_context_iterate (GMainContext *context,
2201 gboolean some_ready;
2202 gint nfds, allocated_nfds;
2203 GPollFD *fds = NULL;
2205 UNLOCK_CONTEXT (context);
2207 #ifdef G_THREADS_ENABLED
2208 if (!g_main_context_acquire (context))
2210 gboolean got_ownership;
2212 g_return_val_if_fail (g_thread_supported (), FALSE);
2217 LOCK_CONTEXT (context);
2220 context->cond = g_cond_new ();
2222 got_ownership = g_main_context_wait (context,
2224 g_static_mutex_get_mutex (&context->mutex));
2228 UNLOCK_CONTEXT (context);
2233 LOCK_CONTEXT (context);
2234 #endif /* G_THREADS_ENABLED */
2236 if (!context->cached_poll_array)
2238 context->cached_poll_array_size = context->n_poll_records;
2239 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2242 allocated_nfds = context->cached_poll_array_size;
2243 fds = context->cached_poll_array;
2245 UNLOCK_CONTEXT (context);
2247 some_ready = g_main_context_prepare (context, &max_priority);
2249 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
2250 allocated_nfds)) > allocated_nfds)
2252 LOCK_CONTEXT (context);
2254 context->cached_poll_array_size = allocated_nfds = nfds;
2255 context->cached_poll_array = fds = g_new (GPollFD, nfds);
2256 UNLOCK_CONTEXT (context);
2262 g_main_context_poll (context, timeout, max_priority, fds, nfds);
2264 g_main_context_check (context, max_priority, fds, nfds);
2267 g_main_context_dispatch (context);
2269 #ifdef G_THREADS_ENABLED
2270 g_main_context_release (context);
2271 #endif /* G_THREADS_ENABLED */
2273 LOCK_CONTEXT (context);
2279 * g_main_context_pending:
2280 * @context: a #GMainContext (if %NULL, the default context will be used)
2282 * Checks if any sources have pending events for the given context.
2284 * Return value: %TRUE if events are pending.
2287 g_main_context_pending (GMainContext *context)
2292 context = g_main_context_default();
2294 LOCK_CONTEXT (context);
2295 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
2296 UNLOCK_CONTEXT (context);
2302 * g_main_context_iteration:
2303 * @context: a #GMainContext (if %NULL, the default context will be used)
2304 * @may_block: whether the call may block.
2306 * Runs a single iteration for the given main loop. This involves
2307 * checking to see if any event sources are ready to be processed,
2308 * then if no events sources are ready and @may_block is %TRUE, waiting
2309 * for a source to become ready, then dispatching the highest priority
2310 * events sources that are ready. Note that even when @may_block is %TRUE,
2311 * it is still possible for g_main_context_iteration() to return
2312 * %FALSE, since the the wait may be interrupted for other
2313 * reasons than an event source becoming ready.
2315 * Return value: %TRUE if events were dispatched.
2318 g_main_context_iteration (GMainContext *context, gboolean may_block)
2323 context = g_main_context_default();
2325 LOCK_CONTEXT (context);
2326 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
2327 UNLOCK_CONTEXT (context);
2334 * @context: a #GMainContext (if %NULL, the default context will be used).
2335 * @is_running: set to %TRUE to indicate that the loop is running. This
2336 * is not very important since calling g_main_loop_run() will set this to
2339 * Creates a new #GMainLoop structure.
2341 * Return value: a new #GMainLoop.
2344 g_main_loop_new (GMainContext *context,
2345 gboolean is_running)
2350 context = g_main_context_default();
2352 g_main_context_ref (context);
2354 loop = g_new0 (GMainLoop, 1);
2355 loop->context = context;
2356 loop->is_running = is_running != FALSE;
2357 loop->ref_count = 1;
2364 * @loop: a #GMainLoop
2366 * Increases the reference count on a #GMainLoop object by one.
2368 * Return value: @loop
2371 g_main_loop_ref (GMainLoop *loop)
2373 g_return_val_if_fail (loop != NULL, NULL);
2374 g_return_val_if_fail (loop->ref_count > 0, NULL);
2376 LOCK_CONTEXT (loop->context);
2378 UNLOCK_CONTEXT (loop->context);
2384 g_main_loop_unref_and_unlock (GMainLoop *loop)
2387 if (loop->ref_count == 0)
2389 /* When the ref_count is 0, there can be nobody else using the
2390 * loop, so it is safe to unlock before destroying.
2392 g_main_context_unref_and_unlock (loop->context);
2396 UNLOCK_CONTEXT (loop->context);
2400 * g_main_loop_unref:
2401 * @loop: a #GMainLoop
2403 * Decreases the reference count on a #GMainLoop object by one. If
2404 * the result is zero, free the loop and free all associated memory.
2407 g_main_loop_unref (GMainLoop *loop)
2409 g_return_if_fail (loop != NULL);
2410 g_return_if_fail (loop->ref_count > 0);
2412 LOCK_CONTEXT (loop->context);
2414 g_main_loop_unref_and_unlock (loop);
2419 * @loop: a #GMainLoop
2421 * Runs a main loop until g_main_loop_quit() is called on the loop.
2422 * If this is called for the thread of the loop's #GMainContext,
2423 * it will process events from the loop, otherwise it will
2427 g_main_loop_run (GMainLoop *loop)
2429 GThread *self = G_THREAD_SELF;
2431 g_return_if_fail (loop != NULL);
2432 g_return_if_fail (loop->ref_count > 0);
2434 #ifdef G_THREADS_ENABLED
2435 if (!g_main_context_acquire (loop->context))
2437 gboolean got_ownership = FALSE;
2439 /* Another thread owns this context */
2440 if (!g_thread_supported ())
2442 g_warning ("g_main_loop_run() was called from second thread but "
2443 "g_thread_init() was never called.");
2447 LOCK_CONTEXT (loop->context);
2451 if (!loop->is_running)
2452 loop->is_running = TRUE;
2454 if (!loop->context->cond)
2455 loop->context->cond = g_cond_new ();
2457 while (loop->is_running || !got_ownership)
2458 got_ownership = g_main_context_wait (loop->context,
2459 loop->context->cond,
2460 g_static_mutex_get_mutex (&loop->context->mutex));
2462 if (!loop->is_running)
2464 UNLOCK_CONTEXT (loop->context);
2466 g_main_context_release (loop->context);
2467 g_main_loop_unref (loop);
2471 g_assert (got_ownership);
2474 LOCK_CONTEXT (loop->context);
2475 #endif /* G_THREADS_ENABLED */
2477 if (loop->context->in_check_or_prepare)
2479 g_warning ("g_main_loop_run(): called recursively from within a source's "
2480 "check() or prepare() member, iteration not possible.");
2485 loop->is_running = TRUE;
2486 while (loop->is_running)
2487 g_main_context_iterate (loop->context, TRUE, TRUE, self);
2489 UNLOCK_CONTEXT (loop->context);
2491 #ifdef G_THREADS_ENABLED
2492 g_main_context_release (loop->context);
2493 #endif /* G_THREADS_ENABLED */
2495 g_main_loop_unref (loop);
2500 * @loop: a #GMainLoop
2502 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
2503 * for the loop will return.
2506 g_main_loop_quit (GMainLoop *loop)
2508 g_return_if_fail (loop != NULL);
2509 g_return_if_fail (loop->ref_count > 0);
2511 LOCK_CONTEXT (loop->context);
2512 loop->is_running = FALSE;
2513 g_main_context_wakeup_unlocked (loop->context);
2515 #ifdef G_THREADS_ENABLED
2516 if (loop->context->cond)
2517 g_cond_broadcast (loop->context->cond);
2518 #endif /* G_THREADS_ENABLED */
2520 UNLOCK_CONTEXT (loop->context);
2524 * g_main_loop_is_running:
2525 * @loop: a #GMainLoop.
2527 * Checks to see if the main loop is currently being run via g_main_loop_run().
2529 * Return value: %TRUE if the mainloop is currently being run.
2532 g_main_loop_is_running (GMainLoop *loop)
2534 g_return_val_if_fail (loop != NULL, FALSE);
2535 g_return_val_if_fail (loop->ref_count > 0, FALSE);
2537 return loop->is_running;
2541 * g_main_loop_get_context:
2542 * @loop: a #GMainLoop.
2544 * Returns the #GMainContext of @loop.
2546 * Return value: the #GMainContext of @loop
2549 g_main_loop_get_context (GMainLoop *loop)
2551 g_return_val_if_fail (loop != NULL, NULL);
2552 g_return_val_if_fail (loop->ref_count > 0, NULL);
2554 return loop->context;
2557 /* HOLDS: context's lock */
2559 g_main_context_poll (GMainContext *context,
2565 #ifdef G_MAIN_POLL_DEBUG
2571 GPollFunc poll_func;
2573 if (n_fds || timeout != 0)
2575 #ifdef G_MAIN_POLL_DEBUG
2576 g_print ("g_main_poll(%d) timeout: %d\n", n_fds, timeout);
2577 poll_timer = g_timer_new ();
2580 LOCK_CONTEXT (context);
2582 poll_func = context->poll_func;
2584 UNLOCK_CONTEXT (context);
2585 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
2586 g_warning ("poll(2) failed due to: %s.",
2587 g_strerror (errno));
2589 #ifdef G_MAIN_POLL_DEBUG
2590 LOCK_CONTEXT (context);
2592 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
2595 g_timer_elapsed (poll_timer, NULL));
2596 g_timer_destroy (poll_timer);
2597 pollrec = context->poll_records;
2601 if (pollrec->fd->events)
2605 g_print (" [%d:", fds[i].fd);
2606 if (fds[i].revents & G_IO_IN)
2608 if (fds[i].revents & G_IO_OUT)
2610 if (fds[i].revents & G_IO_PRI)
2612 if (fds[i].revents & G_IO_ERR)
2614 if (fds[i].revents & G_IO_HUP)
2616 if (fds[i].revents & G_IO_NVAL)
2622 pollrec = pollrec->next;
2626 UNLOCK_CONTEXT (context);
2628 } /* if (n_fds || timeout != 0) */
2632 * g_main_context_add_poll:
2633 * @context: a #GMainContext (or %NULL for the default context)
2634 * @fd: a #GPollFD structure holding information about a file
2635 * descriptor to watch.
2636 * @priority: the priority for this file descriptor which should be
2637 * the same as the priority used for g_source_attach() to ensure that the
2638 * file descriptor is polled whenever the results may be needed.
2640 * Adds a file descriptor to the set of file descriptors polled for
2641 * this context. This will very seldomly be used directly. Instead
2642 * a typical event source will use g_source_add_poll() instead.
2645 g_main_context_add_poll (GMainContext *context,
2650 context = g_main_context_default ();
2652 g_return_if_fail (context->ref_count > 0);
2653 g_return_if_fail (fd);
2655 LOCK_CONTEXT (context);
2656 g_main_context_add_poll_unlocked (context, priority, fd);
2657 UNLOCK_CONTEXT (context);
2660 /* HOLDS: main_loop_lock */
2662 g_main_context_add_poll_unlocked (GMainContext *context,
2666 GPollRec *lastrec, *pollrec, *newrec;
2668 if (!context->poll_chunk)
2669 context->poll_chunk = g_mem_chunk_create (GPollRec, 32, G_ALLOC_ONLY);
2671 if (context->poll_free_list)
2673 newrec = context->poll_free_list;
2674 context->poll_free_list = newrec->next;
2677 newrec = g_chunk_new (GPollRec, context->poll_chunk);
2679 /* This file descriptor may be checked before we ever poll */
2682 newrec->priority = priority;
2685 pollrec = context->poll_records;
2686 while (pollrec && priority >= pollrec->priority)
2689 pollrec = pollrec->next;
2693 lastrec->next = newrec;
2695 context->poll_records = newrec;
2697 newrec->next = pollrec;
2699 context->n_poll_records++;
2701 #ifdef G_THREADS_ENABLED
2702 context->poll_changed = TRUE;
2704 /* Now wake up the main loop if it is waiting in the poll() */
2705 g_main_context_wakeup_unlocked (context);
2710 * g_main_context_remove_poll:
2711 * @context:a #GMainContext
2712 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
2714 * Removes file descriptor from the set of file descriptors to be
2715 * polled for a particular context.
2718 g_main_context_remove_poll (GMainContext *context,
2722 context = g_main_context_default ();
2724 g_return_if_fail (context->ref_count > 0);
2725 g_return_if_fail (fd);
2727 LOCK_CONTEXT (context);
2728 g_main_context_remove_poll_unlocked (context, fd);
2729 UNLOCK_CONTEXT (context);
2733 g_main_context_remove_poll_unlocked (GMainContext *context,
2736 GPollRec *pollrec, *lastrec;
2739 pollrec = context->poll_records;
2743 if (pollrec->fd == fd)
2745 if (lastrec != NULL)
2746 lastrec->next = pollrec->next;
2748 context->poll_records = pollrec->next;
2750 #ifdef ENABLE_GC_FRIENDLY
2752 #endif /* ENABLE_GC_FRIENDLY */
2754 pollrec->next = context->poll_free_list;
2755 context->poll_free_list = pollrec;
2757 context->n_poll_records--;
2761 pollrec = pollrec->next;
2764 #ifdef G_THREADS_ENABLED
2765 context->poll_changed = TRUE;
2767 /* Now wake up the main loop if it is waiting in the poll() */
2768 g_main_context_wakeup_unlocked (context);
2773 * g_source_get_current_time:
2774 * @source: a #GSource
2775 * @timeval: #GTimeVal structure in which to store current time.
2777 * Gets the "current time" to be used when checking
2778 * this source. The advantage of calling this function over
2779 * calling g_get_current_time() directly is that when
2780 * checking multiple sources, GLib can cache a single value
2781 * instead of having to repeatedly get the system time.
2784 g_source_get_current_time (GSource *source,
2787 GMainContext *context;
2789 g_return_if_fail (source->context != NULL);
2791 context = source->context;
2793 LOCK_CONTEXT (context);
2795 if (!context->time_is_current)
2797 g_get_current_time (&context->current_time);
2798 context->time_is_current = TRUE;
2801 *timeval = context->current_time;
2803 UNLOCK_CONTEXT (context);
2807 * g_main_context_set_poll_func:
2808 * @context: a #GMainContext
2809 * @func: the function to call to poll all file descriptors
2811 * Sets the function to use to handle polling of file descriptors. It
2812 * will be used instead of the <function>poll()</function> system call
2813 * (or GLib's replacement function, which is used where
2814 * <function>poll()</function> isn't available).
2816 * This function could possibly be used to integrate the GLib event
2817 * loop with an external event loop.
2820 g_main_context_set_poll_func (GMainContext *context,
2824 context = g_main_context_default ();
2826 g_return_if_fail (context->ref_count > 0);
2828 LOCK_CONTEXT (context);
2831 context->poll_func = func;
2835 context->poll_func = (GPollFunc) poll;
2837 context->poll_func = (GPollFunc) g_poll;
2841 UNLOCK_CONTEXT (context);
2845 * g_main_context_get_poll_func:
2846 * @context: a #GMainContext
2848 * Gets the poll function set by g_main_context_set_poll_func().
2850 * Return value: the poll function
2853 g_main_context_get_poll_func (GMainContext *context)
2858 context = g_main_context_default ();
2860 g_return_val_if_fail (context->ref_count > 0, NULL);
2862 LOCK_CONTEXT (context);
2863 result = context->poll_func;
2864 UNLOCK_CONTEXT (context);
2869 /* HOLDS: context's lock */
2870 /* Wake the main loop up from a poll() */
2872 g_main_context_wakeup_unlocked (GMainContext *context)
2874 #ifdef G_THREADS_ENABLED
2875 if (g_thread_supported() && context->poll_waiting)
2877 context->poll_waiting = FALSE;
2879 write (context->wake_up_pipe[1], "A", 1);
2881 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
2888 * g_main_context_wakeup:
2889 * @context: a #GMainContext
2891 * If @context is currently waiting in a <function>poll()</function>, interrupt
2892 * the <function>poll()</function>, and continue the iteration process.
2895 g_main_context_wakeup (GMainContext *context)
2898 context = g_main_context_default ();
2900 g_return_if_fail (context->ref_count > 0);
2902 LOCK_CONTEXT (context);
2903 g_main_context_wakeup_unlocked (context);
2904 UNLOCK_CONTEXT (context);
2910 g_timeout_set_expiration (GTimeoutSource *timeout_source,
2911 GTimeVal *current_time)
2913 guint seconds = timeout_source->interval / 1000;
2914 guint msecs = timeout_source->interval - seconds * 1000;
2916 timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
2917 timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
2918 if (timeout_source->expiration.tv_usec >= 1000000)
2920 timeout_source->expiration.tv_usec -= 1000000;
2921 timeout_source->expiration.tv_sec++;
2926 g_timeout_prepare (GSource *source,
2931 GTimeVal current_time;
2933 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2935 g_source_get_current_time (source, ¤t_time);
2937 sec = timeout_source->expiration.tv_sec - current_time.tv_sec;
2938 msec = (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000;
2940 /* We do the following in a rather convoluted fashion to deal with
2941 * the fact that we don't have an integral type big enough to hold
2942 * the difference of two timevals in millseconds.
2944 if (sec < 0 || (sec == 0 && msec < 0))
2948 glong interval_sec = timeout_source->interval / 1000;
2949 glong interval_msec = timeout_source->interval % 1000;
2957 if (sec > interval_sec ||
2958 (sec == interval_sec && msec > interval_msec))
2960 /* The system time has been set backwards, so we
2961 * reset the expiration time to now + timeout_source->interval;
2962 * this at least avoids hanging for long periods of time.
2964 g_timeout_set_expiration (timeout_source, ¤t_time);
2965 msec = MIN (G_MAXINT, timeout_source->interval);
2969 msec = MIN (G_MAXINT, (guint)msec + 1000 * (guint)sec);
2973 *timeout = (gint)msec;
2979 g_timeout_check (GSource *source)
2981 GTimeVal current_time;
2982 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2984 g_source_get_current_time (source, ¤t_time);
2986 return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
2987 ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
2988 (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
2992 g_timeout_dispatch (GSource *source,
2993 GSourceFunc callback,
2996 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3000 g_warning ("Timeout source dispatched without callback\n"
3001 "You must call g_source_set_callback().");
3005 if (callback (user_data))
3007 GTimeVal current_time;
3009 g_source_get_current_time (source, ¤t_time);
3010 g_timeout_set_expiration (timeout_source, ¤t_time);
3019 * g_timeout_source_new:
3020 * @interval: the timeout interval in milliseconds.
3022 * Creates a new timeout source.
3024 * The source will not initially be associated with any #GMainContext
3025 * and must be added to one with g_source_attach() before it will be
3028 * Return value: the newly-created timeout source
3031 g_timeout_source_new (guint interval)
3033 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3034 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3035 GTimeVal current_time;
3037 timeout_source->interval = interval;
3039 g_get_current_time (¤t_time);
3040 g_timeout_set_expiration (timeout_source, ¤t_time);
3046 * g_timeout_add_full:
3047 * @priority: the priority of the idle source. Typically this will be in the
3048 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3049 * @interval: the time between calls to the function, in milliseconds
3050 * (1/1000ths of a second)
3051 * @function: function to call
3052 * @data: data to pass to @function
3053 * @notify: function to call when the idle is removed, or %NULL
3055 * Sets a function to be called at regular intervals, with the given
3056 * priority. The function is called repeatedly until it returns
3057 * %FALSE, at which point the timeout is automatically destroyed and
3058 * the function will not be called again. The @notify function is
3059 * called when the timeout is destroyed. The first call to the
3060 * function will be at the end of the first @interval.
3062 * Note that timeout functions may be delayed, due to the processing of other
3063 * event sources. Thus they should not be relied on for precise timing.
3064 * After each call to the timeout function, the time of the next
3065 * timeout is recalculated based on the current time and the given interval
3066 * (it does not try to 'catch up' time lost in delays).
3068 * Return value: the id of event source.
3071 g_timeout_add_full (gint priority,
3073 GSourceFunc function,
3075 GDestroyNotify notify)
3080 g_return_val_if_fail (function != NULL, 0);
3082 source = g_timeout_source_new (interval);
3084 if (priority != G_PRIORITY_DEFAULT)
3085 g_source_set_priority (source, priority);
3087 g_source_set_callback (source, function, data, notify);
3088 id = g_source_attach (source, NULL);
3089 g_source_unref (source);
3096 * @interval: the time between calls to the function, in milliseconds
3097 * (1/1000ths of a second)
3098 * @function: function to call
3099 * @data: data to pass to @function
3101 * Sets a function to be called at regular intervals, with the default
3102 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
3103 * until it returns %FALSE, at which point the timeout is automatically
3104 * destroyed and the function will not be called again. The first call
3105 * to the function will be at the end of the first @interval.
3107 * Note that timeout functions may be delayed, due to the processing of other
3108 * event sources. Thus they should not be relied on for precise timing.
3109 * After each call to the timeout function, the time of the next
3110 * timeout is recalculated based on the current time and the given interval
3111 * (it does not try to 'catch up' time lost in delays).
3113 * Return value: the id of event source.
3116 g_timeout_add (guint32 interval,
3117 GSourceFunc function,
3120 return g_timeout_add_full (G_PRIORITY_DEFAULT,
3121 interval, function, data, NULL);
3124 /* Idle functions */
3127 g_idle_prepare (GSource *source,
3136 g_idle_check (GSource *source)
3142 g_idle_dispatch (GSource *source,
3143 GSourceFunc callback,
3148 g_warning ("Idle source dispatched without callback\n"
3149 "You must call g_source_set_callback().");
3153 return callback (user_data);
3157 * g_idle_source_new:
3159 * Creates a new idle source.
3161 * The source will not initially be associated with any #GMainContext
3162 * and must be added to one with g_source_attach() before it will be
3165 * Return value: the newly-created idle source
3168 g_idle_source_new (void)
3170 return g_source_new (&g_idle_funcs, sizeof (GSource));
3175 * @priority: the priority of the idle source. Typically this will be in the
3176 * range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3177 * @function: function to call
3178 * @data: data to pass to @function
3179 * @notify: function to call when the idle is removed, or %NULL
3181 * Adds a function to be called whenever there are no higher priority
3182 * events pending. If the function returns %FALSE it is automatically
3183 * removed from the list of event sources and will not be called again.
3185 * Return value: the id of the event source.
3188 g_idle_add_full (gint priority,
3189 GSourceFunc function,
3191 GDestroyNotify notify)
3196 g_return_val_if_fail (function != NULL, 0);
3198 source = g_idle_source_new ();
3200 if (priority != G_PRIORITY_DEFAULT)
3201 g_source_set_priority (source, priority);
3203 g_source_set_callback (source, function, data, notify);
3204 id = g_source_attach (source, NULL);
3205 g_source_unref (source);
3212 * @function: function to call
3213 * @data: data to pass to @function.
3215 * Adds a function to be called whenever there are no higher priority
3216 * events pending to the default main loop. The function is given the
3217 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
3218 * returns %FALSE it is automatically removed from the list of event
3219 * sources and will not be called again.
3221 * Return value: the id of the event source.
3224 g_idle_add (GSourceFunc function,
3227 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
3231 * g_idle_remove_by_data:
3232 * @data: the data for the idle source's callback.
3234 * Removes the idle function with the given data.
3236 * Return value: %TRUE if an idle source was found and removed.
3239 g_idle_remove_by_data (gpointer data)
3241 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);