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 #if defined(G_PLATFORM_WIN32) && defined(__GNUC__)
224 __declspec(dllexport)
226 GSourceFuncs g_timeout_funcs =
234 #if defined(G_PLATFORM_WIN32) && defined(__GNUC__)
235 __declspec(dllexport)
237 GSourceFuncs g_idle_funcs =
246 /* SunOS has poll, but doesn't provide a prototype. */
247 # if defined (sun) && !defined (__SVR4)
248 extern gint poll (GPollFD *ufds, guint nfsd, gint timeout);
250 #else /* !HAVE_POLL */
255 g_poll (GPollFD *fds,
259 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
260 gboolean poll_msgs = FALSE;
267 for (f = fds; f < &fds[nfds]; ++f)
270 if (f->events & G_IO_IN)
272 if (f->fd == G_WIN32_MSG_HANDLE)
276 #ifdef G_MAIN_POLL_DEBUG
277 g_print ("g_poll: waiting for %#x\n", f->fd);
279 handles[nhandles++] = (HANDLE) f->fd;
289 /* Waiting for messages, and maybe events
290 * -> First PeekMessage
292 #ifdef G_MAIN_POLL_DEBUG
293 g_print ("PeekMessage\n");
295 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
296 ready = WAIT_OBJECT_0 + nhandles;
301 /* Waiting just for messages */
302 if (timeout == INFINITE)
307 #ifdef G_MAIN_POLL_DEBUG
308 g_print ("WaitMessage\n");
311 g_warning (G_STRLOC ": WaitMessage() failed");
312 ready = WAIT_OBJECT_0 + nhandles;
314 else if (timeout == 0)
316 /* Waiting just for messages, zero timeout.
317 * If we got here, there was no message
319 ready = WAIT_TIMEOUT;
323 /* Waiting just for messages, some timeout
324 * -> Set a timer, wait for message,
325 * kill timer, use PeekMessage
327 timer = SetTimer (NULL, 0, timeout, NULL);
329 g_warning (G_STRLOC ": SetTimer() failed");
332 #ifdef G_MAIN_POLL_DEBUG
333 g_print ("WaitMessage\n");
336 KillTimer (NULL, timer);
337 #ifdef G_MAIN_POLL_DEBUG
338 g_print ("PeekMessage\n");
340 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE)
341 && msg.message != WM_TIMER)
342 ready = WAIT_OBJECT_0;
344 ready = WAIT_TIMEOUT;
350 /* Wait for either message or event
351 * -> Use MsgWaitForMultipleObjects
353 #ifdef G_MAIN_POLL_DEBUG
354 g_print ("MsgWaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
356 ready = MsgWaitForMultipleObjects (nhandles, handles, FALSE,
357 timeout, QS_ALLINPUT);
359 if (ready == WAIT_FAILED)
360 g_warning (G_STRLOC ": MsgWaitForMultipleObjects() failed");
364 else if (nhandles == 0)
366 /* Wait for nothing (huh?) */
371 /* Wait for just events
372 * -> Use WaitForMultipleObjects
374 #ifdef G_MAIN_POLL_DEBUG
375 g_print ("WaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
377 ready = WaitForMultipleObjects (nhandles, handles, FALSE, timeout);
378 if (ready == WAIT_FAILED)
379 g_warning (G_STRLOC ": WaitForMultipleObjects() failed");
382 #ifdef G_MAIN_POLL_DEBUG
383 g_print ("wait returns %d%s\n",
385 (ready == WAIT_FAILED ? " (WAIT_FAILED)" :
386 (ready == WAIT_TIMEOUT ? " (WAIT_TIMEOUT)" :
387 (poll_msgs && ready == WAIT_OBJECT_0 + nhandles ? " (msg)" : ""))));
389 for (f = fds; f < &fds[nfds]; ++f)
392 if (ready == WAIT_FAILED)
394 else if (ready == WAIT_TIMEOUT)
396 else if (poll_msgs && ready == WAIT_OBJECT_0 + nhandles)
398 for (f = fds; f < &fds[nfds]; ++f)
401 if (f->events & G_IO_IN)
402 if (f->fd == G_WIN32_MSG_HANDLE)
403 f->revents |= G_IO_IN;
406 #if TEST_WITHOUT_THIS
407 else if (ready >= WAIT_OBJECT_0 && ready < WAIT_OBJECT_0 + nhandles)
408 for (f = fds; f < &fds[nfds]; ++f)
410 if ((f->events & G_IO_IN)
411 && f->fd == (gint) handles[ready - WAIT_OBJECT_0])
413 f->revents |= G_IO_IN;
414 #ifdef G_MAIN_POLL_DEBUG
415 g_print ("g_poll: got event %#x\n", f->fd);
418 ResetEvent ((HANDLE) f->fd);
427 #else /* !G_OS_WIN32 */
429 /* The following implementation of poll() comes from the GNU C Library.
430 * Copyright (C) 1994, 1996, 1997 Free Software Foundation, Inc.
433 #include <string.h> /* for bzero on BSD systems */
435 #ifdef HAVE_SYS_SELECT_H
436 #include <sys/select.h>
437 #endif /* HAVE_SYS_SELECT_H */
441 #endif /* G_OS_BEOS */
444 # define SELECT_MASK fd_set
445 #else /* !NO_FD_SET */
447 typedef long fd_mask;
450 # define SELECT_MASK void
452 # define SELECT_MASK int
453 # endif /* !_IBMR2 */
454 #endif /* !NO_FD_SET */
457 g_poll (GPollFD *fds,
462 SELECT_MASK rset, wset, xset;
471 for (f = fds; f < &fds[nfds]; ++f)
474 if (f->events & G_IO_IN)
475 FD_SET (f->fd, &rset);
476 if (f->events & G_IO_OUT)
477 FD_SET (f->fd, &wset);
478 if (f->events & G_IO_PRI)
479 FD_SET (f->fd, &xset);
480 if (f->fd > maxfd && (f->events & (G_IO_IN|G_IO_OUT|G_IO_PRI)))
484 tv.tv_sec = timeout / 1000;
485 tv.tv_usec = (timeout % 1000) * 1000;
487 ready = select (maxfd + 1, &rset, &wset, &xset,
488 timeout == -1 ? NULL : &tv);
490 for (f = fds; f < &fds[nfds]; ++f)
495 if (FD_ISSET (f->fd, &rset))
496 f->revents |= G_IO_IN;
497 if (FD_ISSET (f->fd, &wset))
498 f->revents |= G_IO_OUT;
499 if (FD_ISSET (f->fd, &xset))
500 f->revents |= G_IO_PRI;
507 #endif /* !G_OS_WIN32 */
509 #endif /* !HAVE_POLL */
512 * g_main_context_ref:
513 * @context: a #GMainContext
515 * Increases the reference count on a #GMainContext object by one.
518 g_main_context_ref (GMainContext *context)
520 g_return_if_fail (context != NULL);
521 g_return_if_fail (context->ref_count > 0);
523 LOCK_CONTEXT (context);
525 context->ref_count++;
527 UNLOCK_CONTEXT (context);
531 g_main_context_unref_and_unlock (GMainContext *context)
535 context->ref_count--;
537 if (context->ref_count != 0)
539 UNLOCK_CONTEXT (context);
543 source = context->source_list;
546 GSource *next = source->next;
547 g_source_destroy_internal (source, context, TRUE);
550 UNLOCK_CONTEXT (context);
552 #ifdef G_THREADS_ENABLED
553 g_static_mutex_free (&context->mutex);
556 g_ptr_array_free (context->pending_dispatches, TRUE);
557 g_free (context->cached_poll_array);
559 g_mem_chunk_destroy (context->poll_chunk);
561 #ifdef G_THREADS_ENABLED
562 if (g_thread_supported())
565 close (context->wake_up_pipe[0]);
566 close (context->wake_up_pipe[1]);
568 CloseHandle (context->wake_up_semaphore);
577 * g_main_context_unref:
578 * @context: a #GMainContext
580 * Decreases the reference count on a #GMainContext object by one. If
581 * the result is zero, free the context and free all associated memory.
584 g_main_context_unref (GMainContext *context)
586 g_return_if_fail (context != NULL);
587 g_return_if_fail (context->ref_count > 0);
589 LOCK_CONTEXT (context);
590 g_main_context_unref_and_unlock (context);
594 * g_main_context_new:
596 * Creates a new #GMainContext strcuture
598 * Return value: the new #GMainContext
601 g_main_context_new ()
603 GMainContext *context = g_new0 (GMainContext, 1);
605 #ifdef G_THREADS_ENABLED
606 g_static_mutex_init (&context->mutex);
608 context->owner = NULL;
609 context->waiters = NULL;
612 context->ref_count = 1;
614 context->next_id = 1;
616 context->source_list = NULL;
619 context->poll_func = (GPollFunc)poll;
621 context->poll_func = g_poll;
624 context->cached_poll_array = NULL;
625 context->cached_poll_array_size = 0;
627 context->pending_dispatches = g_ptr_array_new ();
629 context->time_is_current = FALSE;
631 #ifdef G_THREADS_ENABLED
632 if (g_thread_supported ())
635 if (pipe (context->wake_up_pipe) < 0)
636 g_error ("Cannot create pipe main loop wake-up: %s\n",
639 context->wake_up_rec.fd = context->wake_up_pipe[0];
640 context->wake_up_rec.events = G_IO_IN;
641 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
643 context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
644 if (context->wake_up_semaphore == NULL)
645 g_error ("Cannot create wake-up semaphore: %s",
646 g_win32_error_message (GetLastError ()));
647 context->wake_up_rec.fd = (gint) context->wake_up_semaphore;
648 context->wake_up_rec.events = G_IO_IN;
649 #ifdef G_MAIN_POLL_DEBUG
650 g_print ("wake-up semaphore: %#x\n", (guint) context->wake_up_semaphore);
652 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
661 * g_main_context_default:
663 * Return the default main context. This is the main context used
664 * for main loop functions when a main loop is not explicitly
667 * Return value: the default main context.
670 g_main_context_default (void)
676 if (!default_main_context)
677 default_main_context = g_main_context_new ();
679 G_UNLOCK (main_loop);
681 return default_main_context;
684 /* Hooks for adding to the main loop */
688 * @source_funcs: structure containing functions that implement
689 * the sources behavior.
690 * @struct_size: size of the #GSource structure to create
692 * Create a new GSource structure. The size is specified to
693 * allow creating structures derived from GSource that contain
694 * additional data. The size passed in must be at least
697 * The source will not initially be associated with any #GMainContext
698 * and must be added to one with g_source_add() before it will be
701 * Return value: the newly create #GSource
704 g_source_new (GSourceFuncs *source_funcs,
709 g_return_val_if_fail (source_funcs != NULL, NULL);
710 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
712 source = (GSource*) g_malloc0 (struct_size);
714 source->source_funcs = source_funcs;
715 source->ref_count = 1;
717 source->priority = G_PRIORITY_DEFAULT;
719 source->flags = G_HOOK_FLAG_ACTIVE;
721 /* NULL/0 initialization for all other fields */
726 /* Holds context's lock
729 g_source_list_add (GSource *source,
730 GMainContext *context)
732 GSource *tmp_source, *last_source;
735 tmp_source = context->source_list;
736 while (tmp_source && tmp_source->priority <= source->priority)
738 last_source = tmp_source;
739 tmp_source = tmp_source->next;
742 source->next = tmp_source;
744 tmp_source->prev = source;
746 source->prev = last_source;
748 last_source->next = source;
750 context->source_list = source;
753 /* Holds context's lock
756 g_source_list_remove (GSource *source,
757 GMainContext *context)
760 source->prev->next = source->next;
762 context->source_list = source->next;
765 source->next->prev = source->prev;
773 * @source: a #GSource
774 * @context: a #GMainContext (if %NULL, the default context will be used)
776 * Adds a #GSource to a @context so that it will be executed within
779 * Return value: the ID for the source within the #GMainContext
782 g_source_attach (GSource *source,
783 GMainContext *context)
788 g_return_val_if_fail (source->context == NULL, 0);
789 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
792 context = g_main_context_default ();
794 LOCK_CONTEXT (context);
796 source->context = context;
797 result = source->id = context->next_id++;
800 g_source_list_add (source, context);
802 tmp_list = source->poll_fds;
805 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
806 tmp_list = tmp_list->next;
809 #ifdef G_THREADS_ENABLED
810 /* Now wake up the main loop if it is waiting in the poll() */
811 g_main_context_wakeup_unlocked (context);
814 UNLOCK_CONTEXT (context);
820 g_source_destroy_internal (GSource *source,
821 GMainContext *context,
825 LOCK_CONTEXT (context);
827 if (!SOURCE_DESTROYED (source))
830 gpointer old_cb_data;
831 GSourceCallbackFuncs *old_cb_funcs;
833 source->flags &= ~G_HOOK_FLAG_ACTIVE;
835 old_cb_data = source->callback_data;
836 old_cb_funcs = source->callback_funcs;
838 source->callback_data = NULL;
839 source->callback_funcs = NULL;
843 UNLOCK_CONTEXT (context);
844 old_cb_funcs->unref (old_cb_data);
845 LOCK_CONTEXT (context);
848 tmp_list = source->poll_fds;
851 g_main_context_remove_poll_unlocked (context, tmp_list->data);
852 tmp_list = tmp_list->next;
855 g_source_unref_internal (source, context, TRUE);
859 UNLOCK_CONTEXT (context);
864 * @source: a #GSource
866 * Remove a source from its #GMainContext, if any, and mark it as
867 * destroyed. The source cannot be subsequently added to another
871 g_source_destroy (GSource *source)
873 GMainContext *context;
875 g_return_if_fail (source != NULL);
877 context = source->context;
880 g_source_destroy_internal (source, context, FALSE);
882 source->flags &= ~G_HOOK_FLAG_ACTIVE;
887 * @source: a #GSource
889 * Return the numeric ID for a particular source. The ID of a source
890 * is unique within a particular main loop context. The reverse
891 * mapping from ID to source is done by g_main_context_find_source_by_id().
893 * Return value: the ID for the source
896 g_source_get_id (GSource *source)
900 g_return_val_if_fail (source != NULL, 0);
901 g_return_val_if_fail (source->context != NULL, 0);
903 LOCK_CONTEXT (source->context);
905 UNLOCK_CONTEXT (source->context);
911 * g_source_get_context:
912 * @source: a #GSource
914 * Get the #GMainContext with which the source is associated.
915 * Calling this function on a destroyed source is an error.
917 * Return value: the #GMainContext with which the source is associated,
918 * or %NULL if the context has not yet been added
922 g_source_get_context (GSource *source)
924 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
926 return source->context;
932 * @fd: a #GPollFD structure holding information about a file
933 * descriptor to watch.
935 * Add a file descriptor to the set of file descriptors polled for
936 * this source. This is usually combined with g_source_new() to add an
937 * event source. The event source's check function will typically test
938 * the revents field in the #GPollFD struct and return %TRUE if events need
942 g_source_add_poll (GSource *source,
945 GMainContext *context;
947 g_return_if_fail (source != NULL);
948 g_return_if_fail (fd != NULL);
949 g_return_if_fail (!SOURCE_DESTROYED (source));
951 context = source->context;
954 LOCK_CONTEXT (context);
956 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
960 g_main_context_add_poll_unlocked (context, source->priority, fd);
961 UNLOCK_CONTEXT (context);
966 * g_source_remove_poll:
968 * @fd: a #GPollFD structure previously passed to g_source_poll.
970 * Remove a file descriptor from the set of file descriptors polled for
974 g_source_remove_poll (GSource *source,
977 GMainContext *context;
979 g_return_if_fail (source != NULL);
980 g_return_if_fail (fd != NULL);
981 g_return_if_fail (!SOURCE_DESTROYED (source));
983 context = source->context;
986 LOCK_CONTEXT (context);
988 source->poll_fds = g_slist_remove (source->poll_fds, fd);
992 g_main_context_remove_poll_unlocked (context, fd);
993 UNLOCK_CONTEXT (context);
998 * g_source_set_callback_indirect:
999 * @source: the source
1000 * @callback_data: pointer to callback data "object"
1001 * @callback_funcs: functions for reference counting callback_data
1002 * and getting the callback and data
1004 * Set the callback function storing the data as a refcounted callback
1005 * "object". This is used to implement g_source_set_callback_closure()
1006 * and internally. Note that calling g_source_set_callback_indirect() assumes
1007 * an initial reference count on @callback_data, and thus
1008 * @callback_funcs->unref will eventually be called once more
1009 * than @callback_funcs->ref.
1012 g_source_set_callback_indirect (GSource *source,
1013 gpointer callback_data,
1014 GSourceCallbackFuncs *callback_funcs)
1016 GMainContext *context;
1017 gpointer old_cb_data;
1018 GSourceCallbackFuncs *old_cb_funcs;
1020 g_return_if_fail (source != NULL);
1021 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1023 context = source->context;
1026 LOCK_CONTEXT (context);
1028 old_cb_data = source->callback_data;
1029 old_cb_funcs = source->callback_funcs;
1031 source->callback_data = callback_data;
1032 source->callback_funcs = callback_funcs;
1035 UNLOCK_CONTEXT (context);
1038 old_cb_funcs->unref (old_cb_data);
1042 g_source_callback_ref (gpointer cb_data)
1044 GSourceCallback *callback = cb_data;
1046 callback->ref_count++;
1051 g_source_callback_unref (gpointer cb_data)
1053 GSourceCallback *callback = cb_data;
1055 callback->ref_count--;
1056 if (callback->ref_count == 0)
1058 if (callback->notify)
1059 callback->notify (callback->data);
1065 g_source_callback_get (gpointer cb_data,
1070 GSourceCallback *callback = cb_data;
1072 *func = callback->func;
1073 *data = callback->data;
1076 static GSourceCallbackFuncs g_source_callback_funcs = {
1077 g_source_callback_ref,
1078 g_source_callback_unref,
1079 g_source_callback_get,
1083 * g_source_set_callback:
1084 * @source: the source
1085 * @func: a callback function
1086 * @data: the data to pass to callback function
1087 * @notify: a function to call when @data is no longer in use, or %NULL.
1089 * Set the callback function for a source.
1092 g_source_set_callback (GSource *source,
1095 GDestroyNotify notify)
1097 GSourceCallback *new_callback;
1099 g_return_if_fail (source != NULL);
1101 new_callback = g_new (GSourceCallback, 1);
1103 new_callback->ref_count = 1;
1104 new_callback->func = func;
1105 new_callback->data = data;
1106 new_callback->notify = notify;
1108 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1112 * g_source_set_priority:
1113 * @source: a #GSource
1114 * @priority: the new priority.
1116 * Set the priority of a source. While the main loop is being
1117 * run, a source will
1120 g_source_set_priority (GSource *source,
1124 GMainContext *context;
1126 g_return_if_fail (source != NULL);
1128 context = source->context;
1131 LOCK_CONTEXT (context);
1133 source->priority = priority;
1137 source->next = NULL;
1138 source->prev = NULL;
1140 tmp_list = source->poll_fds;
1143 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1144 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1146 tmp_list = tmp_list->next;
1149 UNLOCK_CONTEXT (source->context);
1154 * g_source_get_priority:
1155 * @source: a #GSource
1157 * Gets the priority of a surce
1159 * Return value: the priority of the source
1162 g_source_get_priority (GSource *source)
1164 g_return_val_if_fail (source != NULL, 0);
1166 return source->priority;
1170 * g_source_set_can_recurse:
1171 * @source: a #GSource
1172 * @can_recurse: whether recursion is allowed for this source
1174 * Sets whether a source can be called recursively. If @can_recurse is
1175 * %TRUE, then while the source is being dispatched then this source
1176 * will be processed normally. Otherwise, all processing of this
1177 * source is blocked until the dispatch function returns.
1180 g_source_set_can_recurse (GSource *source,
1181 gboolean can_recurse)
1183 GMainContext *context;
1185 g_return_if_fail (source != NULL);
1187 context = source->context;
1190 LOCK_CONTEXT (context);
1193 source->flags |= G_SOURCE_CAN_RECURSE;
1195 source->flags &= ~G_SOURCE_CAN_RECURSE;
1198 UNLOCK_CONTEXT (context);
1202 * g_source_get_can_recurse:
1203 * @source: a #GSource
1205 * Checks whether a source is allowed to be called recursively.
1206 * see g_source_set_can_recurse.
1208 * Return value: whether recursion is allowed.
1211 g_source_get_can_recurse (GSource *source)
1213 g_return_val_if_fail (source != NULL, FALSE);
1215 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1220 * @source: a #GSource
1222 * Increases the reference count on a source by one.
1224 * Return value: @source
1227 g_source_ref (GSource *source)
1229 GMainContext *context;
1231 g_return_val_if_fail (source != NULL, NULL);
1233 context = source->context;
1236 LOCK_CONTEXT (context);
1238 source->ref_count++;
1241 UNLOCK_CONTEXT (context);
1246 /* g_source_unref() but possible to call within context lock
1249 g_source_unref_internal (GSource *source,
1250 GMainContext *context,
1253 gpointer old_cb_data = NULL;
1254 GSourceCallbackFuncs *old_cb_funcs = NULL;
1256 g_return_if_fail (source != NULL);
1258 if (!have_lock && context)
1259 LOCK_CONTEXT (context);
1261 source->ref_count--;
1262 if (source->ref_count == 0)
1264 old_cb_data = source->callback_data;
1265 old_cb_funcs = source->callback_funcs;
1267 source->callback_data = NULL;
1268 source->callback_funcs = NULL;
1270 if (context && !SOURCE_DESTROYED (source))
1272 g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1273 source->ref_count++;
1276 g_source_list_remove (source, context);
1278 if (source->source_funcs->finalize)
1279 source->source_funcs->finalize (source);
1281 g_slist_free (source->poll_fds);
1282 source->poll_fds = NULL;
1286 if (!have_lock && context)
1287 UNLOCK_CONTEXT (context);
1292 UNLOCK_CONTEXT (context);
1294 old_cb_funcs->unref (old_cb_data);
1297 LOCK_CONTEXT (context);
1303 * @source: a #GSource
1305 * Decreases the reference count of a source by one. If the
1306 * resulting reference count is zero the source and associated
1307 * memory will be destroyed.
1310 g_source_unref (GSource *source)
1312 g_return_if_fail (source != NULL);
1314 g_source_unref_internal (source, source->context, FALSE);
1318 * g_main_context_find_source_by_id:
1319 * @context: a #GMainContext (if %NULL, the default context will be used)
1320 * @id: the source ID, as returned by g_source_get_id()
1322 * Finds a #GSource given a pair of context and ID
1324 * Return value: the #GSource if found, otherwise, %NULL
1327 g_main_context_find_source_by_id (GMainContext *context,
1332 g_return_val_if_fail (id > 0, FALSE);
1334 if (context == NULL)
1335 context = g_main_context_default ();
1337 LOCK_CONTEXT (context);
1339 source = context->source_list;
1342 if (!SOURCE_DESTROYED (source) &&
1345 source = source->next;
1348 UNLOCK_CONTEXT (context);
1354 * g_main_context_find_source_by_funcs_user_data:
1355 * @context: a #GMainContext (if %NULL, the default context will be used).
1356 * @funcs: the @source_funcs passed to g_source_new().
1357 * @user_data: the user data from the callback.
1359 * Finds a source with the given source functions and user data. If
1360 * multiple sources exist with the same source function and user data,
1361 * the first one found will be returned.
1363 * Return value: the source, if one was found, otherwise %NULL
1366 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1367 GSourceFuncs *funcs,
1372 g_return_val_if_fail (funcs != NULL, FALSE);
1374 if (context == NULL)
1375 context = g_main_context_default ();
1377 LOCK_CONTEXT (context);
1379 source = context->source_list;
1382 if (!SOURCE_DESTROYED (source) &&
1383 source->source_funcs == funcs &&
1384 source->callback_funcs)
1386 GSourceFunc callback;
1387 gpointer callback_data;
1389 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1391 if (callback_data == user_data)
1394 source = source->next;
1397 UNLOCK_CONTEXT (context);
1403 * g_main_context_find_source_by_user_data:
1404 * @context: a #GMainContext
1405 * @user_data: the user_data for the callback.
1407 * Finds a source with the given user data for the callback. If
1408 * multiple sources exist with the same user data, the first
1409 * one found will be returned.
1411 * Return value: the source, if one was found, otherwise %NULL
1414 g_main_context_find_source_by_user_data (GMainContext *context,
1419 if (context == NULL)
1420 context = g_main_context_default ();
1422 LOCK_CONTEXT (context);
1424 source = context->source_list;
1427 if (!SOURCE_DESTROYED (source) &&
1428 source->callback_funcs)
1430 GSourceFunc callback;
1431 gpointer callback_data = NULL;
1433 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1435 if (callback_data == user_data)
1438 source = source->next;
1441 UNLOCK_CONTEXT (context);
1448 * @tag: the id of the source to remove.
1450 * Removes the source with the given id from the default main
1451 * context. The id of a #GSource is given by g_source_get_id(),
1452 * or will be returned by the functions g_source_attach(),
1453 * g_idle_add(), g_idle_add_full(), g_timeout_add(),
1454 * g_timeout_add_full(), g_io_add_watch, and g_io_add_watch_full().
1456 * See also g_source_destroy().
1458 * Return value: %TRUE if the source was found and removed.
1461 g_source_remove (guint tag)
1465 g_return_val_if_fail (tag > 0, FALSE);
1467 source = g_main_context_find_source_by_id (NULL, tag);
1469 g_source_destroy (source);
1471 return source != NULL;
1475 * g_source_remove_by_user_data:
1476 * @user_data: the user_data for the callback.
1478 * Removes a source from the default main loop context given the user
1479 * data for the callback. If multiple sources exist with the same user
1480 * data, only one will be destroyed.
1482 * Return value: %TRUE if a source was found and removed.
1485 g_source_remove_by_user_data (gpointer user_data)
1489 source = g_main_context_find_source_by_user_data (NULL, user_data);
1492 g_source_destroy (source);
1500 * g_source_remove_by_funcs_user_data:
1501 * @funcs: The @source_funcs passed to g_source_new()
1502 * @user_data: the user data for the callback
1504 * Removes a source from the default main loop context given the
1505 * source functions and user data. If multiple sources exist with the
1506 * same source functions and user data, only one will be destroyed.
1508 * Return value: %TRUE if a source was found and removed.
1511 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1516 g_return_val_if_fail (funcs != NULL, FALSE);
1518 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1521 g_source_destroy (source);
1529 * g_get_current_time:
1530 * @result: #GTimeVal structure in which to store current time.
1532 * Equivalent to Unix's <function>gettimeofday()</function>, but portable
1535 g_get_current_time (GTimeVal *result)
1540 g_return_if_fail (result != NULL);
1542 /*this is required on alpha, there the timeval structs are int's
1543 not longs and a cast only would fail horribly*/
1544 gettimeofday (&r, NULL);
1545 result->tv_sec = r.tv_sec;
1546 result->tv_usec = r.tv_usec;
1548 /* Avoid calling time() except for the first time.
1549 * GetTickCount() should be pretty fast and low-level?
1550 * I could also use ftime() but it seems unnecessarily overheady.
1552 static DWORD start_tick = 0;
1553 static time_t start_time;
1556 g_return_if_fail (result != NULL);
1558 if (start_tick == 0)
1560 start_tick = GetTickCount ();
1564 tick = GetTickCount ();
1566 result->tv_sec = (tick - start_tick) / 1000 + start_time;
1567 result->tv_usec = ((tick - start_tick) % 1000) * 1000;
1571 /* Running the main loop */
1573 /* HOLDS: context's lock */
1575 g_main_dispatch (GMainContext *context)
1579 for (i = 0; i < context->pending_dispatches->len; i++)
1581 GSource *source = context->pending_dispatches->pdata[i];
1583 context->pending_dispatches->pdata[i] = NULL;
1586 source->flags &= ~G_SOURCE_READY;
1588 if (!SOURCE_DESTROYED (source))
1590 gboolean was_in_call;
1591 gpointer user_data = NULL;
1592 GSourceFunc callback = NULL;
1593 GSourceCallbackFuncs *cb_funcs;
1595 gboolean need_destroy;
1597 gboolean (*dispatch) (GSource *,
1601 dispatch = source->source_funcs->dispatch;
1602 cb_funcs = source->callback_funcs;
1603 cb_data = source->callback_data;
1606 cb_funcs->ref (cb_data);
1608 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
1609 source->flags |= G_HOOK_FLAG_IN_CALL;
1612 cb_funcs->get (cb_data, source, &callback, &user_data);
1614 UNLOCK_CONTEXT (context);
1616 need_destroy = ! dispatch (source,
1619 LOCK_CONTEXT (context);
1622 cb_funcs->unref (cb_data);
1625 source->flags &= ~G_HOOK_FLAG_IN_CALL;
1627 /* Note: this depends on the fact that we can't switch
1628 * sources from one main context to another
1630 if (need_destroy && !SOURCE_DESTROYED (source))
1632 g_assert (source->context == context);
1633 g_source_destroy_internal (source, context, TRUE);
1637 SOURCE_UNREF (source, context);
1640 g_ptr_array_set_size (context->pending_dispatches, 0);
1643 /* Holds context's lock */
1644 static inline GSource *
1645 next_valid_source (GMainContext *context,
1648 GSource *new_source = source ? source->next : context->source_list;
1652 if (!SOURCE_DESTROYED (new_source))
1654 new_source->ref_count++;
1658 new_source = new_source->next;
1662 SOURCE_UNREF (source, context);
1668 * g_main_context_acquire:
1669 * @context: a #GMainContext
1671 * Tries to become the owner of the specified context.
1672 * If some other context is the owner of the context,
1673 * returns %FALSE immediately. Ownership is properly
1674 * recursive: the owner can require ownership again
1675 * and will release ownership when g_main_context_release()
1676 * is called as many times as g_main_context_acquire().
1678 * You must be the owner of a context before you
1679 * can call g_main_context_prepare(), g_main_context_query(),
1680 * g_main_context_check(), g_main_context_dispatch().
1682 * Return value: %TRUE if the operation succeeded, and
1683 * this thread is now the owner of @context.
1686 g_main_context_acquire (GMainContext *context)
1688 #ifdef G_THREAD_ENABLED
1689 gboolean result = FALSE;
1690 GThread *self = G_THREAD_SELF;
1692 if (context == NULL)
1693 context = g_main_context_default ();
1695 LOCK_CONTEXT (context);
1697 if (!context->owner)
1699 context->owner = self;
1700 g_assert (context->owner_count == 0);
1703 if (context->owner == self)
1705 context->owner_count++;
1709 UNLOCK_CONTEXT (context);
1712 #else /* !G_THREAD_ENABLED */
1714 #endif /* G_THREAD_ENABLED */
1718 * g_main_context_release:
1719 * @context: a #GMainContext
1721 * Release ownership of a context previously acquired by this thread
1722 * with g_main_context_acquire(). If the context was acquired multiple
1723 * times, the only release ownership when g_main_context_release()
1724 * is called as many times as it was acquired.
1727 g_main_context_release (GMainContext *context)
1729 #ifdef G_THREAD_ENABLED
1730 if (context == NULL)
1731 context = g_main_context_default ();
1733 LOCK_CONTEXT (context);
1735 context->owner_count--;
1736 if (context->owner_count == 0)
1738 context->owner = NULL;
1740 if (context->waiters)
1742 GMainWaiter *waiter = context->waiters->data;
1743 gboolean loop_internal_waiter =
1744 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
1745 context->waiters = g_slist_delete_link (context->waiters,
1747 if (!loop_internal_waiter)
1748 g_mutex_lock (waiter->mutex);
1750 g_cond_signal (waiter->cond);
1752 if (!loop_internal_waiter)
1753 g_mutex_unlock (waiter->mutex);
1757 UNLOCK_CONTEXT (context);
1760 #endif /* G_THREAD_ENABLED */
1764 * g_main_context_wait:
1765 * @context: a #GMainContext
1766 * @cond: a condition variable
1767 * @mutex: a mutex, currently held
1769 * Tries to become the owner of the specified context,
1770 * as with g_main_context_acquire. But if another thread
1771 * is the owner, atomically drop @mutex and wait on
1772 * @cond until wait until that owner releases
1773 * ownership or until @cond is signaled, then
1774 * try again (once) to become the owner.
1776 * Return value: %TRUE if the operation succeeded, and
1777 * this thread is now the owner of @context.
1780 g_main_context_wait (GMainContext *context,
1784 #ifdef G_THREAD_ENABLED
1785 gboolean result = FALSE;
1786 GThread *self = G_THREAD_SELF;
1787 gboolean loop_internal_waiter;
1789 if (context == NULL)
1790 context = g_main_context_default ();
1792 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
1794 if (!loop_internal_waiter)
1795 LOCK_CONTEXT (context);
1797 if (context->owner && context->owner != self)
1802 waiter.mutex = mutex;
1804 context->waiters = g_slist_append (context->waiters, &waiter);
1806 if (!loop_internal_waiter)
1807 UNLOCK_CONTEXT (context);
1808 g_cond_wait (cond, mutex);
1809 if (!loop_internal_waiter)
1810 LOCK_CONTEXT (context);
1812 context->waiters = g_slist_remove (context->waiters, &waiter);
1815 if (!context->owner)
1817 context->owner = self;
1818 g_assert (context->owner_count == 0);
1821 if (context->owner == self)
1823 context->owner_count++;
1827 if (!loop_internal_waiter)
1828 UNLOCK_CONTEXT (context);
1831 #else /* !G_THREAD_ENABLED */
1833 #endif /* G_THREAD_ENABLED */
1837 * g_main_context_prepare:
1838 * @context: a #GMainContext
1839 * @priority: location to store priority of highest priority
1840 * source already ready.
1842 * Prepares to poll sources within a main loop. The resulting information
1843 * for polling is determined by calling g_main_context_query ().
1845 * Return value: %TRUE if some source is ready to be dispatched
1849 g_main_context_prepare (GMainContext *context,
1853 gint current_priority = G_MAXINT;
1856 if (context == NULL)
1857 context = g_main_context_default ();
1859 LOCK_CONTEXT (context);
1861 context->time_is_current = FALSE;
1863 if (context->in_check_or_prepare)
1865 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
1866 "prepare() member.");
1867 UNLOCK_CONTEXT (context);
1871 #ifdef G_THREADS_ENABLED
1872 if (context->poll_waiting)
1874 g_warning("g_main_context_prepare(): main loop already active in another thread");
1875 UNLOCK_CONTEXT (context);
1879 context->poll_waiting = TRUE;
1880 #endif /* G_THREADS_ENABLED */
1883 /* If recursing, finish up current dispatch, before starting over */
1884 if (context->pending_dispatches)
1887 g_main_dispatch (context, ¤t_time);
1889 UNLOCK_CONTEXT (context);
1894 /* If recursing, clear list of pending dispatches */
1895 g_ptr_array_set_size (context->pending_dispatches, 0);
1897 /* Prepare all sources */
1899 context->timeout = -1;
1901 source = next_valid_source (context, NULL);
1904 gint source_timeout = -1;
1906 if ((n_ready > 0) && (source->priority > current_priority))
1908 SOURCE_UNREF (source, context);
1911 if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
1914 if (!(source->flags & G_SOURCE_READY))
1917 gboolean (*prepare) (GSource *source,
1920 prepare = source->source_funcs->prepare;
1921 context->in_check_or_prepare++;
1922 UNLOCK_CONTEXT (context);
1924 result = (*prepare) (source, &source_timeout);
1926 LOCK_CONTEXT (context);
1927 context->in_check_or_prepare--;
1930 source->flags |= G_SOURCE_READY;
1933 if (source->flags & G_SOURCE_READY)
1936 current_priority = source->priority;
1937 context->timeout = 0;
1940 if (source_timeout >= 0)
1942 if (context->timeout < 0)
1943 context->timeout = source_timeout;
1945 context->timeout = MIN (context->timeout, source_timeout);
1949 source = next_valid_source (context, source);
1952 UNLOCK_CONTEXT (context);
1955 *priority = current_priority;
1957 return (n_ready > 0);
1961 * g_main_context_query:
1962 * @context: a #GMainContext
1963 * @max_priority: maximum priority source to check
1964 * @timeout: location to store timeout to be used in polling
1965 * @fds: location to store #GPollFD records that need to be polled.
1966 * @n_fds: length of @fds.
1968 * Determines information necessary to poll this main loop.
1970 * Return value: the number of records actually stored in @fds,
1971 * or, if more than @n_fds records need to be stored, the number
1972 * of records that need to be stored.
1975 g_main_context_query (GMainContext *context,
1984 LOCK_CONTEXT (context);
1986 pollrec = context->poll_records;
1988 while (pollrec && max_priority >= pollrec->priority)
1990 if (pollrec->fd->events)
1994 fds[n_poll].fd = pollrec->fd->fd;
1995 /* In direct contradiction to the Unix98 spec, IRIX runs into
1996 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
1997 * flags in the events field of the pollfd while it should
1998 * just ignoring them. So we mask them out here.
2000 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2001 fds[n_poll].revents = 0;
2006 pollrec = pollrec->next;
2009 #ifdef G_THREADS_ENABLED
2010 context->poll_changed = FALSE;
2015 *timeout = context->timeout;
2017 context->time_is_current = FALSE;
2020 UNLOCK_CONTEXT (context);
2026 * g_main_context_check:
2027 * @context: a #GMainContext
2028 * @max_priority: the maximum numerical priority of sources to check
2029 * @fds: array of #GPollFD's that was passed to the last call to
2030 * g_main_context_query()
2031 * @n_fds: return value of g_main_context_query()
2033 * Pass the results of polling back to the main loop.
2035 * Return value: %TRUE if some sources are ready to be dispatched.
2038 g_main_context_check (GMainContext *context,
2048 LOCK_CONTEXT (context);
2050 if (context->in_check_or_prepare)
2052 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2053 "prepare() member.");
2054 UNLOCK_CONTEXT (context);
2058 #ifdef G_THREADS_ENABLED
2059 if (!context->poll_waiting)
2063 read (context->wake_up_pipe[0], &c, 1);
2067 context->poll_waiting = FALSE;
2069 /* If the set of poll file descriptors changed, bail out
2070 * and let the main loop rerun
2072 if (context->poll_changed)
2074 UNLOCK_CONTEXT (context);
2077 #endif /* G_THREADS_ENABLED */
2079 pollrec = context->poll_records;
2083 if (pollrec->fd->events)
2085 pollrec->fd->revents = fds[i].revents;
2088 pollrec = pollrec->next;
2091 source = next_valid_source (context, NULL);
2094 if ((n_ready > 0) && (source->priority > max_priority))
2096 SOURCE_UNREF (source, context);
2099 if ((source->flags & G_HOOK_FLAG_IN_CALL) && !(source->flags & G_SOURCE_CAN_RECURSE))
2102 if (!(source->flags & G_SOURCE_READY))
2105 gboolean (*check) (GSource *source);
2107 check = source->source_funcs->check;
2109 context->in_check_or_prepare++;
2110 UNLOCK_CONTEXT (context);
2112 result = (*check) (source);
2114 LOCK_CONTEXT (context);
2115 context->in_check_or_prepare--;
2118 source->flags |= G_SOURCE_READY;
2121 if (source->flags & G_SOURCE_READY)
2123 source->ref_count++;
2124 g_ptr_array_add (context->pending_dispatches, source);
2130 source = next_valid_source (context, source);
2133 UNLOCK_CONTEXT (context);
2139 * g_main_context_dispatch:
2140 * @context: a #GMainContext
2142 * Dispatch all pending sources()
2145 g_main_context_dispatch (GMainContext *context)
2147 LOCK_CONTEXT (context);
2149 if (context->pending_dispatches->len > 0)
2151 g_main_dispatch (context);
2154 UNLOCK_CONTEXT (context);
2157 /* HOLDS context lock */
2159 g_main_context_iterate (GMainContext *context,
2166 gboolean some_ready;
2167 gint nfds, allocated_nfds;
2168 GPollFD *fds = NULL;
2170 UNLOCK_CONTEXT (context);
2172 #ifdef G_THREADS_ENABLED
2173 if (!g_main_context_acquire (context))
2175 gboolean got_ownership;
2177 g_return_val_if_fail (g_thread_supported (), FALSE);
2182 LOCK_CONTEXT (context);
2185 context->cond = g_cond_new ();
2187 got_ownership = g_main_context_wait (context,
2189 g_static_mutex_get_mutex (&context->mutex));
2193 UNLOCK_CONTEXT (context);
2198 LOCK_CONTEXT (context);
2199 #endif /* G_THREADS_ENABLED */
2201 if (!context->cached_poll_array)
2203 context->cached_poll_array_size = context->n_poll_records;
2204 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2207 allocated_nfds = context->cached_poll_array_size;
2208 fds = context->cached_poll_array;
2210 UNLOCK_CONTEXT (context);
2212 some_ready = g_main_context_prepare (context, &max_priority);
2214 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
2215 allocated_nfds)) > allocated_nfds)
2217 LOCK_CONTEXT (context);
2219 context->cached_poll_array_size = allocated_nfds = nfds;
2220 context->cached_poll_array = fds = g_new (GPollFD, nfds);
2221 UNLOCK_CONTEXT (context);
2227 g_main_context_poll (context, timeout, max_priority, fds, nfds);
2229 g_main_context_check (context, max_priority, fds, nfds);
2232 g_main_context_dispatch (context);
2234 #ifdef G_THREADS_ENABLED
2235 g_main_context_release (context);
2236 #endif /* G_THREADS_ENABLED */
2238 LOCK_CONTEXT (context);
2244 * g_main_context_pending:
2245 * @context: a #GMainContext (if %NULL, the default context will be used)
2247 * Check if any sources have pending events for the given context.
2249 * Return value: %TRUE if events are pending.
2252 g_main_context_pending (GMainContext *context)
2257 context = g_main_context_default();
2259 LOCK_CONTEXT (context);
2260 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
2261 UNLOCK_CONTEXT (context);
2267 * g_main_context_iteration:
2268 * @context: a #GMainContext (if %NULL, the default context will be used)
2269 * @may_block: whether the call may block.
2271 * Run a single iteration for the given main loop. This involves
2272 * checking to see if any event sources are ready to be processed,
2273 * then if no events sources are ready and @may_block is %TRUE, waiting
2274 * for a source to become ready, then dispatching the highest priority
2275 * events sources that are ready. Note that even when @may_block is %TRUE,
2276 * it is still possible for g_main_context_iteration() to return
2277 * %FALSE, since the the wait may be interrupted for other
2278 * reasons than an event source becoming ready.
2280 * Return value: %TRUE if events were dispatched.
2283 g_main_context_iteration (GMainContext *context, gboolean may_block)
2288 context = g_main_context_default();
2290 LOCK_CONTEXT (context);
2291 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
2292 UNLOCK_CONTEXT (context);
2299 * @context: a #GMainContext (if %NULL, the default context will be used).
2300 * @is_running: set to TRUE to indicate that the loop is running. This
2301 * is not very important since calling g_main_run() will set this to
2304 * Create a new #GMainLoop structure
2309 g_main_loop_new (GMainContext *context,
2310 gboolean is_running)
2315 context = g_main_context_default();
2317 g_main_context_ref (context);
2319 loop = g_new0 (GMainLoop, 1);
2320 loop->context = context;
2321 loop->is_running = is_running != FALSE;
2322 loop->ref_count = 1;
2329 * @loop: a #GMainLoop
2331 * Increase the reference count on a #GMainLoop object by one.
2333 * Return value: @loop
2336 g_main_loop_ref (GMainLoop *loop)
2338 g_return_val_if_fail (loop != NULL, NULL);
2339 g_return_val_if_fail (loop->ref_count > 0, NULL);
2341 LOCK_CONTEXT (loop->context);
2343 UNLOCK_CONTEXT (loop->context);
2349 g_main_loop_unref_and_unlock (GMainLoop *loop)
2352 if (loop->ref_count == 0)
2354 /* When the ref_count is 0, there can be nobody else using the
2355 * loop, so it is safe to unlock before destroying.
2357 g_main_context_unref_and_unlock (loop->context);
2361 UNLOCK_CONTEXT (loop->context);
2365 * g_main_loop_unref:
2366 * @loop: a #GMainLoop
2368 * Decreases the reference count on a #GMainLoop object by one. If
2369 * the result is zero, free the loop and free all associated memory.
2372 g_main_loop_unref (GMainLoop *loop)
2374 g_return_if_fail (loop != NULL);
2375 g_return_if_fail (loop->ref_count > 0);
2377 LOCK_CONTEXT (loop->context);
2379 g_main_loop_unref_and_unlock (loop);
2384 * @loop: a #GMainLoop
2386 * Run a main loop until g_main_quit() is called on the loop.
2387 * If this is called for the thread of the loop's #GMainContext,
2388 * it will process events from the loop, otherwise it will
2392 g_main_loop_run (GMainLoop *loop)
2394 GThread *self = G_THREAD_SELF;
2396 g_return_if_fail (loop != NULL);
2397 g_return_if_fail (loop->ref_count > 0);
2399 #ifdef G_THREADS_ENABLED
2400 if (!g_main_context_acquire (loop->context))
2402 gboolean got_ownership = FALSE;
2404 /* Another thread owns this context */
2405 if (!g_thread_supported ())
2407 g_warning ("g_main_loop_run() was called from second thread but"
2408 "g_thread_init() was never called.");
2412 LOCK_CONTEXT (loop->context);
2416 if (!loop->is_running)
2417 loop->is_running = TRUE;
2419 if (!loop->context->cond)
2420 loop->context->cond = g_cond_new ();
2422 while (loop->is_running || !got_ownership)
2423 got_ownership = g_main_context_wait (loop->context,
2424 loop->context->cond,
2425 g_static_mutex_get_mutex (&loop->context->mutex));
2427 if (!loop->is_running)
2429 UNLOCK_CONTEXT (loop->context);
2431 g_main_context_release (loop->context);
2432 g_main_loop_unref (loop);
2436 g_assert (got_ownership);
2439 LOCK_CONTEXT (loop->context);
2440 #endif /* G_THREADS_ENABLED */
2442 if (loop->context->in_check_or_prepare)
2444 g_warning ("g_main_run(): called recursively from within a source's check() or "
2445 "prepare() member, iteration not possible.");
2450 loop->is_running = TRUE;
2451 while (loop->is_running)
2452 g_main_context_iterate (loop->context, TRUE, TRUE, self);
2454 #ifdef G_THREADS_ENABLED
2455 g_main_context_release (loop->context);
2456 #endif /* G_THREADS_ENABLED */
2458 g_main_loop_unref_and_unlock (loop);
2463 * @loop: a #GMainLoop
2465 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
2466 * for the loop will return.
2469 g_main_loop_quit (GMainLoop *loop)
2471 g_return_if_fail (loop != NULL);
2472 g_return_if_fail (loop->ref_count > 0);
2474 LOCK_CONTEXT (loop->context);
2475 loop->is_running = FALSE;
2476 g_main_context_wakeup_unlocked (loop->context);
2478 if (loop->context->cond)
2479 g_cond_broadcast (loop->context->cond);
2480 UNLOCK_CONTEXT (loop->context);
2484 * g_main_loop_is_running:
2485 * @loop: a #GMainLoop.
2487 * Check to see if the main loop is currently being run via g_main_run()
2489 * Return value: %TRUE if the mainloop is currently being run.
2492 g_main_loop_is_running (GMainLoop *loop)
2494 g_return_val_if_fail (loop != NULL, FALSE);
2495 g_return_val_if_fail (loop->ref_count > 0, FALSE);
2497 return loop->is_running;
2501 * g_main_loop_get_context:
2502 * @loop: a #GMainLoop.
2504 * Returns the #GMainContext of @loop.
2506 * Return value: the #GMainContext of @loop
2509 g_main_loop_get_context (GMainLoop *loop)
2511 g_return_val_if_fail (loop != NULL, NULL);
2512 g_return_val_if_fail (loop->ref_count > 0, NULL);
2514 return loop->context;
2517 /* HOLDS: context's lock */
2519 g_main_context_poll (GMainContext *context,
2525 #ifdef G_MAIN_POLL_DEBUG
2531 GPollFunc poll_func;
2533 if (n_fds || timeout != 0)
2535 #ifdef G_MAIN_POLL_DEBUG
2536 g_print ("g_main_poll(%d) timeout: %d\n", n_fds, timeout);
2537 poll_timer = g_timer_new ();
2540 LOCK_CONTEXT (context);
2542 poll_func = context->poll_func;
2544 UNLOCK_CONTEXT (context);
2545 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
2546 g_warning ("poll(2) failed due to: %s.",
2547 g_strerror (errno));
2549 #ifdef G_MAIN_POLL_DEBUG
2550 LOCK_CONTEXT (context);
2552 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
2555 g_timer_elapsed (poll_timer, NULL));
2556 g_timer_destroy (poll_timer);
2557 pollrec = context->poll_records;
2561 if (pollrec->fd->events)
2565 g_print (" [%d:", fds[i].fd);
2566 if (fds[i].revents & G_IO_IN)
2568 if (fds[i].revents & G_IO_OUT)
2570 if (fds[i].revents & G_IO_PRI)
2572 if (fds[i].revents & G_IO_ERR)
2574 if (fds[i].revents & G_IO_HUP)
2576 if (fds[i].revents & G_IO_NVAL)
2582 pollrec = pollrec->next;
2586 UNLOCK_CONTEXT (context);
2588 } /* if (n_fds || timeout != 0) */
2592 * g_main_context_add_poll:
2593 * @context: a #GMainContext (or %NULL for the default context)
2594 * @fd: a #GPollFD structure holding information about a file
2595 * descriptor to watch.
2596 * @priority: the priority for this file descriptor which should be
2597 * the same as the priority used for g_source_attach() to ensure that the
2598 * file descriptor is polled whenever the results may be needed.
2600 * Add a file descriptor to the set of file descriptors polled * for
2601 * this context. This will very seldom be used directly. Instead
2602 * a typical event source will use g_source_add_poll() instead.
2605 g_main_context_add_poll (GMainContext *context,
2610 context = g_main_context_default ();
2612 g_return_if_fail (context->ref_count > 0);
2613 g_return_if_fail (fd);
2615 LOCK_CONTEXT (context);
2616 g_main_context_add_poll_unlocked (context, priority, fd);
2617 UNLOCK_CONTEXT (context);
2620 /* HOLDS: main_loop_lock */
2622 g_main_context_add_poll_unlocked (GMainContext *context,
2626 GPollRec *lastrec, *pollrec, *newrec;
2628 if (!context->poll_chunk)
2629 context->poll_chunk = g_mem_chunk_create (GPollRec, 32, G_ALLOC_ONLY);
2631 if (context->poll_free_list)
2633 newrec = context->poll_free_list;
2634 context->poll_free_list = newrec->next;
2637 newrec = g_chunk_new (GPollRec, context->poll_chunk);
2639 /* This file descriptor may be checked before we ever poll */
2642 newrec->priority = priority;
2645 pollrec = context->poll_records;
2646 while (pollrec && priority >= pollrec->priority)
2649 pollrec = pollrec->next;
2653 lastrec->next = newrec;
2655 context->poll_records = newrec;
2657 newrec->next = pollrec;
2659 context->n_poll_records++;
2661 #ifdef G_THREADS_ENABLED
2662 context->poll_changed = TRUE;
2664 /* Now wake up the main loop if it is waiting in the poll() */
2665 g_main_context_wakeup_unlocked (context);
2670 * g_main_context_remove_poll:
2671 * @context:a #GMainContext
2672 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
2674 * Remove file descriptor from the set of file descriptors to be
2675 * polled for a particular context.
2678 g_main_context_remove_poll (GMainContext *context,
2682 context = g_main_context_default ();
2684 g_return_if_fail (context->ref_count > 0);
2685 g_return_if_fail (fd);
2687 LOCK_CONTEXT (context);
2688 g_main_context_remove_poll_unlocked (context, fd);
2689 UNLOCK_CONTEXT (context);
2693 g_main_context_remove_poll_unlocked (GMainContext *context,
2696 GPollRec *pollrec, *lastrec;
2699 pollrec = context->poll_records;
2703 if (pollrec->fd == fd)
2705 if (lastrec != NULL)
2706 lastrec->next = pollrec->next;
2708 context->poll_records = pollrec->next;
2710 #ifdef ENABLE_GC_FRIENDLY
2712 #endif /* ENABLE_GC_FRIENDLY */
2714 pollrec->next = context->poll_free_list;
2715 context->poll_free_list = pollrec;
2717 context->n_poll_records--;
2721 pollrec = pollrec->next;
2724 #ifdef G_THREADS_ENABLED
2725 context->poll_changed = TRUE;
2727 /* Now wake up the main loop if it is waiting in the poll() */
2728 g_main_context_wakeup_unlocked (context);
2733 * g_source_get_current_time:
2734 * @source: a #GSource
2735 * @timeval: #GTimeVal structure in which to store current time.
2737 * Gets the "current time" to be used when checking
2738 * this source. The advantage of calling this function over
2739 * calling g_get_current_time() directly is that when
2740 * checking multiple sources, GLib can cache a single value
2741 * instead of having to repeatedly get the system time.
2744 g_source_get_current_time (GSource *source,
2747 GMainContext *context;
2749 g_return_if_fail (source->context != NULL);
2751 context = source->context;
2753 LOCK_CONTEXT (context);
2755 if (!context->time_is_current)
2757 g_get_current_time (&context->current_time);
2758 context->time_is_current = TRUE;
2761 *timeval = context->current_time;
2763 UNLOCK_CONTEXT (context);
2767 * g_main_context_set_poll_func:
2768 * @context: a #GMainContext
2769 * @func: the function to call to poll all file descriptors
2771 * Sets the function to use to handle polling of file descriptors. It
2772 * will be used instead of the poll() system call (or GLib's
2773 * replacement function, which is used where poll() isn't available).
2775 * This function could possibly be used to integrate the GLib event
2776 * loop with an external event loop.
2779 g_main_context_set_poll_func (GMainContext *context,
2783 context = g_main_context_default ();
2785 g_return_if_fail (context->ref_count > 0);
2787 LOCK_CONTEXT (context);
2790 context->poll_func = func;
2794 context->poll_func = (GPollFunc) poll;
2796 context->poll_func = (GPollFunc) g_poll;
2800 UNLOCK_CONTEXT (context);
2804 * g_main_context_get_poll_func:
2805 * @context: a #GMainContext
2807 * Gets the poll function set by g_main_context_set_poll_func()
2809 * Return value: the poll function
2812 g_main_context_get_poll_func (GMainContext *context)
2817 context = g_main_context_default ();
2819 g_return_val_if_fail (context->ref_count > 0, NULL);
2821 LOCK_CONTEXT (context);
2822 result = context->poll_func;
2823 UNLOCK_CONTEXT (context);
2828 /* HOLDS: context's lock */
2829 /* Wake the main loop up from a poll() */
2831 g_main_context_wakeup_unlocked (GMainContext *context)
2833 #ifdef G_THREADS_ENABLED
2834 if (g_thread_supported() && context->poll_waiting)
2836 context->poll_waiting = FALSE;
2838 write (context->wake_up_pipe[1], "A", 1);
2840 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
2847 * g_main_context_wakeup:
2848 * @context: a #GMainContext
2850 * If @context is currently waiting in a poll(), interrupt
2851 * the poll(), and continue the iteration process.
2854 g_main_context_wakeup (GMainContext *context)
2857 context = g_main_context_default ();
2859 g_return_if_fail (context->ref_count > 0);
2861 LOCK_CONTEXT (context);
2862 g_main_context_wakeup_unlocked (context);
2863 UNLOCK_CONTEXT (context);
2869 g_timeout_set_expiration (GTimeoutSource *timeout_source,
2870 GTimeVal *current_time)
2872 guint seconds = timeout_source->interval / 1000;
2873 guint msecs = timeout_source->interval - seconds * 1000;
2875 timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
2876 timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
2877 if (timeout_source->expiration.tv_usec >= 1000000)
2879 timeout_source->expiration.tv_usec -= 1000000;
2880 timeout_source->expiration.tv_sec++;
2885 g_timeout_prepare (GSource *source,
2890 GTimeVal current_time;
2892 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2894 g_source_get_current_time (source, ¤t_time);
2896 sec = timeout_source->expiration.tv_sec - current_time.tv_sec;
2897 msec = (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000;
2899 /* We do the following in a rather convoluted fashion to deal with
2900 * the fact that we don't have an integral type big enough to hold
2901 * the difference of two timevals in millseconds.
2903 if (sec < 0 || (sec == 0 && msec < 0))
2907 glong interval_sec = timeout_source->interval / 1000;
2908 glong interval_msec = timeout_source->interval % 1000;
2916 if (sec > interval_sec ||
2917 (sec == interval_sec && msec > interval_msec))
2919 /* The system time has been set backwards, so we
2920 * reset the expiration time to now + timeout_source->interval;
2921 * this at least avoids hanging for long periods of time.
2923 g_timeout_set_expiration (timeout_source, ¤t_time);
2924 msec = timeout_source->interval;
2932 *timeout = (gint)msec;
2938 g_timeout_check (GSource *source)
2940 GTimeVal current_time;
2941 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2943 g_source_get_current_time (source, ¤t_time);
2945 return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
2946 ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
2947 (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
2951 g_timeout_dispatch (GSource *source,
2952 GSourceFunc callback,
2955 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2959 g_warning ("Timeout source dispatched without callback\n"
2960 "You must call g_source_set_callback().");
2964 if (callback (user_data))
2966 GTimeVal current_time;
2968 g_source_get_current_time (source, ¤t_time);
2969 g_timeout_set_expiration (timeout_source, ¤t_time);
2978 * g_timeout_source_new:
2979 * @interval: the timeout interval in milliseconds.
2981 * Create a new timeout source.
2983 * The source will not initially be associated with any #GMainContext
2984 * and must be added to one with g_source_attach() before it will be
2987 * Return value: the newly create timeout source
2990 g_timeout_source_new (guint interval)
2992 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
2993 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
2994 GTimeVal current_time;
2996 timeout_source->interval = interval;
2998 g_get_current_time (¤t_time);
2999 g_timeout_set_expiration (timeout_source, ¤t_time);
3005 * g_timeout_add_full:
3006 * @priority: the priority of the idle source. Typically this will be in the
3007 * range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3008 * @interval: the time between calls to the function, in milliseconds
3009 * (1/1000ths of a second.)
3010 * @function: function to call
3011 * @data: data to pass to @function
3012 * @notify: function to call when the idle is removed, or %NULL
3014 * Sets a function to be called at regular intervals, with the given
3015 * priority. The function is called repeatedly until it returns
3016 * FALSE, at which point the timeout is automatically destroyed and
3017 * the function will not be called again. The @notify function is
3018 * called when the timeout is destroyed. The first call to the
3019 * function will be at the end of the first @interval.
3021 * Note that timeout functions may be delayed, due to the processing of other
3022 * event sources. Thus they should not be relied on for precise timing.
3023 * After each call to the timeout function, the time of the next
3024 * timeout is recalculated based on the current time and the given interval
3025 * (it does not try to 'catch up' time lost in delays).
3027 * Return value: the id of event source.
3030 g_timeout_add_full (gint priority,
3032 GSourceFunc function,
3034 GDestroyNotify notify)
3039 g_return_val_if_fail (function != NULL, 0);
3041 source = g_timeout_source_new (interval);
3043 if (priority != G_PRIORITY_DEFAULT)
3044 g_source_set_priority (source, priority);
3046 g_source_set_callback (source, function, data, notify);
3047 id = g_source_attach (source, NULL);
3048 g_source_unref (source);
3055 * @interval: the time between calls to the function, in milliseconds
3056 * (1/1000ths of a second.)
3057 * @function: function to call
3058 * @data: data to pass to @function
3060 * Sets a function to be called at regular intervals, with the default
3061 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
3062 * until it returns FALSE, at which point the timeout is automatically
3063 * destroyed and the function will not be called again. The @notify
3064 * function is called when the timeout is destroyed. The first call
3065 * to the function will be at the end of the first @interval.
3067 * Note that timeout functions may be delayed, due to the processing of other
3068 * event sources. Thus they should not be relied on for precise timing.
3069 * After each call to the timeout function, the time of the next
3070 * timeout is recalculated based on the current time and the given interval
3071 * (it does not try to 'catch up' time lost in delays).
3073 * Return value: the id of event source.
3076 g_timeout_add (guint32 interval,
3077 GSourceFunc function,
3080 return g_timeout_add_full (G_PRIORITY_DEFAULT,
3081 interval, function, data, NULL);
3084 /* Idle functions */
3087 g_idle_prepare (GSource *source,
3096 g_idle_check (GSource *source)
3102 g_idle_dispatch (GSource *source,
3103 GSourceFunc callback,
3108 g_warning ("Idle source dispatched without callback\n"
3109 "You must call g_source_set_callback().");
3113 return callback (user_data);
3117 * g_idle_source_new:
3119 * Create a new idle source.
3121 * The source will not initially be associated with any #GMainContext
3122 * and must be added to one with g_source_attach() before it will be
3125 * Return value: the newly created idle source
3128 g_idle_source_new (void)
3130 return g_source_new (&g_idle_funcs, sizeof (GSource));
3135 * @priority: the priority of the idle source. Typically this will be in the
3136 * range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3137 * @function: function to call
3138 * @data: data to pass to @function
3139 * @notify: function to call when the idle is removed, or %NULL
3141 * Adds a function to be called whenever there are no higher priority
3142 * events pending. If the function returns FALSE it is automatically
3143 * removed from the list of event sources and will not be called again.
3145 * Return value: the id of the event source.
3148 g_idle_add_full (gint priority,
3149 GSourceFunc function,
3151 GDestroyNotify notify)
3156 g_return_val_if_fail (function != NULL, 0);
3158 source = g_idle_source_new ();
3160 if (priority != G_PRIORITY_DEFAULT)
3161 g_source_set_priority (source, priority);
3163 g_source_set_callback (source, function, data, notify);
3164 id = g_source_attach (source, NULL);
3165 g_source_unref (source);
3172 * @function: function to call
3173 * @data: data to pass to @function.
3175 * Adds a function to be called whenever there are no higher priority
3176 * events pending to the default main loop. The function is given the
3177 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
3178 * returns FALSE it is automatically removed from the list of event
3179 * sources and will not be called again.
3181 * Return value: the id of the event source.
3184 g_idle_add (GSourceFunc function,
3187 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
3191 * g_idle_remove_by_data:
3192 * @data: the data for the idle source's callback.
3194 * Removes the idle function with the given data.
3196 * Return value: %TRUE if an idle source was found and removed.
3199 g_idle_remove_by_data (gpointer data)
3201 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);