Remove redundant header inclusions
[glib.git] / glib / gmain.c
blobd87f820d7a22225514eb131c99b58fc46e21e796
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/.
30 /*
31 * MT safe
34 #include "config.h"
36 /* Uncomment the next line (and the corresponding line in gpoll.c) to
37 * enable debugging printouts if the environment variable
38 * G_MAIN_POLL_DEBUG is set to some value.
40 /* #define G_MAIN_POLL_DEBUG */
42 #ifdef _WIN32
43 /* Always enable debugging printout on Windows, as it is more often
44 * needed there...
46 #define G_MAIN_POLL_DEBUG
47 #endif
49 #define _GNU_SOURCE /* for pipe2 */
51 #include "glib.h"
52 #include "gthreadprivate.h"
53 #include <signal.h>
54 #include <sys/types.h>
55 #include <time.h>
56 #include <stdlib.h>
57 #ifdef HAVE_SYS_TIME_H
58 #include <sys/time.h>
59 #endif /* HAVE_SYS_TIME_H */
60 #ifdef HAVE_UNISTD_H
61 #include <unistd.h>
62 #endif /* HAVE_UNISTD_H */
63 #include <errno.h>
65 #ifdef G_OS_WIN32
66 #define STRICT
67 #include <windows.h>
68 #endif /* G_OS_WIN32 */
70 #ifdef G_OS_BEOS
71 #include <sys/socket.h>
72 #include <sys/wait.h>
73 #endif /* G_OS_BEOS */
75 #ifdef G_OS_UNIX
76 #include <fcntl.h>
77 #include <sys/wait.h>
78 #endif
81 /**
82 * SECTION:main
83 * @title: The Main Event Loop
84 * @short_description: manages all available sources of events
86 * The main event loop manages all the available sources of events for
87 * GLib and GTK+ applications. These events can come from any number of
88 * different types of sources such as file descriptors (plain files,
89 * pipes or sockets) and timeouts. New types of event sources can also
90 * be added using g_source_attach().
92 * To allow multiple independent sets of sources to be handled in
93 * different threads, each source is associated with a #GMainContext.
94 * A GMainContext can only be running in a single thread, but
95 * sources can be added to it and removed from it from other threads.
97 * Each event source is assigned a priority. The default priority,
98 * #G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
99 * Values greater than 0 denote lower priorities. Events from high priority
100 * sources are always processed before events from lower priority sources.
102 * Idle functions can also be added, and assigned a priority. These will
103 * be run whenever no events with a higher priority are ready to be processed.
105 * The #GMainLoop data type represents a main event loop. A GMainLoop is
106 * created with g_main_loop_new(). After adding the initial event sources,
107 * g_main_loop_run() is called. This continuously checks for new events from
108 * each of the event sources and dispatches them. Finally, the processing of
109 * an event from one of the sources leads to a call to g_main_loop_quit() to
110 * exit the main loop, and g_main_loop_run() returns.
112 * It is possible to create new instances of #GMainLoop recursively.
113 * This is often used in GTK+ applications when showing modal dialog
114 * boxes. Note that event sources are associated with a particular
115 * #GMainContext, and will be checked and dispatched for all main
116 * loops associated with that GMainContext.
118 * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
119 * gtk_main_quit() and gtk_events_pending().
121 * <refsect2><title>Creating new source types</title>
122 * <para>One of the unusual features of the #GMainLoop functionality
123 * is that new types of event source can be created and used in
124 * addition to the builtin type of event source. A new event source
125 * type is used for handling GDK events. A new source type is created
126 * by <firstterm>deriving</firstterm> from the #GSource structure.
127 * The derived type of source is represented by a structure that has
128 * the #GSource structure as a first element, and other elements specific
129 * to the new source type. To create an instance of the new source type,
130 * call g_source_new() passing in the size of the derived structure and
131 * a table of functions. These #GSourceFuncs determine the behavior of
132 * the new source type.</para>
133 * <para>New source types basically interact with the main context
134 * in two ways. Their prepare function in #GSourceFuncs can set a timeout
135 * to determine the maximum amount of time that the main loop will sleep
136 * before checking the source again. In addition, or as well, the source
137 * can add file descriptors to the set that the main context checks using
138 * g_source_add_poll().</para>
139 * </refsect2>
140 * <refsect2><title>Customizing the main loop iteration</title>
141 * <para>Single iterations of a #GMainContext can be run with
142 * g_main_context_iteration(). In some cases, more detailed control
143 * of exactly how the details of the main loop work is desired, for
144 * instance, when integrating the #GMainLoop with an external main loop.
145 * In such cases, you can call the component functions of
146 * g_main_context_iteration() directly. These functions are
147 * g_main_context_prepare(), g_main_context_query(),
148 * g_main_context_check() and g_main_context_dispatch().</para>
149 * <para>The operation of these functions can best be seen in terms
150 * of a state diagram, as shown in <xref linkend="mainloop-states"/>.</para>
151 * <figure id="mainloop-states"><title>States of a Main Context</title>
152 * <graphic fileref="mainloop-states.gif" format="GIF"></graphic>
153 * </figure>
154 * </refsect2>
157 /* Types */
159 typedef struct _GTimeoutSource GTimeoutSource;
160 typedef struct _GChildWatchSource GChildWatchSource;
161 typedef struct _GPollRec GPollRec;
162 typedef struct _GSourceCallback GSourceCallback;
164 typedef enum
166 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
167 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
168 } GSourceFlags;
170 #ifdef G_THREADS_ENABLED
171 typedef struct _GMainWaiter GMainWaiter;
173 struct _GMainWaiter
175 GCond *cond;
176 GMutex *mutex;
178 #endif
180 typedef struct _GMainDispatch GMainDispatch;
182 struct _GMainDispatch
184 gint depth;
185 GSList *dispatching_sources; /* stack of current sources */
188 #ifdef G_MAIN_POLL_DEBUG
189 gboolean _g_main_poll_debug = FALSE;
190 #endif
192 struct _GMainContext
194 #ifdef G_THREADS_ENABLED
195 /* The following lock is used for both the list of sources
196 * and the list of poll records
198 GStaticMutex mutex;
199 GCond *cond;
200 GThread *owner;
201 guint owner_count;
202 GSList *waiters;
203 #endif
205 gint ref_count;
207 GPtrArray *pending_dispatches;
208 gint timeout; /* Timeout for current iteration */
210 guint next_id;
211 GSource *source_list;
212 gint in_check_or_prepare;
214 GPollRec *poll_records;
215 guint n_poll_records;
216 GPollFD *cached_poll_array;
217 guint cached_poll_array_size;
219 #ifdef G_THREADS_ENABLED
220 #ifndef G_OS_WIN32
221 /* this pipe is used to wake up the main loop when a source is added.
223 gint wake_up_pipe[2];
224 #else /* G_OS_WIN32 */
225 HANDLE wake_up_semaphore;
226 #endif /* G_OS_WIN32 */
228 GPollFD wake_up_rec;
229 gboolean poll_waiting;
231 /* Flag indicating whether the set of fd's changed during a poll */
232 gboolean poll_changed;
233 #endif /* G_THREADS_ENABLED */
235 GPollFunc poll_func;
237 GTimeVal current_time;
238 gboolean time_is_current;
241 struct _GSourceCallback
243 guint ref_count;
244 GSourceFunc func;
245 gpointer data;
246 GDestroyNotify notify;
249 struct _GMainLoop
251 GMainContext *context;
252 gboolean is_running;
253 gint ref_count;
256 struct _GTimeoutSource
258 GSource source;
259 GTimeVal expiration;
260 guint interval;
261 guint granularity;
264 struct _GChildWatchSource
266 GSource source;
267 GPid pid;
268 gint child_status;
269 #ifdef G_OS_WIN32
270 GPollFD poll;
271 #else /* G_OS_WIN32 */
272 gint count;
273 gboolean child_exited;
274 #endif /* G_OS_WIN32 */
277 struct _GPollRec
279 GPollFD *fd;
280 GPollRec *next;
281 gint priority;
284 #ifdef G_THREADS_ENABLED
285 #define LOCK_CONTEXT(context) g_static_mutex_lock (&context->mutex)
286 #define UNLOCK_CONTEXT(context) g_static_mutex_unlock (&context->mutex)
287 #define G_THREAD_SELF g_thread_self ()
288 #else
289 #define LOCK_CONTEXT(context) (void)0
290 #define UNLOCK_CONTEXT(context) (void)0
291 #define G_THREAD_SELF NULL
292 #endif
294 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
295 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
296 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
298 #define SOURCE_UNREF(source, context) \
299 G_STMT_START { \
300 if ((source)->ref_count > 1) \
301 (source)->ref_count--; \
302 else \
303 g_source_unref_internal ((source), (context), TRUE); \
304 } G_STMT_END
307 /* Forward declarations */
309 static void g_source_unref_internal (GSource *source,
310 GMainContext *context,
311 gboolean have_lock);
312 static void g_source_destroy_internal (GSource *source,
313 GMainContext *context,
314 gboolean have_lock);
315 static void g_main_context_poll (GMainContext *context,
316 gint timeout,
317 gint priority,
318 GPollFD *fds,
319 gint n_fds);
320 static void g_main_context_add_poll_unlocked (GMainContext *context,
321 gint priority,
322 GPollFD *fd);
323 static void g_main_context_remove_poll_unlocked (GMainContext *context,
324 GPollFD *fd);
325 static void g_main_context_wakeup_unlocked (GMainContext *context);
327 static gboolean g_timeout_prepare (GSource *source,
328 gint *timeout);
329 static gboolean g_timeout_check (GSource *source);
330 static gboolean g_timeout_dispatch (GSource *source,
331 GSourceFunc callback,
332 gpointer user_data);
333 static gboolean g_child_watch_prepare (GSource *source,
334 gint *timeout);
335 static gboolean g_child_watch_check (GSource *source);
336 static gboolean g_child_watch_dispatch (GSource *source,
337 GSourceFunc callback,
338 gpointer user_data);
339 static gboolean g_idle_prepare (GSource *source,
340 gint *timeout);
341 static gboolean g_idle_check (GSource *source);
342 static gboolean g_idle_dispatch (GSource *source,
343 GSourceFunc callback,
344 gpointer user_data);
346 G_LOCK_DEFINE_STATIC (main_loop);
347 static GMainContext *default_main_context;
348 static GSList *main_contexts_without_pipe = NULL;
350 #ifndef G_OS_WIN32
351 /* Child status monitoring code */
352 enum {
353 CHILD_WATCH_UNINITIALIZED,
354 CHILD_WATCH_INITIALIZED_SINGLE,
355 CHILD_WATCH_INITIALIZED_THREADED
357 static gint child_watch_init_state = CHILD_WATCH_UNINITIALIZED;
358 static gint child_watch_count = 1;
359 static gint child_watch_wake_up_pipe[2] = {0, 0};
360 #endif /* !G_OS_WIN32 */
361 G_LOCK_DEFINE_STATIC (main_context_list);
362 static GSList *main_context_list = NULL;
364 static gint timer_perturb = -1;
366 GSourceFuncs g_timeout_funcs =
368 g_timeout_prepare,
369 g_timeout_check,
370 g_timeout_dispatch,
371 NULL
374 GSourceFuncs g_child_watch_funcs =
376 g_child_watch_prepare,
377 g_child_watch_check,
378 g_child_watch_dispatch,
379 NULL
382 GSourceFuncs g_idle_funcs =
384 g_idle_prepare,
385 g_idle_check,
386 g_idle_dispatch,
387 NULL
391 * g_main_context_ref:
392 * @context: a #GMainContext
394 * Increases the reference count on a #GMainContext object by one.
396 * Returns: the @context that was passed in (since 2.6)
398 GMainContext *
399 g_main_context_ref (GMainContext *context)
401 g_return_val_if_fail (context != NULL, NULL);
402 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
404 g_atomic_int_inc (&context->ref_count);
406 return context;
409 static inline void
410 poll_rec_list_free (GMainContext *context,
411 GPollRec *list)
413 g_slice_free_chain (GPollRec, list, next);
417 * g_main_context_unref:
418 * @context: a #GMainContext
420 * Decreases the reference count on a #GMainContext object by one. If
421 * the result is zero, free the context and free all associated memory.
423 void
424 g_main_context_unref (GMainContext *context)
426 GSource *source;
427 g_return_if_fail (context != NULL);
428 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
430 if (!g_atomic_int_dec_and_test (&context->ref_count))
431 return;
433 G_LOCK (main_context_list);
434 main_context_list = g_slist_remove (main_context_list, context);
435 G_UNLOCK (main_context_list);
437 source = context->source_list;
438 while (source)
440 GSource *next = source->next;
441 g_source_destroy_internal (source, context, FALSE);
442 source = next;
445 #ifdef G_THREADS_ENABLED
446 g_static_mutex_free (&context->mutex);
447 #endif
449 g_ptr_array_free (context->pending_dispatches, TRUE);
450 g_free (context->cached_poll_array);
452 poll_rec_list_free (context, context->poll_records);
454 #ifdef G_THREADS_ENABLED
455 if (g_thread_supported())
457 #ifndef G_OS_WIN32
458 close (context->wake_up_pipe[0]);
459 close (context->wake_up_pipe[1]);
460 #else
461 CloseHandle (context->wake_up_semaphore);
462 #endif
464 else
465 main_contexts_without_pipe = g_slist_remove (main_contexts_without_pipe,
466 context);
468 if (context->cond != NULL)
469 g_cond_free (context->cond);
470 #endif
472 g_free (context);
475 #ifdef G_THREADS_ENABLED
476 static void
477 g_main_context_init_pipe (GMainContext *context)
479 # ifndef G_OS_WIN32
480 if (context->wake_up_pipe[0] != -1)
481 return;
483 #ifdef HAVE_PIPE2
484 /* if this fails, we fall through and try pipe */
485 pipe2 (context->wake_up_pipe, O_CLOEXEC);
486 #endif
487 if (context->wake_up_pipe[0] == -1)
489 if (pipe (context->wake_up_pipe) < 0)
490 g_error ("Cannot create pipe main loop wake-up: %s\n",
491 g_strerror (errno));
493 fcntl (context->wake_up_pipe[0], F_SETFD, FD_CLOEXEC);
494 fcntl (context->wake_up_pipe[1], F_SETFD, FD_CLOEXEC);
497 context->wake_up_rec.fd = context->wake_up_pipe[0];
498 context->wake_up_rec.events = G_IO_IN;
499 # else
500 if (context->wake_up_semaphore != NULL)
501 return;
502 context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
503 if (context->wake_up_semaphore == NULL)
504 g_error ("Cannot create wake-up semaphore: %s",
505 g_win32_error_message (GetLastError ()));
506 context->wake_up_rec.fd = (gintptr) context->wake_up_semaphore;
507 context->wake_up_rec.events = G_IO_IN;
509 if (_g_main_poll_debug)
510 g_print ("wake-up semaphore: %p\n", context->wake_up_semaphore);
511 # endif
512 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
515 void
516 _g_main_thread_init (void)
518 GSList *curr = main_contexts_without_pipe;
519 while (curr)
521 g_main_context_init_pipe ((GMainContext *)curr->data);
522 curr = curr->next;
524 g_slist_free (main_contexts_without_pipe);
525 main_contexts_without_pipe = NULL;
527 #endif /* G_THREADS_ENABLED */
530 * g_main_context_new:
532 * Creates a new #GMainContext structure.
534 * Return value: the new #GMainContext
536 GMainContext *
537 g_main_context_new (void)
539 GMainContext *context = g_new0 (GMainContext, 1);
541 #ifdef G_MAIN_POLL_DEBUG
543 static gboolean beenhere = FALSE;
545 if (!beenhere)
547 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
548 _g_main_poll_debug = TRUE;
549 beenhere = TRUE;
552 #endif
554 #ifdef G_THREADS_ENABLED
555 g_static_mutex_init (&context->mutex);
557 context->owner = NULL;
558 context->waiters = NULL;
560 # ifndef G_OS_WIN32
561 context->wake_up_pipe[0] = -1;
562 context->wake_up_pipe[1] = -1;
563 # else
564 context->wake_up_semaphore = NULL;
565 # endif
566 #endif
568 context->ref_count = 1;
570 context->next_id = 1;
572 context->source_list = NULL;
574 context->poll_func = g_poll;
576 context->cached_poll_array = NULL;
577 context->cached_poll_array_size = 0;
579 context->pending_dispatches = g_ptr_array_new ();
581 context->time_is_current = FALSE;
583 #ifdef G_THREADS_ENABLED
584 if (g_thread_supported ())
585 g_main_context_init_pipe (context);
586 else
587 main_contexts_without_pipe = g_slist_prepend (main_contexts_without_pipe,
588 context);
589 #endif
591 G_LOCK (main_context_list);
592 main_context_list = g_slist_append (main_context_list, context);
594 #ifdef G_MAIN_POLL_DEBUG
595 if (_g_main_poll_debug)
596 g_print ("created context=%p\n", context);
597 #endif
599 G_UNLOCK (main_context_list);
601 return context;
605 * g_main_context_default:
607 * Returns the global default main context. This is the main context
608 * used for main loop functions when a main loop is not explicitly
609 * specified, and corresponds to the "main" main loop. See also
610 * g_main_context_get_thread_default().
612 * Return value: the global default main context.
614 GMainContext *
615 g_main_context_default (void)
617 /* Slow, but safe */
619 G_LOCK (main_loop);
621 if (!default_main_context)
623 default_main_context = g_main_context_new ();
624 #ifdef G_MAIN_POLL_DEBUG
625 if (_g_main_poll_debug)
626 g_print ("default context=%p\n", default_main_context);
627 #endif
630 G_UNLOCK (main_loop);
632 return default_main_context;
635 static GStaticPrivate thread_context_stack = G_STATIC_PRIVATE_INIT;
637 static void
638 free_context_stack (gpointer data)
640 GQueue *stack = data;
641 GMainContext *context;
643 while (!g_queue_is_empty (stack))
645 context = g_queue_pop_head (stack);
646 g_main_context_release (context);
647 if (context)
648 g_main_context_unref (context);
650 g_queue_free (stack);
654 * g_main_context_push_thread_default:
655 * @context: a #GMainContext, or %NULL for the global default context
657 * Acquires @context and sets it as the thread-default context for the
658 * current thread. This will cause certain asynchronous operations
659 * (such as most <link linkend="gio">gio</link>-based I/O) which are
660 * started in this thread to run under @context and deliver their
661 * results to its main loop, rather than running under the global
662 * default context in the main thread. Note that calling this function
663 * changes the context returned by
664 * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
665 * one returned by g_main_context_default(), so it does not affect the
666 * context used by functions like g_idle_add().
668 * Normally you would call this function shortly after creating a new
669 * thread, passing it a #GMainContext which will be run by a
670 * #GMainLoop in that thread, to set a new default context for all
671 * async operations in that thread. (In this case, you don't need to
672 * ever call g_main_context_pop_thread_default().) In some cases
673 * however, you may want to schedule a single operation in a
674 * non-default context, or temporarily use a non-default context in
675 * the main thread. In that case, you can wrap the call to the
676 * asynchronous operation inside a
677 * g_main_context_push_thread_default() /
678 * g_main_context_pop_thread_default() pair, but it is up to you to
679 * ensure that no other asynchronous operations accidentally get
680 * started while the non-default context is active.
682 * Beware that libraries that predate this function may not correctly
683 * handle being used from a thread with a thread-default context. Eg,
684 * see g_file_supports_thread_contexts().
686 * Since: 2.22
688 void
689 g_main_context_push_thread_default (GMainContext *context)
691 GQueue *stack;
692 gboolean acquired_context;
694 acquired_context = g_main_context_acquire (context);
695 g_return_if_fail (acquired_context);
697 if (context == g_main_context_default ())
698 context = NULL;
699 else if (context)
700 g_main_context_ref (context);
702 stack = g_static_private_get (&thread_context_stack);
703 if (!stack)
705 stack = g_queue_new ();
706 g_static_private_set (&thread_context_stack, stack,
707 free_context_stack);
710 g_queue_push_head (stack, context);
714 * g_main_context_pop_thread_default:
715 * @context: a #GMainContext object, or %NULL
717 * Pops @context off the thread-default context stack (verifying that
718 * it was on the top of the stack).
720 * Since: 2.22
722 void
723 g_main_context_pop_thread_default (GMainContext *context)
725 GQueue *stack;
727 if (context == g_main_context_default ())
728 context = NULL;
730 stack = g_static_private_get (&thread_context_stack);
732 g_return_if_fail (stack != NULL);
733 g_return_if_fail (g_queue_peek_head (stack) == context);
735 g_queue_pop_head (stack);
737 g_main_context_release (context);
738 if (context)
739 g_main_context_unref (context);
743 * g_main_context_get_thread_default:
745 * Gets the thread-default #GMainContext for this thread. Asynchronous
746 * operations that want to be able to be run in contexts other than
747 * the default one should call this method to get a #GMainContext to
748 * add their #GSource<!-- -->s to. (Note that even in single-threaded
749 * programs applications may sometimes want to temporarily push a
750 * non-default context, so it is not safe to assume that this will
751 * always return %NULL if threads are not initialized.)
753 * Returns: the thread-default #GMainContext, or %NULL if the
754 * thread-default context is the global default context.
756 * Since: 2.22
758 GMainContext *
759 g_main_context_get_thread_default (void)
761 GQueue *stack;
763 stack = g_static_private_get (&thread_context_stack);
764 if (stack)
765 return g_queue_peek_head (stack);
766 else
767 return NULL;
770 /* Hooks for adding to the main loop */
773 * g_source_new:
774 * @source_funcs: structure containing functions that implement
775 * the sources behavior.
776 * @struct_size: size of the #GSource structure to create.
778 * Creates a new #GSource structure. The size is specified to
779 * allow creating structures derived from #GSource that contain
780 * additional data. The size passed in must be at least
781 * <literal>sizeof (GSource)</literal>.
783 * The source will not initially be associated with any #GMainContext
784 * and must be added to one with g_source_attach() before it will be
785 * executed.
787 * Return value: the newly-created #GSource.
789 GSource *
790 g_source_new (GSourceFuncs *source_funcs,
791 guint struct_size)
793 GSource *source;
795 g_return_val_if_fail (source_funcs != NULL, NULL);
796 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
798 source = (GSource*) g_malloc0 (struct_size);
800 source->source_funcs = source_funcs;
801 source->ref_count = 1;
803 source->priority = G_PRIORITY_DEFAULT;
805 source->flags = G_HOOK_FLAG_ACTIVE;
807 /* NULL/0 initialization for all other fields */
809 return source;
812 /* Holds context's lock
814 static void
815 g_source_list_add (GSource *source,
816 GMainContext *context)
818 GSource *tmp_source, *last_source;
820 last_source = NULL;
821 tmp_source = context->source_list;
822 while (tmp_source && tmp_source->priority <= source->priority)
824 last_source = tmp_source;
825 tmp_source = tmp_source->next;
828 source->next = tmp_source;
829 if (tmp_source)
830 tmp_source->prev = source;
832 source->prev = last_source;
833 if (last_source)
834 last_source->next = source;
835 else
836 context->source_list = source;
839 /* Holds context's lock
841 static void
842 g_source_list_remove (GSource *source,
843 GMainContext *context)
845 if (source->prev)
846 source->prev->next = source->next;
847 else
848 context->source_list = source->next;
850 if (source->next)
851 source->next->prev = source->prev;
853 source->prev = NULL;
854 source->next = NULL;
858 * g_source_attach:
859 * @source: a #GSource
860 * @context: a #GMainContext (if %NULL, the default context will be used)
862 * Adds a #GSource to a @context so that it will be executed within
863 * that context. Remove it by calling g_source_destroy().
865 * Return value: the ID (greater than 0) for the source within the
866 * #GMainContext.
868 guint
869 g_source_attach (GSource *source,
870 GMainContext *context)
872 guint result = 0;
873 GSList *tmp_list;
875 g_return_val_if_fail (source->context == NULL, 0);
876 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
878 if (!context)
879 context = g_main_context_default ();
881 LOCK_CONTEXT (context);
883 source->context = context;
884 result = source->source_id = context->next_id++;
886 source->ref_count++;
887 g_source_list_add (source, context);
889 tmp_list = source->poll_fds;
890 while (tmp_list)
892 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
893 tmp_list = tmp_list->next;
896 #ifdef G_THREADS_ENABLED
897 /* Now wake up the main loop if it is waiting in the poll() */
898 g_main_context_wakeup_unlocked (context);
899 #endif
901 UNLOCK_CONTEXT (context);
903 return result;
906 static void
907 g_source_destroy_internal (GSource *source,
908 GMainContext *context,
909 gboolean have_lock)
911 if (!have_lock)
912 LOCK_CONTEXT (context);
914 if (!SOURCE_DESTROYED (source))
916 GSList *tmp_list;
917 gpointer old_cb_data;
918 GSourceCallbackFuncs *old_cb_funcs;
920 source->flags &= ~G_HOOK_FLAG_ACTIVE;
922 old_cb_data = source->callback_data;
923 old_cb_funcs = source->callback_funcs;
925 source->callback_data = NULL;
926 source->callback_funcs = NULL;
928 if (old_cb_funcs)
930 UNLOCK_CONTEXT (context);
931 old_cb_funcs->unref (old_cb_data);
932 LOCK_CONTEXT (context);
935 if (!SOURCE_BLOCKED (source))
937 tmp_list = source->poll_fds;
938 while (tmp_list)
940 g_main_context_remove_poll_unlocked (context, tmp_list->data);
941 tmp_list = tmp_list->next;
945 g_source_unref_internal (source, context, TRUE);
948 if (!have_lock)
949 UNLOCK_CONTEXT (context);
953 * g_source_destroy:
954 * @source: a #GSource
956 * Removes a source from its #GMainContext, if any, and mark it as
957 * destroyed. The source cannot be subsequently added to another
958 * context.
960 void
961 g_source_destroy (GSource *source)
963 GMainContext *context;
965 g_return_if_fail (source != NULL);
967 context = source->context;
969 if (context)
970 g_source_destroy_internal (source, context, FALSE);
971 else
972 source->flags &= ~G_HOOK_FLAG_ACTIVE;
976 * g_source_get_id:
977 * @source: a #GSource
979 * Returns the numeric ID for a particular source. The ID of a source
980 * is a positive integer which is unique within a particular main loop
981 * context. The reverse
982 * mapping from ID to source is done by g_main_context_find_source_by_id().
984 * Return value: the ID (greater than 0) for the source
986 guint
987 g_source_get_id (GSource *source)
989 guint result;
991 g_return_val_if_fail (source != NULL, 0);
992 g_return_val_if_fail (source->context != NULL, 0);
994 LOCK_CONTEXT (source->context);
995 result = source->source_id;
996 UNLOCK_CONTEXT (source->context);
998 return result;
1002 * g_source_get_context:
1003 * @source: a #GSource
1005 * Gets the #GMainContext with which the source is associated.
1006 * Calling this function on a destroyed source is an error.
1008 * Return value: the #GMainContext with which the source is associated,
1009 * or %NULL if the context has not yet been added
1010 * to a source.
1012 GMainContext *
1013 g_source_get_context (GSource *source)
1015 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1017 return source->context;
1021 * g_source_add_poll:
1022 * @source:a #GSource
1023 * @fd: a #GPollFD structure holding information about a file
1024 * descriptor to watch.
1026 * Adds a file descriptor to the set of file descriptors polled for
1027 * this source. This is usually combined with g_source_new() to add an
1028 * event source. The event source's check function will typically test
1029 * the @revents field in the #GPollFD struct and return %TRUE if events need
1030 * to be processed.
1032 void
1033 g_source_add_poll (GSource *source,
1034 GPollFD *fd)
1036 GMainContext *context;
1038 g_return_if_fail (source != NULL);
1039 g_return_if_fail (fd != NULL);
1040 g_return_if_fail (!SOURCE_DESTROYED (source));
1042 context = source->context;
1044 if (context)
1045 LOCK_CONTEXT (context);
1047 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1049 if (context)
1051 if (!SOURCE_BLOCKED (source))
1052 g_main_context_add_poll_unlocked (context, source->priority, fd);
1053 UNLOCK_CONTEXT (context);
1058 * g_source_remove_poll:
1059 * @source:a #GSource
1060 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1062 * Removes a file descriptor from the set of file descriptors polled for
1063 * this source.
1065 void
1066 g_source_remove_poll (GSource *source,
1067 GPollFD *fd)
1069 GMainContext *context;
1071 g_return_if_fail (source != NULL);
1072 g_return_if_fail (fd != NULL);
1073 g_return_if_fail (!SOURCE_DESTROYED (source));
1075 context = source->context;
1077 if (context)
1078 LOCK_CONTEXT (context);
1080 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1082 if (context)
1084 if (!SOURCE_BLOCKED (source))
1085 g_main_context_remove_poll_unlocked (context, fd);
1086 UNLOCK_CONTEXT (context);
1091 * g_source_set_callback_indirect:
1092 * @source: the source
1093 * @callback_data: pointer to callback data "object"
1094 * @callback_funcs: functions for reference counting @callback_data
1095 * and getting the callback and data
1097 * Sets the callback function storing the data as a refcounted callback
1098 * "object". This is used internally. Note that calling
1099 * g_source_set_callback_indirect() assumes
1100 * an initial reference count on @callback_data, and thus
1101 * @callback_funcs->unref will eventually be called once more
1102 * than @callback_funcs->ref.
1104 void
1105 g_source_set_callback_indirect (GSource *source,
1106 gpointer callback_data,
1107 GSourceCallbackFuncs *callback_funcs)
1109 GMainContext *context;
1110 gpointer old_cb_data;
1111 GSourceCallbackFuncs *old_cb_funcs;
1113 g_return_if_fail (source != NULL);
1114 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1116 context = source->context;
1118 if (context)
1119 LOCK_CONTEXT (context);
1121 old_cb_data = source->callback_data;
1122 old_cb_funcs = source->callback_funcs;
1124 source->callback_data = callback_data;
1125 source->callback_funcs = callback_funcs;
1127 if (context)
1128 UNLOCK_CONTEXT (context);
1130 if (old_cb_funcs)
1131 old_cb_funcs->unref (old_cb_data);
1134 static void
1135 g_source_callback_ref (gpointer cb_data)
1137 GSourceCallback *callback = cb_data;
1139 callback->ref_count++;
1143 static void
1144 g_source_callback_unref (gpointer cb_data)
1146 GSourceCallback *callback = cb_data;
1148 callback->ref_count--;
1149 if (callback->ref_count == 0)
1151 if (callback->notify)
1152 callback->notify (callback->data);
1153 g_free (callback);
1157 static void
1158 g_source_callback_get (gpointer cb_data,
1159 GSource *source,
1160 GSourceFunc *func,
1161 gpointer *data)
1163 GSourceCallback *callback = cb_data;
1165 *func = callback->func;
1166 *data = callback->data;
1169 static GSourceCallbackFuncs g_source_callback_funcs = {
1170 g_source_callback_ref,
1171 g_source_callback_unref,
1172 g_source_callback_get,
1176 * g_source_set_callback:
1177 * @source: the source
1178 * @func: a callback function
1179 * @data: the data to pass to callback function
1180 * @notify: a function to call when @data is no longer in use, or %NULL.
1182 * Sets the callback function for a source. The callback for a source is
1183 * called from the source's dispatch function.
1185 * The exact type of @func depends on the type of source; ie. you
1186 * should not count on @func being called with @data as its first
1187 * parameter.
1189 * Typically, you won't use this function. Instead use functions specific
1190 * to the type of source you are using.
1192 void
1193 g_source_set_callback (GSource *source,
1194 GSourceFunc func,
1195 gpointer data,
1196 GDestroyNotify notify)
1198 GSourceCallback *new_callback;
1200 g_return_if_fail (source != NULL);
1202 new_callback = g_new (GSourceCallback, 1);
1204 new_callback->ref_count = 1;
1205 new_callback->func = func;
1206 new_callback->data = data;
1207 new_callback->notify = notify;
1209 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1214 * g_source_set_funcs:
1215 * @source: a #GSource
1216 * @funcs: the new #GSourceFuncs
1218 * Sets the source functions (can be used to override
1219 * default implementations) of an unattached source.
1221 * Since: 2.12
1223 void
1224 g_source_set_funcs (GSource *source,
1225 GSourceFuncs *funcs)
1227 g_return_if_fail (source != NULL);
1228 g_return_if_fail (source->context == NULL);
1229 g_return_if_fail (source->ref_count > 0);
1230 g_return_if_fail (funcs != NULL);
1232 source->source_funcs = funcs;
1236 * g_source_set_priority:
1237 * @source: a #GSource
1238 * @priority: the new priority.
1240 * Sets the priority of a source. While the main loop is being
1241 * run, a source will be dispatched if it is ready to be dispatched and no sources
1242 * at a higher (numerically smaller) priority are ready to be dispatched.
1244 void
1245 g_source_set_priority (GSource *source,
1246 gint priority)
1248 GSList *tmp_list;
1249 GMainContext *context;
1251 g_return_if_fail (source != NULL);
1253 context = source->context;
1255 if (context)
1256 LOCK_CONTEXT (context);
1258 source->priority = priority;
1260 if (context)
1262 /* Remove the source from the context's source and then
1263 * add it back so it is sorted in the correct plcae
1265 g_source_list_remove (source, source->context);
1266 g_source_list_add (source, source->context);
1268 if (!SOURCE_BLOCKED (source))
1270 tmp_list = source->poll_fds;
1271 while (tmp_list)
1273 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1274 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1276 tmp_list = tmp_list->next;
1280 UNLOCK_CONTEXT (source->context);
1285 * g_source_get_priority:
1286 * @source: a #GSource
1288 * Gets the priority of a source.
1290 * Return value: the priority of the source
1292 gint
1293 g_source_get_priority (GSource *source)
1295 g_return_val_if_fail (source != NULL, 0);
1297 return source->priority;
1301 * g_source_set_can_recurse:
1302 * @source: a #GSource
1303 * @can_recurse: whether recursion is allowed for this source
1305 * Sets whether a source can be called recursively. If @can_recurse is
1306 * %TRUE, then while the source is being dispatched then this source
1307 * will be processed normally. Otherwise, all processing of this
1308 * source is blocked until the dispatch function returns.
1310 void
1311 g_source_set_can_recurse (GSource *source,
1312 gboolean can_recurse)
1314 GMainContext *context;
1316 g_return_if_fail (source != NULL);
1318 context = source->context;
1320 if (context)
1321 LOCK_CONTEXT (context);
1323 if (can_recurse)
1324 source->flags |= G_SOURCE_CAN_RECURSE;
1325 else
1326 source->flags &= ~G_SOURCE_CAN_RECURSE;
1328 if (context)
1329 UNLOCK_CONTEXT (context);
1333 * g_source_get_can_recurse:
1334 * @source: a #GSource
1336 * Checks whether a source is allowed to be called recursively.
1337 * see g_source_set_can_recurse().
1339 * Return value: whether recursion is allowed.
1341 gboolean
1342 g_source_get_can_recurse (GSource *source)
1344 g_return_val_if_fail (source != NULL, FALSE);
1346 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1351 * g_source_set_name:
1352 * @source: a #GSource
1353 * @name: debug name for the source
1355 * Sets a name for the source, used in debugging and profiling.
1356 * The name defaults to #NULL.
1358 * The source name should describe in a human-readable way
1359 * what the source does. For example, "X11 event queue"
1360 * or "GTK+ repaint idle handler" or whatever it is.
1362 * It is permitted to call this function multiple times, but is not
1363 * recommended due to the potential performance impact. For example,
1364 * one could change the name in the "check" function of a #GSourceFuncs
1365 * to include details like the event type in the source name.
1367 * Since: 2.26
1369 void
1370 g_source_set_name (GSource *source,
1371 const char *name)
1373 g_return_if_fail (source != NULL);
1375 /* setting back to NULL is allowed, just because it's
1376 * weird if get_name can return NULL but you can't
1377 * set that.
1380 g_free (source->name);
1381 source->name = g_strdup (name);
1385 * g_source_get_name:
1386 * @source: a #GSource
1388 * Gets a name for the source, used in debugging and profiling.
1389 * The name may be #NULL if it has never been set with
1390 * g_source_set_name().
1392 * Return value: the name of the source
1393 * Since: 2.26
1395 G_CONST_RETURN char*
1396 g_source_get_name (GSource *source)
1398 g_return_val_if_fail (source != NULL, NULL);
1400 return source->name;
1404 * g_source_set_name_by_id:
1405 * @tag: a #GSource ID
1406 * @name: debug name for the source
1408 * Sets the name of a source using its ID.
1410 * This is a convenience utility to set source names from the return
1411 * value of g_idle_add(), g_timeout_add(), etc.
1413 * Since: 2.26
1415 void
1416 g_source_set_name_by_id (guint tag,
1417 const char *name)
1419 GSource *source;
1421 g_return_if_fail (tag > 0);
1423 source = g_main_context_find_source_by_id (NULL, tag);
1424 if (source == NULL)
1425 return;
1427 g_source_set_name (source, name);
1432 * g_source_ref:
1433 * @source: a #GSource
1435 * Increases the reference count on a source by one.
1437 * Return value: @source
1439 GSource *
1440 g_source_ref (GSource *source)
1442 GMainContext *context;
1444 g_return_val_if_fail (source != NULL, NULL);
1446 context = source->context;
1448 if (context)
1449 LOCK_CONTEXT (context);
1451 source->ref_count++;
1453 if (context)
1454 UNLOCK_CONTEXT (context);
1456 return source;
1459 /* g_source_unref() but possible to call within context lock
1461 static void
1462 g_source_unref_internal (GSource *source,
1463 GMainContext *context,
1464 gboolean have_lock)
1466 gpointer old_cb_data = NULL;
1467 GSourceCallbackFuncs *old_cb_funcs = NULL;
1469 g_return_if_fail (source != NULL);
1471 if (!have_lock && context)
1472 LOCK_CONTEXT (context);
1474 source->ref_count--;
1475 if (source->ref_count == 0)
1477 old_cb_data = source->callback_data;
1478 old_cb_funcs = source->callback_funcs;
1480 source->callback_data = NULL;
1481 source->callback_funcs = NULL;
1483 if (context && !SOURCE_DESTROYED (source))
1485 g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1486 source->ref_count++;
1488 else if (context)
1489 g_source_list_remove (source, context);
1491 if (source->source_funcs->finalize)
1492 source->source_funcs->finalize (source);
1494 g_free (source->name);
1495 source->name = NULL;
1497 g_slist_free (source->poll_fds);
1498 source->poll_fds = NULL;
1499 g_free (source);
1502 if (!have_lock && context)
1503 UNLOCK_CONTEXT (context);
1505 if (old_cb_funcs)
1507 if (have_lock)
1508 UNLOCK_CONTEXT (context);
1510 old_cb_funcs->unref (old_cb_data);
1512 if (have_lock)
1513 LOCK_CONTEXT (context);
1518 * g_source_unref:
1519 * @source: a #GSource
1521 * Decreases the reference count of a source by one. If the
1522 * resulting reference count is zero the source and associated
1523 * memory will be destroyed.
1525 void
1526 g_source_unref (GSource *source)
1528 g_return_if_fail (source != NULL);
1530 g_source_unref_internal (source, source->context, FALSE);
1534 * g_main_context_find_source_by_id:
1535 * @context: a #GMainContext (if %NULL, the default context will be used)
1536 * @source_id: the source ID, as returned by g_source_get_id().
1538 * Finds a #GSource given a pair of context and ID.
1540 * Return value: the #GSource if found, otherwise, %NULL
1542 GSource *
1543 g_main_context_find_source_by_id (GMainContext *context,
1544 guint source_id)
1546 GSource *source;
1548 g_return_val_if_fail (source_id > 0, NULL);
1550 if (context == NULL)
1551 context = g_main_context_default ();
1553 LOCK_CONTEXT (context);
1555 source = context->source_list;
1556 while (source)
1558 if (!SOURCE_DESTROYED (source) &&
1559 source->source_id == source_id)
1560 break;
1561 source = source->next;
1564 UNLOCK_CONTEXT (context);
1566 return source;
1570 * g_main_context_find_source_by_funcs_user_data:
1571 * @context: a #GMainContext (if %NULL, the default context will be used).
1572 * @funcs: the @source_funcs passed to g_source_new().
1573 * @user_data: the user data from the callback.
1575 * Finds a source with the given source functions and user data. If
1576 * multiple sources exist with the same source function and user data,
1577 * the first one found will be returned.
1579 * Return value: the source, if one was found, otherwise %NULL
1581 GSource *
1582 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1583 GSourceFuncs *funcs,
1584 gpointer user_data)
1586 GSource *source;
1588 g_return_val_if_fail (funcs != NULL, NULL);
1590 if (context == NULL)
1591 context = g_main_context_default ();
1593 LOCK_CONTEXT (context);
1595 source = context->source_list;
1596 while (source)
1598 if (!SOURCE_DESTROYED (source) &&
1599 source->source_funcs == funcs &&
1600 source->callback_funcs)
1602 GSourceFunc callback;
1603 gpointer callback_data;
1605 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1607 if (callback_data == user_data)
1608 break;
1610 source = source->next;
1613 UNLOCK_CONTEXT (context);
1615 return source;
1619 * g_main_context_find_source_by_user_data:
1620 * @context: a #GMainContext
1621 * @user_data: the user_data for the callback.
1623 * Finds a source with the given user data for the callback. If
1624 * multiple sources exist with the same user data, the first
1625 * one found will be returned.
1627 * Return value: the source, if one was found, otherwise %NULL
1629 GSource *
1630 g_main_context_find_source_by_user_data (GMainContext *context,
1631 gpointer user_data)
1633 GSource *source;
1635 if (context == NULL)
1636 context = g_main_context_default ();
1638 LOCK_CONTEXT (context);
1640 source = context->source_list;
1641 while (source)
1643 if (!SOURCE_DESTROYED (source) &&
1644 source->callback_funcs)
1646 GSourceFunc callback;
1647 gpointer callback_data = NULL;
1649 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1651 if (callback_data == user_data)
1652 break;
1654 source = source->next;
1657 UNLOCK_CONTEXT (context);
1659 return source;
1663 * g_source_remove:
1664 * @tag: the ID of the source to remove.
1666 * Removes the source with the given id from the default main context.
1667 * The id of
1668 * a #GSource is given by g_source_get_id(), or will be returned by the
1669 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1670 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1671 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1673 * See also g_source_destroy(). You must use g_source_destroy() for sources
1674 * added to a non-default main context.
1676 * Return value: %TRUE if the source was found and removed.
1678 gboolean
1679 g_source_remove (guint tag)
1681 GSource *source;
1683 g_return_val_if_fail (tag > 0, FALSE);
1685 source = g_main_context_find_source_by_id (NULL, tag);
1686 if (source)
1687 g_source_destroy (source);
1689 return source != NULL;
1693 * g_source_remove_by_user_data:
1694 * @user_data: the user_data for the callback.
1696 * Removes a source from the default main loop context given the user
1697 * data for the callback. If multiple sources exist with the same user
1698 * data, only one will be destroyed.
1700 * Return value: %TRUE if a source was found and removed.
1702 gboolean
1703 g_source_remove_by_user_data (gpointer user_data)
1705 GSource *source;
1707 source = g_main_context_find_source_by_user_data (NULL, user_data);
1708 if (source)
1710 g_source_destroy (source);
1711 return TRUE;
1713 else
1714 return FALSE;
1718 * g_source_remove_by_funcs_user_data:
1719 * @funcs: The @source_funcs passed to g_source_new()
1720 * @user_data: the user data for the callback
1722 * Removes a source from the default main loop context given the
1723 * source functions and user data. If multiple sources exist with the
1724 * same source functions and user data, only one will be destroyed.
1726 * Return value: %TRUE if a source was found and removed.
1728 gboolean
1729 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1730 gpointer user_data)
1732 GSource *source;
1734 g_return_val_if_fail (funcs != NULL, FALSE);
1736 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1737 if (source)
1739 g_source_destroy (source);
1740 return TRUE;
1742 else
1743 return FALSE;
1747 * g_get_current_time:
1748 * @result: #GTimeVal structure in which to store current time.
1750 * Equivalent to the UNIX gettimeofday() function, but portable.
1752 void
1753 g_get_current_time (GTimeVal *result)
1755 #ifndef G_OS_WIN32
1756 struct timeval r;
1758 g_return_if_fail (result != NULL);
1760 /*this is required on alpha, there the timeval structs are int's
1761 not longs and a cast only would fail horribly*/
1762 gettimeofday (&r, NULL);
1763 result->tv_sec = r.tv_sec;
1764 result->tv_usec = r.tv_usec;
1765 #else
1766 FILETIME ft;
1767 guint64 time64;
1769 g_return_if_fail (result != NULL);
1771 GetSystemTimeAsFileTime (&ft);
1772 memmove (&time64, &ft, sizeof (FILETIME));
1774 /* Convert from 100s of nanoseconds since 1601-01-01
1775 * to Unix epoch. Yes, this is Y2038 unsafe.
1777 time64 -= G_GINT64_CONSTANT (116444736000000000);
1778 time64 /= 10;
1780 result->tv_sec = time64 / 1000000;
1781 result->tv_usec = time64 % 1000000;
1782 #endif
1785 static void
1786 g_main_dispatch_free (gpointer dispatch)
1788 g_slice_free (GMainDispatch, dispatch);
1791 /* Running the main loop */
1793 static GMainDispatch *
1794 get_dispatch (void)
1796 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
1797 GMainDispatch *dispatch = g_static_private_get (&depth_private);
1798 if (!dispatch)
1800 dispatch = g_slice_new0 (GMainDispatch);
1801 g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
1804 return dispatch;
1808 * g_main_depth:
1810 * Returns the depth of the stack of calls to
1811 * g_main_context_dispatch() on any #GMainContext in the current thread.
1812 * That is, when called from the toplevel, it gives 0. When
1813 * called from within a callback from g_main_context_iteration()
1814 * (or g_main_loop_run(), etc.) it returns 1. When called from within
1815 * a callback to a recursive call to g_main_context_iterate(),
1816 * it returns 2. And so forth.
1818 * This function is useful in a situation like the following:
1819 * Imagine an extremely simple "garbage collected" system.
1821 * |[
1822 * static GList *free_list;
1824 * gpointer
1825 * allocate_memory (gsize size)
1826 * {
1827 * gpointer result = g_malloc (size);
1828 * free_list = g_list_prepend (free_list, result);
1829 * return result;
1832 * void
1833 * free_allocated_memory (void)
1835 * GList *l;
1836 * for (l = free_list; l; l = l->next);
1837 * g_free (l->data);
1838 * g_list_free (free_list);
1839 * free_list = NULL;
1842 * [...]
1844 * while (TRUE);
1846 * g_main_context_iteration (NULL, TRUE);
1847 * free_allocated_memory();
1849 * ]|
1851 * This works from an application, however, if you want to do the same
1852 * thing from a library, it gets more difficult, since you no longer
1853 * control the main loop. You might think you can simply use an idle
1854 * function to make the call to free_allocated_memory(), but that
1855 * doesn't work, since the idle function could be called from a
1856 * recursive callback. This can be fixed by using g_main_depth()
1858 * |[
1859 * gpointer
1860 * allocate_memory (gsize size)
1861 * {
1862 * FreeListBlock *block = g_new (FreeListBlock, 1);
1863 * block->mem = g_malloc (size);
1864 * block->depth = g_main_depth ();
1865 * free_list = g_list_prepend (free_list, block);
1866 * return block->mem;
1869 * void
1870 * free_allocated_memory (void)
1872 * GList *l;
1874 * int depth = g_main_depth ();
1875 * for (l = free_list; l; );
1877 * GList *next = l->next;
1878 * FreeListBlock *block = l->data;
1879 * if (block->depth > depth)
1881 * g_free (block->mem);
1882 * g_free (block);
1883 * free_list = g_list_delete_link (free_list, l);
1886 * l = next;
1889 * ]|
1891 * There is a temptation to use g_main_depth() to solve
1892 * problems with reentrancy. For instance, while waiting for data
1893 * to be received from the network in response to a menu item,
1894 * the menu item might be selected again. It might seem that
1895 * one could make the menu item's callback return immediately
1896 * and do nothing if g_main_depth() returns a value greater than 1.
1897 * However, this should be avoided since the user then sees selecting
1898 * the menu item do nothing. Furthermore, you'll find yourself adding
1899 * these checks all over your code, since there are doubtless many,
1900 * many things that the user could do. Instead, you can use the
1901 * following techniques:
1903 * <orderedlist>
1904 * <listitem>
1905 * <para>
1906 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
1907 * the user from interacting with elements while the main
1908 * loop is recursing.
1909 * </para>
1910 * </listitem>
1911 * <listitem>
1912 * <para>
1913 * Avoid main loop recursion in situations where you can't handle
1914 * arbitrary callbacks. Instead, structure your code so that you
1915 * simply return to the main loop and then get called again when
1916 * there is more work to do.
1917 * </para>
1918 * </listitem>
1919 * </orderedlist>
1921 * Return value: The main loop recursion level in the current thread
1924 g_main_depth (void)
1926 GMainDispatch *dispatch = get_dispatch ();
1927 return dispatch->depth;
1931 * g_main_current_source:
1933 * Returns the currently firing source for this thread.
1935 * Return value: The currently firing source or %NULL.
1937 * Since: 2.12
1939 GSource *
1940 g_main_current_source (void)
1942 GMainDispatch *dispatch = get_dispatch ();
1943 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
1947 * g_source_is_destroyed:
1948 * @source: a #GSource
1950 * Returns whether @source has been destroyed.
1952 * This is important when you operate upon your objects
1953 * from within idle handlers, but may have freed the object
1954 * before the dispatch of your idle handler.
1956 * |[
1957 * static gboolean
1958 * idle_callback (gpointer data)
1960 * SomeWidget *self = data;
1962 * GDK_THREADS_ENTER (<!-- -->);
1963 * /<!-- -->* do stuff with self *<!-- -->/
1964 * self->idle_id = 0;
1965 * GDK_THREADS_LEAVE (<!-- -->);
1967 * return FALSE;
1970 * static void
1971 * some_widget_do_stuff_later (SomeWidget *self)
1973 * self->idle_id = g_idle_add (idle_callback, self);
1976 * static void
1977 * some_widget_finalize (GObject *object)
1979 * SomeWidget *self = SOME_WIDGET (object);
1981 * if (self->idle_id)
1982 * g_source_remove (self->idle_id);
1984 * G_OBJECT_CLASS (parent_class)->finalize (object);
1986 * ]|
1988 * This will fail in a multi-threaded application if the
1989 * widget is destroyed before the idle handler fires due
1990 * to the use after free in the callback. A solution, to
1991 * this particular problem, is to check to if the source
1992 * has already been destroy within the callback.
1994 * |[
1995 * static gboolean
1996 * idle_callback (gpointer data)
1998 * SomeWidget *self = data;
2000 * GDK_THREADS_ENTER ();
2001 * if (!g_source_is_destroyed (g_main_current_source ()))
2003 * /<!-- -->* do stuff with self *<!-- -->/
2005 * GDK_THREADS_LEAVE ();
2007 * return FALSE;
2009 * ]|
2011 * Return value: %TRUE if the source has been destroyed
2013 * Since: 2.12
2015 gboolean
2016 g_source_is_destroyed (GSource *source)
2018 return SOURCE_DESTROYED (source);
2021 /* Temporarily remove all this source's file descriptors from the
2022 * poll(), so that if data comes available for one of the file descriptors
2023 * we don't continually spin in the poll()
2025 /* HOLDS: source->context's lock */
2026 static void
2027 block_source (GSource *source)
2029 GSList *tmp_list;
2031 g_return_if_fail (!SOURCE_BLOCKED (source));
2033 tmp_list = source->poll_fds;
2034 while (tmp_list)
2036 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2037 tmp_list = tmp_list->next;
2041 /* HOLDS: source->context's lock */
2042 static void
2043 unblock_source (GSource *source)
2045 GSList *tmp_list;
2047 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
2048 g_return_if_fail (!SOURCE_DESTROYED (source));
2050 tmp_list = source->poll_fds;
2051 while (tmp_list)
2053 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2054 tmp_list = tmp_list->next;
2058 /* HOLDS: context's lock */
2059 static void
2060 g_main_dispatch (GMainContext *context)
2062 GMainDispatch *current = get_dispatch ();
2063 guint i;
2065 for (i = 0; i < context->pending_dispatches->len; i++)
2067 GSource *source = context->pending_dispatches->pdata[i];
2069 context->pending_dispatches->pdata[i] = NULL;
2070 g_assert (source);
2072 source->flags &= ~G_SOURCE_READY;
2074 if (!SOURCE_DESTROYED (source))
2076 gboolean was_in_call;
2077 gpointer user_data = NULL;
2078 GSourceFunc callback = NULL;
2079 GSourceCallbackFuncs *cb_funcs;
2080 gpointer cb_data;
2081 gboolean need_destroy;
2083 gboolean (*dispatch) (GSource *,
2084 GSourceFunc,
2085 gpointer);
2086 GSList current_source_link;
2088 dispatch = source->source_funcs->dispatch;
2089 cb_funcs = source->callback_funcs;
2090 cb_data = source->callback_data;
2092 if (cb_funcs)
2093 cb_funcs->ref (cb_data);
2095 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2096 block_source (source);
2098 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2099 source->flags |= G_HOOK_FLAG_IN_CALL;
2101 if (cb_funcs)
2102 cb_funcs->get (cb_data, source, &callback, &user_data);
2104 UNLOCK_CONTEXT (context);
2106 current->depth++;
2107 /* The on-stack allocation of the GSList is unconventional, but
2108 * we know that the lifetime of the link is bounded to this
2109 * function as the link is kept in a thread specific list and
2110 * not manipulated outside of this function and its descendants.
2111 * Avoiding the overhead of a g_slist_alloc() is useful as many
2112 * applications do little more than dispatch events.
2114 * This is a performance hack - do not revert to g_slist_prepend()!
2116 current_source_link.data = source;
2117 current_source_link.next = current->dispatching_sources;
2118 current->dispatching_sources = &current_source_link;
2119 need_destroy = ! dispatch (source,
2120 callback,
2121 user_data);
2122 g_assert (current->dispatching_sources == &current_source_link);
2123 current->dispatching_sources = current_source_link.next;
2124 current->depth--;
2126 if (cb_funcs)
2127 cb_funcs->unref (cb_data);
2129 LOCK_CONTEXT (context);
2131 if (!was_in_call)
2132 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2134 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2135 !SOURCE_DESTROYED (source))
2136 unblock_source (source);
2138 /* Note: this depends on the fact that we can't switch
2139 * sources from one main context to another
2141 if (need_destroy && !SOURCE_DESTROYED (source))
2143 g_assert (source->context == context);
2144 g_source_destroy_internal (source, context, TRUE);
2148 SOURCE_UNREF (source, context);
2151 g_ptr_array_set_size (context->pending_dispatches, 0);
2154 /* Holds context's lock */
2155 static inline GSource *
2156 next_valid_source (GMainContext *context,
2157 GSource *source)
2159 GSource *new_source = source ? source->next : context->source_list;
2161 while (new_source)
2163 if (!SOURCE_DESTROYED (new_source))
2165 new_source->ref_count++;
2166 break;
2169 new_source = new_source->next;
2172 if (source)
2173 SOURCE_UNREF (source, context);
2175 return new_source;
2179 * g_main_context_acquire:
2180 * @context: a #GMainContext
2182 * Tries to become the owner of the specified context.
2183 * If some other thread is the owner of the context,
2184 * returns %FALSE immediately. Ownership is properly
2185 * recursive: the owner can require ownership again
2186 * and will release ownership when g_main_context_release()
2187 * is called as many times as g_main_context_acquire().
2189 * You must be the owner of a context before you
2190 * can call g_main_context_prepare(), g_main_context_query(),
2191 * g_main_context_check(), g_main_context_dispatch().
2193 * Return value: %TRUE if the operation succeeded, and
2194 * this thread is now the owner of @context.
2196 gboolean
2197 g_main_context_acquire (GMainContext *context)
2199 #ifdef G_THREADS_ENABLED
2200 gboolean result = FALSE;
2201 GThread *self = G_THREAD_SELF;
2203 if (context == NULL)
2204 context = g_main_context_default ();
2206 LOCK_CONTEXT (context);
2208 if (!context->owner)
2210 context->owner = self;
2211 g_assert (context->owner_count == 0);
2214 if (context->owner == self)
2216 context->owner_count++;
2217 result = TRUE;
2220 UNLOCK_CONTEXT (context);
2222 return result;
2223 #else /* !G_THREADS_ENABLED */
2224 return TRUE;
2225 #endif /* G_THREADS_ENABLED */
2229 * g_main_context_release:
2230 * @context: a #GMainContext
2232 * Releases ownership of a context previously acquired by this thread
2233 * with g_main_context_acquire(). If the context was acquired multiple
2234 * times, the ownership will be released only when g_main_context_release()
2235 * is called as many times as it was acquired.
2237 void
2238 g_main_context_release (GMainContext *context)
2240 #ifdef G_THREADS_ENABLED
2241 if (context == NULL)
2242 context = g_main_context_default ();
2244 LOCK_CONTEXT (context);
2246 context->owner_count--;
2247 if (context->owner_count == 0)
2249 context->owner = NULL;
2251 if (context->waiters)
2253 GMainWaiter *waiter = context->waiters->data;
2254 gboolean loop_internal_waiter =
2255 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
2256 context->waiters = g_slist_delete_link (context->waiters,
2257 context->waiters);
2258 if (!loop_internal_waiter)
2259 g_mutex_lock (waiter->mutex);
2261 g_cond_signal (waiter->cond);
2263 if (!loop_internal_waiter)
2264 g_mutex_unlock (waiter->mutex);
2268 UNLOCK_CONTEXT (context);
2269 #endif /* G_THREADS_ENABLED */
2273 * g_main_context_wait:
2274 * @context: a #GMainContext
2275 * @cond: a condition variable
2276 * @mutex: a mutex, currently held
2278 * Tries to become the owner of the specified context,
2279 * as with g_main_context_acquire(). But if another thread
2280 * is the owner, atomically drop @mutex and wait on @cond until
2281 * that owner releases ownership or until @cond is signaled, then
2282 * try again (once) to become the owner.
2284 * Return value: %TRUE if the operation succeeded, and
2285 * this thread is now the owner of @context.
2287 gboolean
2288 g_main_context_wait (GMainContext *context,
2289 GCond *cond,
2290 GMutex *mutex)
2292 #ifdef G_THREADS_ENABLED
2293 gboolean result = FALSE;
2294 GThread *self = G_THREAD_SELF;
2295 gboolean loop_internal_waiter;
2297 if (context == NULL)
2298 context = g_main_context_default ();
2300 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2302 if (!loop_internal_waiter)
2303 LOCK_CONTEXT (context);
2305 if (context->owner && context->owner != self)
2307 GMainWaiter waiter;
2309 waiter.cond = cond;
2310 waiter.mutex = mutex;
2312 context->waiters = g_slist_append (context->waiters, &waiter);
2314 if (!loop_internal_waiter)
2315 UNLOCK_CONTEXT (context);
2316 g_cond_wait (cond, mutex);
2317 if (!loop_internal_waiter)
2318 LOCK_CONTEXT (context);
2320 context->waiters = g_slist_remove (context->waiters, &waiter);
2323 if (!context->owner)
2325 context->owner = self;
2326 g_assert (context->owner_count == 0);
2329 if (context->owner == self)
2331 context->owner_count++;
2332 result = TRUE;
2335 if (!loop_internal_waiter)
2336 UNLOCK_CONTEXT (context);
2338 return result;
2339 #else /* !G_THREADS_ENABLED */
2340 return TRUE;
2341 #endif /* G_THREADS_ENABLED */
2345 * g_main_context_prepare:
2346 * @context: a #GMainContext
2347 * @priority: location to store priority of highest priority
2348 * source already ready.
2350 * Prepares to poll sources within a main loop. The resulting information
2351 * for polling is determined by calling g_main_context_query ().
2353 * Return value: %TRUE if some source is ready to be dispatched
2354 * prior to polling.
2356 gboolean
2357 g_main_context_prepare (GMainContext *context,
2358 gint *priority)
2360 gint i;
2361 gint n_ready = 0;
2362 gint current_priority = G_MAXINT;
2363 GSource *source;
2365 if (context == NULL)
2366 context = g_main_context_default ();
2368 LOCK_CONTEXT (context);
2370 context->time_is_current = FALSE;
2372 if (context->in_check_or_prepare)
2374 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2375 "prepare() member.");
2376 UNLOCK_CONTEXT (context);
2377 return FALSE;
2380 #ifdef G_THREADS_ENABLED
2381 if (context->poll_waiting)
2383 g_warning("g_main_context_prepare(): main loop already active in another thread");
2384 UNLOCK_CONTEXT (context);
2385 return FALSE;
2388 context->poll_waiting = TRUE;
2389 #endif /* G_THREADS_ENABLED */
2391 #if 0
2392 /* If recursing, finish up current dispatch, before starting over */
2393 if (context->pending_dispatches)
2395 if (dispatch)
2396 g_main_dispatch (context, &current_time);
2398 UNLOCK_CONTEXT (context);
2399 return TRUE;
2401 #endif
2403 /* If recursing, clear list of pending dispatches */
2405 for (i = 0; i < context->pending_dispatches->len; i++)
2407 if (context->pending_dispatches->pdata[i])
2408 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2410 g_ptr_array_set_size (context->pending_dispatches, 0);
2412 /* Prepare all sources */
2414 context->timeout = -1;
2416 source = next_valid_source (context, NULL);
2417 while (source)
2419 gint source_timeout = -1;
2421 if ((n_ready > 0) && (source->priority > current_priority))
2423 SOURCE_UNREF (source, context);
2424 break;
2426 if (SOURCE_BLOCKED (source))
2427 goto next;
2429 if (!(source->flags & G_SOURCE_READY))
2431 gboolean result;
2432 gboolean (*prepare) (GSource *source,
2433 gint *timeout);
2435 prepare = source->source_funcs->prepare;
2436 context->in_check_or_prepare++;
2437 UNLOCK_CONTEXT (context);
2439 result = (*prepare) (source, &source_timeout);
2441 LOCK_CONTEXT (context);
2442 context->in_check_or_prepare--;
2444 if (result)
2445 source->flags |= G_SOURCE_READY;
2448 if (source->flags & G_SOURCE_READY)
2450 n_ready++;
2451 current_priority = source->priority;
2452 context->timeout = 0;
2455 if (source_timeout >= 0)
2457 if (context->timeout < 0)
2458 context->timeout = source_timeout;
2459 else
2460 context->timeout = MIN (context->timeout, source_timeout);
2463 next:
2464 source = next_valid_source (context, source);
2467 UNLOCK_CONTEXT (context);
2469 if (priority)
2470 *priority = current_priority;
2472 return (n_ready > 0);
2476 * g_main_context_query:
2477 * @context: a #GMainContext
2478 * @max_priority: maximum priority source to check
2479 * @timeout_: location to store timeout to be used in polling
2480 * @fds: location to store #GPollFD records that need to be polled.
2481 * @n_fds: length of @fds.
2483 * Determines information necessary to poll this main loop.
2485 * Return value: the number of records actually stored in @fds,
2486 * or, if more than @n_fds records need to be stored, the number
2487 * of records that need to be stored.
2489 gint
2490 g_main_context_query (GMainContext *context,
2491 gint max_priority,
2492 gint *timeout,
2493 GPollFD *fds,
2494 gint n_fds)
2496 gint n_poll;
2497 GPollRec *pollrec;
2499 LOCK_CONTEXT (context);
2501 pollrec = context->poll_records;
2502 n_poll = 0;
2503 while (pollrec && max_priority >= pollrec->priority)
2505 /* We need to include entries with fd->events == 0 in the array because
2506 * otherwise if the application changes fd->events behind our back and
2507 * makes it non-zero, we'll be out of sync when we check the fds[] array.
2508 * (Changing fd->events after adding an FD wasn't an anticipated use of
2509 * this API, but it occurs in practice.) */
2510 if (n_poll < n_fds)
2512 fds[n_poll].fd = pollrec->fd->fd;
2513 /* In direct contradiction to the Unix98 spec, IRIX runs into
2514 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2515 * flags in the events field of the pollfd while it should
2516 * just ignoring them. So we mask them out here.
2518 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2519 fds[n_poll].revents = 0;
2522 pollrec = pollrec->next;
2523 n_poll++;
2526 #ifdef G_THREADS_ENABLED
2527 context->poll_changed = FALSE;
2528 #endif
2530 if (timeout)
2532 *timeout = context->timeout;
2533 if (*timeout != 0)
2534 context->time_is_current = FALSE;
2537 UNLOCK_CONTEXT (context);
2539 return n_poll;
2543 * g_main_context_check:
2544 * @context: a #GMainContext
2545 * @max_priority: the maximum numerical priority of sources to check
2546 * @fds: array of #GPollFD's that was passed to the last call to
2547 * g_main_context_query()
2548 * @n_fds: return value of g_main_context_query()
2550 * Passes the results of polling back to the main loop.
2552 * Return value: %TRUE if some sources are ready to be dispatched.
2554 gboolean
2555 g_main_context_check (GMainContext *context,
2556 gint max_priority,
2557 GPollFD *fds,
2558 gint n_fds)
2560 GSource *source;
2561 GPollRec *pollrec;
2562 gint n_ready = 0;
2563 gint i;
2565 LOCK_CONTEXT (context);
2567 if (context->in_check_or_prepare)
2569 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2570 "prepare() member.");
2571 UNLOCK_CONTEXT (context);
2572 return FALSE;
2575 #ifdef G_THREADS_ENABLED
2576 if (!context->poll_waiting)
2578 #ifndef G_OS_WIN32
2579 gchar a;
2580 read (context->wake_up_pipe[0], &a, 1);
2581 #endif
2583 else
2584 context->poll_waiting = FALSE;
2586 /* If the set of poll file descriptors changed, bail out
2587 * and let the main loop rerun
2589 if (context->poll_changed)
2591 UNLOCK_CONTEXT (context);
2592 return FALSE;
2594 #endif /* G_THREADS_ENABLED */
2596 pollrec = context->poll_records;
2597 i = 0;
2598 while (i < n_fds)
2600 if (pollrec->fd->events)
2601 pollrec->fd->revents = fds[i].revents;
2603 pollrec = pollrec->next;
2604 i++;
2607 source = next_valid_source (context, NULL);
2608 while (source)
2610 if ((n_ready > 0) && (source->priority > max_priority))
2612 SOURCE_UNREF (source, context);
2613 break;
2615 if (SOURCE_BLOCKED (source))
2616 goto next;
2618 if (!(source->flags & G_SOURCE_READY))
2620 gboolean result;
2621 gboolean (*check) (GSource *source);
2623 check = source->source_funcs->check;
2625 context->in_check_or_prepare++;
2626 UNLOCK_CONTEXT (context);
2628 result = (*check) (source);
2630 LOCK_CONTEXT (context);
2631 context->in_check_or_prepare--;
2633 if (result)
2634 source->flags |= G_SOURCE_READY;
2637 if (source->flags & G_SOURCE_READY)
2639 source->ref_count++;
2640 g_ptr_array_add (context->pending_dispatches, source);
2642 n_ready++;
2644 /* never dispatch sources with less priority than the first
2645 * one we choose to dispatch
2647 max_priority = source->priority;
2650 next:
2651 source = next_valid_source (context, source);
2654 UNLOCK_CONTEXT (context);
2656 return n_ready > 0;
2660 * g_main_context_dispatch:
2661 * @context: a #GMainContext
2663 * Dispatches all pending sources.
2665 void
2666 g_main_context_dispatch (GMainContext *context)
2668 LOCK_CONTEXT (context);
2670 if (context->pending_dispatches->len > 0)
2672 g_main_dispatch (context);
2675 UNLOCK_CONTEXT (context);
2678 /* HOLDS context lock */
2679 static gboolean
2680 g_main_context_iterate (GMainContext *context,
2681 gboolean block,
2682 gboolean dispatch,
2683 GThread *self)
2685 gint max_priority;
2686 gint timeout;
2687 gboolean some_ready;
2688 gint nfds, allocated_nfds;
2689 GPollFD *fds = NULL;
2691 UNLOCK_CONTEXT (context);
2693 #ifdef G_THREADS_ENABLED
2694 if (!g_main_context_acquire (context))
2696 gboolean got_ownership;
2698 LOCK_CONTEXT (context);
2700 g_return_val_if_fail (g_thread_supported (), FALSE);
2702 if (!block)
2703 return FALSE;
2705 if (!context->cond)
2706 context->cond = g_cond_new ();
2708 got_ownership = g_main_context_wait (context,
2709 context->cond,
2710 g_static_mutex_get_mutex (&context->mutex));
2712 if (!got_ownership)
2713 return FALSE;
2715 else
2716 LOCK_CONTEXT (context);
2717 #endif /* G_THREADS_ENABLED */
2719 if (!context->cached_poll_array)
2721 context->cached_poll_array_size = context->n_poll_records;
2722 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2725 allocated_nfds = context->cached_poll_array_size;
2726 fds = context->cached_poll_array;
2728 UNLOCK_CONTEXT (context);
2730 g_main_context_prepare (context, &max_priority);
2732 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
2733 allocated_nfds)) > allocated_nfds)
2735 LOCK_CONTEXT (context);
2736 g_free (fds);
2737 context->cached_poll_array_size = allocated_nfds = nfds;
2738 context->cached_poll_array = fds = g_new (GPollFD, nfds);
2739 UNLOCK_CONTEXT (context);
2742 if (!block)
2743 timeout = 0;
2745 g_main_context_poll (context, timeout, max_priority, fds, nfds);
2747 some_ready = g_main_context_check (context, max_priority, fds, nfds);
2749 if (dispatch)
2750 g_main_context_dispatch (context);
2752 #ifdef G_THREADS_ENABLED
2753 g_main_context_release (context);
2754 #endif /* G_THREADS_ENABLED */
2756 LOCK_CONTEXT (context);
2758 return some_ready;
2762 * g_main_context_pending:
2763 * @context: a #GMainContext (if %NULL, the default context will be used)
2765 * Checks if any sources have pending events for the given context.
2767 * Return value: %TRUE if events are pending.
2769 gboolean
2770 g_main_context_pending (GMainContext *context)
2772 gboolean retval;
2774 if (!context)
2775 context = g_main_context_default();
2777 LOCK_CONTEXT (context);
2778 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
2779 UNLOCK_CONTEXT (context);
2781 return retval;
2785 * g_main_context_iteration:
2786 * @context: a #GMainContext (if %NULL, the default context will be used)
2787 * @may_block: whether the call may block.
2789 * Runs a single iteration for the given main loop. This involves
2790 * checking to see if any event sources are ready to be processed,
2791 * then if no events sources are ready and @may_block is %TRUE, waiting
2792 * for a source to become ready, then dispatching the highest priority
2793 * events sources that are ready. Otherwise, if @may_block is %FALSE
2794 * sources are not waited to become ready, only those highest priority
2795 * events sources will be dispatched (if any), that are ready at this
2796 * given moment without further waiting.
2798 * Note that even when @may_block is %TRUE, it is still possible for
2799 * g_main_context_iteration() to return %FALSE, since the the wait may
2800 * be interrupted for other reasons than an event source becoming ready.
2802 * Return value: %TRUE if events were dispatched.
2804 gboolean
2805 g_main_context_iteration (GMainContext *context, gboolean may_block)
2807 gboolean retval;
2809 if (!context)
2810 context = g_main_context_default();
2812 LOCK_CONTEXT (context);
2813 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
2814 UNLOCK_CONTEXT (context);
2816 return retval;
2820 * g_main_loop_new:
2821 * @context: a #GMainContext (if %NULL, the default context will be used).
2822 * @is_running: set to %TRUE to indicate that the loop is running. This
2823 * is not very important since calling g_main_loop_run() will set this to
2824 * %TRUE anyway.
2826 * Creates a new #GMainLoop structure.
2828 * Return value: a new #GMainLoop.
2830 GMainLoop *
2831 g_main_loop_new (GMainContext *context,
2832 gboolean is_running)
2834 GMainLoop *loop;
2836 if (!context)
2837 context = g_main_context_default();
2839 g_main_context_ref (context);
2841 loop = g_new0 (GMainLoop, 1);
2842 loop->context = context;
2843 loop->is_running = is_running != FALSE;
2844 loop->ref_count = 1;
2846 return loop;
2850 * g_main_loop_ref:
2851 * @loop: a #GMainLoop
2853 * Increases the reference count on a #GMainLoop object by one.
2855 * Return value: @loop
2857 GMainLoop *
2858 g_main_loop_ref (GMainLoop *loop)
2860 g_return_val_if_fail (loop != NULL, NULL);
2861 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2863 g_atomic_int_inc (&loop->ref_count);
2865 return loop;
2869 * g_main_loop_unref:
2870 * @loop: a #GMainLoop
2872 * Decreases the reference count on a #GMainLoop object by one. If
2873 * the result is zero, free the loop and free all associated memory.
2875 void
2876 g_main_loop_unref (GMainLoop *loop)
2878 g_return_if_fail (loop != NULL);
2879 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2881 if (!g_atomic_int_dec_and_test (&loop->ref_count))
2882 return;
2884 g_main_context_unref (loop->context);
2885 g_free (loop);
2889 * g_main_loop_run:
2890 * @loop: a #GMainLoop
2892 * Runs a main loop until g_main_loop_quit() is called on the loop.
2893 * If this is called for the thread of the loop's #GMainContext,
2894 * it will process events from the loop, otherwise it will
2895 * simply wait.
2897 void
2898 g_main_loop_run (GMainLoop *loop)
2900 GThread *self = G_THREAD_SELF;
2902 g_return_if_fail (loop != NULL);
2903 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2905 #ifdef G_THREADS_ENABLED
2906 if (!g_main_context_acquire (loop->context))
2908 gboolean got_ownership = FALSE;
2910 /* Another thread owns this context */
2911 if (!g_thread_supported ())
2913 g_warning ("g_main_loop_run() was called from second thread but "
2914 "g_thread_init() was never called.");
2915 return;
2918 LOCK_CONTEXT (loop->context);
2920 g_atomic_int_inc (&loop->ref_count);
2922 if (!loop->is_running)
2923 loop->is_running = TRUE;
2925 if (!loop->context->cond)
2926 loop->context->cond = g_cond_new ();
2928 while (loop->is_running && !got_ownership)
2929 got_ownership = g_main_context_wait (loop->context,
2930 loop->context->cond,
2931 g_static_mutex_get_mutex (&loop->context->mutex));
2933 if (!loop->is_running)
2935 UNLOCK_CONTEXT (loop->context);
2936 if (got_ownership)
2937 g_main_context_release (loop->context);
2938 g_main_loop_unref (loop);
2939 return;
2942 g_assert (got_ownership);
2944 else
2945 LOCK_CONTEXT (loop->context);
2946 #endif /* G_THREADS_ENABLED */
2948 if (loop->context->in_check_or_prepare)
2950 g_warning ("g_main_loop_run(): called recursively from within a source's "
2951 "check() or prepare() member, iteration not possible.");
2952 return;
2955 g_atomic_int_inc (&loop->ref_count);
2956 loop->is_running = TRUE;
2957 while (loop->is_running)
2958 g_main_context_iterate (loop->context, TRUE, TRUE, self);
2960 UNLOCK_CONTEXT (loop->context);
2962 #ifdef G_THREADS_ENABLED
2963 g_main_context_release (loop->context);
2964 #endif /* G_THREADS_ENABLED */
2966 g_main_loop_unref (loop);
2970 * g_main_loop_quit:
2971 * @loop: a #GMainLoop
2973 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
2974 * for the loop will return.
2976 * Note that sources that have already been dispatched when
2977 * g_main_loop_quit() is called will still be executed.
2979 void
2980 g_main_loop_quit (GMainLoop *loop)
2982 g_return_if_fail (loop != NULL);
2983 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2985 LOCK_CONTEXT (loop->context);
2986 loop->is_running = FALSE;
2987 g_main_context_wakeup_unlocked (loop->context);
2989 #ifdef G_THREADS_ENABLED
2990 if (loop->context->cond)
2991 g_cond_broadcast (loop->context->cond);
2992 #endif /* G_THREADS_ENABLED */
2994 UNLOCK_CONTEXT (loop->context);
2998 * g_main_loop_is_running:
2999 * @loop: a #GMainLoop.
3001 * Checks to see if the main loop is currently being run via g_main_loop_run().
3003 * Return value: %TRUE if the mainloop is currently being run.
3005 gboolean
3006 g_main_loop_is_running (GMainLoop *loop)
3008 g_return_val_if_fail (loop != NULL, FALSE);
3009 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3011 return loop->is_running;
3015 * g_main_loop_get_context:
3016 * @loop: a #GMainLoop.
3018 * Returns the #GMainContext of @loop.
3020 * Return value: the #GMainContext of @loop
3022 GMainContext *
3023 g_main_loop_get_context (GMainLoop *loop)
3025 g_return_val_if_fail (loop != NULL, NULL);
3026 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3028 return loop->context;
3031 /* HOLDS: context's lock */
3032 static void
3033 g_main_context_poll (GMainContext *context,
3034 gint timeout,
3035 gint priority,
3036 GPollFD *fds,
3037 gint n_fds)
3039 #ifdef G_MAIN_POLL_DEBUG
3040 GTimer *poll_timer;
3041 GPollRec *pollrec;
3042 gint i;
3043 #endif
3045 GPollFunc poll_func;
3047 if (n_fds || timeout != 0)
3049 #ifdef G_MAIN_POLL_DEBUG
3050 if (_g_main_poll_debug)
3052 g_print ("polling context=%p n=%d timeout=%d\n",
3053 context, n_fds, timeout);
3054 poll_timer = g_timer_new ();
3056 #endif
3058 LOCK_CONTEXT (context);
3060 poll_func = context->poll_func;
3062 UNLOCK_CONTEXT (context);
3063 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3065 #ifndef G_OS_WIN32
3066 g_warning ("poll(2) failed due to: %s.",
3067 g_strerror (errno));
3068 #else
3069 /* If g_poll () returns -1, it has already called g_warning() */
3070 #endif
3073 #ifdef G_MAIN_POLL_DEBUG
3074 if (_g_main_poll_debug)
3076 LOCK_CONTEXT (context);
3078 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3079 n_fds,
3080 timeout,
3081 g_timer_elapsed (poll_timer, NULL));
3082 g_timer_destroy (poll_timer);
3083 pollrec = context->poll_records;
3085 while (pollrec != NULL)
3087 i = 0;
3088 while (i < n_fds)
3090 if (fds[i].fd == pollrec->fd->fd &&
3091 pollrec->fd->events &&
3092 fds[i].revents)
3094 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3095 if (fds[i].revents & G_IO_IN)
3096 g_print ("i");
3097 if (fds[i].revents & G_IO_OUT)
3098 g_print ("o");
3099 if (fds[i].revents & G_IO_PRI)
3100 g_print ("p");
3101 if (fds[i].revents & G_IO_ERR)
3102 g_print ("e");
3103 if (fds[i].revents & G_IO_HUP)
3104 g_print ("h");
3105 if (fds[i].revents & G_IO_NVAL)
3106 g_print ("n");
3107 g_print ("]");
3109 i++;
3111 pollrec = pollrec->next;
3113 g_print ("\n");
3115 UNLOCK_CONTEXT (context);
3117 #endif
3118 } /* if (n_fds || timeout != 0) */
3122 * g_main_context_add_poll:
3123 * @context: a #GMainContext (or %NULL for the default context)
3124 * @fd: a #GPollFD structure holding information about a file
3125 * descriptor to watch.
3126 * @priority: the priority for this file descriptor which should be
3127 * the same as the priority used for g_source_attach() to ensure that the
3128 * file descriptor is polled whenever the results may be needed.
3130 * Adds a file descriptor to the set of file descriptors polled for
3131 * this context. This will very seldomly be used directly. Instead
3132 * a typical event source will use g_source_add_poll() instead.
3134 void
3135 g_main_context_add_poll (GMainContext *context,
3136 GPollFD *fd,
3137 gint priority)
3139 if (!context)
3140 context = g_main_context_default ();
3142 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3143 g_return_if_fail (fd);
3145 LOCK_CONTEXT (context);
3146 g_main_context_add_poll_unlocked (context, priority, fd);
3147 UNLOCK_CONTEXT (context);
3150 /* HOLDS: main_loop_lock */
3151 static void
3152 g_main_context_add_poll_unlocked (GMainContext *context,
3153 gint priority,
3154 GPollFD *fd)
3156 GPollRec *lastrec, *pollrec;
3157 GPollRec *newrec = g_slice_new (GPollRec);
3159 /* This file descriptor may be checked before we ever poll */
3160 fd->revents = 0;
3161 newrec->fd = fd;
3162 newrec->priority = priority;
3164 lastrec = NULL;
3165 pollrec = context->poll_records;
3166 while (pollrec && priority >= pollrec->priority)
3168 lastrec = pollrec;
3169 pollrec = pollrec->next;
3172 if (lastrec)
3173 lastrec->next = newrec;
3174 else
3175 context->poll_records = newrec;
3177 newrec->next = pollrec;
3179 context->n_poll_records++;
3181 #ifdef G_THREADS_ENABLED
3182 context->poll_changed = TRUE;
3184 /* Now wake up the main loop if it is waiting in the poll() */
3185 g_main_context_wakeup_unlocked (context);
3186 #endif
3190 * g_main_context_remove_poll:
3191 * @context:a #GMainContext
3192 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3194 * Removes file descriptor from the set of file descriptors to be
3195 * polled for a particular context.
3197 void
3198 g_main_context_remove_poll (GMainContext *context,
3199 GPollFD *fd)
3201 if (!context)
3202 context = g_main_context_default ();
3204 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3205 g_return_if_fail (fd);
3207 LOCK_CONTEXT (context);
3208 g_main_context_remove_poll_unlocked (context, fd);
3209 UNLOCK_CONTEXT (context);
3212 static void
3213 g_main_context_remove_poll_unlocked (GMainContext *context,
3214 GPollFD *fd)
3216 GPollRec *pollrec, *lastrec;
3218 lastrec = NULL;
3219 pollrec = context->poll_records;
3221 while (pollrec)
3223 if (pollrec->fd == fd)
3225 if (lastrec != NULL)
3226 lastrec->next = pollrec->next;
3227 else
3228 context->poll_records = pollrec->next;
3230 g_slice_free (GPollRec, pollrec);
3232 context->n_poll_records--;
3233 break;
3235 lastrec = pollrec;
3236 pollrec = pollrec->next;
3239 #ifdef G_THREADS_ENABLED
3240 context->poll_changed = TRUE;
3242 /* Now wake up the main loop if it is waiting in the poll() */
3243 g_main_context_wakeup_unlocked (context);
3244 #endif
3248 * g_source_get_current_time:
3249 * @source: a #GSource
3250 * @timeval: #GTimeVal structure in which to store current time.
3252 * Gets the "current time" to be used when checking
3253 * this source. The advantage of calling this function over
3254 * calling g_get_current_time() directly is that when
3255 * checking multiple sources, GLib can cache a single value
3256 * instead of having to repeatedly get the system time.
3258 void
3259 g_source_get_current_time (GSource *source,
3260 GTimeVal *timeval)
3262 GMainContext *context;
3264 g_return_if_fail (source->context != NULL);
3266 context = source->context;
3268 LOCK_CONTEXT (context);
3270 if (!context->time_is_current)
3272 g_get_current_time (&context->current_time);
3273 context->time_is_current = TRUE;
3276 *timeval = context->current_time;
3278 UNLOCK_CONTEXT (context);
3282 * g_main_context_set_poll_func:
3283 * @context: a #GMainContext
3284 * @func: the function to call to poll all file descriptors
3286 * Sets the function to use to handle polling of file descriptors. It
3287 * will be used instead of the poll() system call
3288 * (or GLib's replacement function, which is used where
3289 * poll() isn't available).
3291 * This function could possibly be used to integrate the GLib event
3292 * loop with an external event loop.
3294 void
3295 g_main_context_set_poll_func (GMainContext *context,
3296 GPollFunc func)
3298 if (!context)
3299 context = g_main_context_default ();
3301 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3303 LOCK_CONTEXT (context);
3305 if (func)
3306 context->poll_func = func;
3307 else
3308 context->poll_func = g_poll;
3310 UNLOCK_CONTEXT (context);
3314 * g_main_context_get_poll_func:
3315 * @context: a #GMainContext
3317 * Gets the poll function set by g_main_context_set_poll_func().
3319 * Return value: the poll function
3321 GPollFunc
3322 g_main_context_get_poll_func (GMainContext *context)
3324 GPollFunc result;
3326 if (!context)
3327 context = g_main_context_default ();
3329 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3331 LOCK_CONTEXT (context);
3332 result = context->poll_func;
3333 UNLOCK_CONTEXT (context);
3335 return result;
3338 /* HOLDS: context's lock */
3339 /* Wake the main loop up from a poll() */
3340 static void
3341 g_main_context_wakeup_unlocked (GMainContext *context)
3343 #ifdef G_THREADS_ENABLED
3344 if (g_thread_supported() && context->poll_waiting)
3346 context->poll_waiting = FALSE;
3347 #ifndef G_OS_WIN32
3348 write (context->wake_up_pipe[1], "A", 1);
3349 #else
3350 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
3351 #endif
3353 #endif
3357 * g_main_context_wakeup:
3358 * @context: a #GMainContext
3360 * If @context is currently waiting in a poll(), interrupt
3361 * the poll(), and continue the iteration process.
3363 void
3364 g_main_context_wakeup (GMainContext *context)
3366 if (!context)
3367 context = g_main_context_default ();
3369 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3371 LOCK_CONTEXT (context);
3372 g_main_context_wakeup_unlocked (context);
3373 UNLOCK_CONTEXT (context);
3377 * g_main_context_is_owner:
3378 * @context: a #GMainContext
3380 * Determines whether this thread holds the (recursive)
3381 * ownership of this #GMaincontext. This is useful to
3382 * know before waiting on another thread that may be
3383 * blocking to get ownership of @context.
3385 * Returns: %TRUE if current thread is owner of @context.
3387 * Since: 2.10
3389 gboolean
3390 g_main_context_is_owner (GMainContext *context)
3392 gboolean is_owner;
3394 if (!context)
3395 context = g_main_context_default ();
3397 #ifdef G_THREADS_ENABLED
3398 LOCK_CONTEXT (context);
3399 is_owner = context->owner == G_THREAD_SELF;
3400 UNLOCK_CONTEXT (context);
3401 #else
3402 is_owner = TRUE;
3403 #endif
3405 return is_owner;
3408 /* Timeouts */
3410 static void
3411 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3412 GTimeVal *current_time)
3414 guint seconds = timeout_source->interval / 1000;
3415 guint msecs = timeout_source->interval - seconds * 1000;
3417 timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
3418 timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
3419 if (timeout_source->expiration.tv_usec >= 1000000)
3421 timeout_source->expiration.tv_usec -= 1000000;
3422 timeout_source->expiration.tv_sec++;
3424 if (timer_perturb==-1)
3427 * we want a per machine/session unique 'random' value; try the dbus
3428 * address first, that has a UUID in it. If there is no dbus, use the
3429 * hostname for hashing.
3431 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3432 if (!session_bus_address)
3433 session_bus_address = g_getenv ("HOSTNAME");
3434 if (session_bus_address)
3435 timer_perturb = ABS ((gint) g_str_hash (session_bus_address));
3436 else
3437 timer_perturb = 0;
3439 if (timeout_source->granularity)
3441 gint remainder;
3442 gint gran; /* in usecs */
3443 gint perturb;
3445 gran = timeout_source->granularity * 1000;
3446 perturb = timer_perturb % gran;
3448 * We want to give each machine a per machine pertubation;
3449 * shift time back first, and forward later after the rounding
3452 timeout_source->expiration.tv_usec -= perturb;
3453 if (timeout_source->expiration.tv_usec < 0)
3455 timeout_source->expiration.tv_usec += 1000000;
3456 timeout_source->expiration.tv_sec--;
3459 remainder = timeout_source->expiration.tv_usec % gran;
3460 if (remainder >= gran/4) /* round up */
3461 timeout_source->expiration.tv_usec += gran;
3462 timeout_source->expiration.tv_usec -= remainder;
3463 /* shift back */
3464 timeout_source->expiration.tv_usec += perturb;
3466 /* the rounding may have overflown tv_usec */
3467 while (timeout_source->expiration.tv_usec > 1000000)
3469 timeout_source->expiration.tv_usec -= 1000000;
3470 timeout_source->expiration.tv_sec++;
3475 static gboolean
3476 g_timeout_prepare (GSource *source,
3477 gint *timeout)
3479 glong sec;
3480 glong msec;
3481 GTimeVal current_time;
3483 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3485 g_source_get_current_time (source, &current_time);
3487 sec = timeout_source->expiration.tv_sec - current_time.tv_sec;
3488 msec = (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000;
3490 /* We do the following in a rather convoluted fashion to deal with
3491 * the fact that we don't have an integral type big enough to hold
3492 * the difference of two timevals in millseconds.
3494 if (sec < 0 || (sec == 0 && msec < 0))
3495 msec = 0;
3496 else
3498 glong interval_sec = timeout_source->interval / 1000;
3499 glong interval_msec = timeout_source->interval % 1000;
3501 if (msec < 0)
3503 msec += 1000;
3504 sec -= 1;
3507 if (sec > interval_sec ||
3508 (sec == interval_sec && msec > interval_msec))
3510 /* The system time has been set backwards, so we
3511 * reset the expiration time to now + timeout_source->interval;
3512 * this at least avoids hanging for long periods of time.
3514 g_timeout_set_expiration (timeout_source, &current_time);
3515 msec = MIN (G_MAXINT, timeout_source->interval);
3517 else
3519 msec = MIN (G_MAXINT, (guint)msec + 1000 * (guint)sec);
3523 *timeout = (gint)msec;
3525 return msec == 0;
3528 static gboolean
3529 g_timeout_check (GSource *source)
3531 GTimeVal current_time;
3532 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3534 g_source_get_current_time (source, &current_time);
3536 return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
3537 ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
3538 (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
3541 static gboolean
3542 g_timeout_dispatch (GSource *source,
3543 GSourceFunc callback,
3544 gpointer user_data)
3546 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3548 if (!callback)
3550 g_warning ("Timeout source dispatched without callback\n"
3551 "You must call g_source_set_callback().");
3552 return FALSE;
3555 if (callback (user_data))
3557 GTimeVal current_time;
3559 g_source_get_current_time (source, &current_time);
3560 g_timeout_set_expiration (timeout_source, &current_time);
3562 return TRUE;
3564 else
3565 return FALSE;
3569 * g_timeout_source_new:
3570 * @interval: the timeout interval in milliseconds.
3572 * Creates a new timeout source.
3574 * The source will not initially be associated with any #GMainContext
3575 * and must be added to one with g_source_attach() before it will be
3576 * executed.
3578 * Return value: the newly-created timeout source
3580 GSource *
3581 g_timeout_source_new (guint interval)
3583 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3584 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3585 GTimeVal current_time;
3587 timeout_source->interval = interval;
3589 g_get_current_time (&current_time);
3590 g_timeout_set_expiration (timeout_source, &current_time);
3592 return source;
3596 * g_timeout_source_new_seconds:
3597 * @interval: the timeout interval in seconds
3599 * Creates a new timeout source.
3601 * The source will not initially be associated with any #GMainContext
3602 * and must be added to one with g_source_attach() before it will be
3603 * executed.
3605 * The scheduling granularity/accuracy of this timeout source will be
3606 * in seconds.
3608 * Return value: the newly-created timeout source
3610 * Since: 2.14
3612 GSource *
3613 g_timeout_source_new_seconds (guint interval)
3615 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3616 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3617 GTimeVal current_time;
3619 timeout_source->interval = 1000*interval;
3620 timeout_source->granularity = 1000;
3622 g_get_current_time (&current_time);
3623 g_timeout_set_expiration (timeout_source, &current_time);
3625 return source;
3630 * g_timeout_add_full:
3631 * @priority: the priority of the timeout source. Typically this will be in
3632 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3633 * @interval: the time between calls to the function, in milliseconds
3634 * (1/1000ths of a second)
3635 * @function: function to call
3636 * @data: data to pass to @function
3637 * @notify: function to call when the timeout is removed, or %NULL
3639 * Sets a function to be called at regular intervals, with the given
3640 * priority. The function is called repeatedly until it returns
3641 * %FALSE, at which point the timeout is automatically destroyed and
3642 * the function will not be called again. The @notify function is
3643 * called when the timeout is destroyed. The first call to the
3644 * function will be at the end of the first @interval.
3646 * Note that timeout functions may be delayed, due to the processing of other
3647 * event sources. Thus they should not be relied on for precise timing.
3648 * After each call to the timeout function, the time of the next
3649 * timeout is recalculated based on the current time and the given interval
3650 * (it does not try to 'catch up' time lost in delays).
3652 * This internally creates a main loop source using g_timeout_source_new()
3653 * and attaches it to the main loop context using g_source_attach(). You can
3654 * do these steps manually if you need greater control.
3656 * Return value: the ID (greater than 0) of the event source.
3658 guint
3659 g_timeout_add_full (gint priority,
3660 guint interval,
3661 GSourceFunc function,
3662 gpointer data,
3663 GDestroyNotify notify)
3665 GSource *source;
3666 guint id;
3668 g_return_val_if_fail (function != NULL, 0);
3670 source = g_timeout_source_new (interval);
3672 if (priority != G_PRIORITY_DEFAULT)
3673 g_source_set_priority (source, priority);
3675 g_source_set_callback (source, function, data, notify);
3676 id = g_source_attach (source, NULL);
3677 g_source_unref (source);
3679 return id;
3683 * g_timeout_add:
3684 * @interval: the time between calls to the function, in milliseconds
3685 * (1/1000ths of a second)
3686 * @function: function to call
3687 * @data: data to pass to @function
3689 * Sets a function to be called at regular intervals, with the default
3690 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
3691 * until it returns %FALSE, at which point the timeout is automatically
3692 * destroyed and the function will not be called again. The first call
3693 * to the function will be at the end of the first @interval.
3695 * Note that timeout functions may be delayed, due to the processing of other
3696 * event sources. Thus they should not be relied on for precise timing.
3697 * After each call to the timeout function, the time of the next
3698 * timeout is recalculated based on the current time and the given interval
3699 * (it does not try to 'catch up' time lost in delays).
3701 * If you want to have a timer in the "seconds" range and do not care
3702 * about the exact time of the first call of the timer, use the
3703 * g_timeout_add_seconds() function; this function allows for more
3704 * optimizations and more efficient system power usage.
3706 * This internally creates a main loop source using g_timeout_source_new()
3707 * and attaches it to the main loop context using g_source_attach(). You can
3708 * do these steps manually if you need greater control.
3710 * Return value: the ID (greater than 0) of the event source.
3712 guint
3713 g_timeout_add (guint32 interval,
3714 GSourceFunc function,
3715 gpointer data)
3717 return g_timeout_add_full (G_PRIORITY_DEFAULT,
3718 interval, function, data, NULL);
3722 * g_timeout_add_seconds_full:
3723 * @priority: the priority of the timeout source. Typically this will be in
3724 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3725 * @interval: the time between calls to the function, in seconds
3726 * @function: function to call
3727 * @data: data to pass to @function
3728 * @notify: function to call when the timeout is removed, or %NULL
3730 * Sets a function to be called at regular intervals, with @priority.
3731 * The function is called repeatedly until it returns %FALSE, at which
3732 * point the timeout is automatically destroyed and the function will
3733 * not be called again.
3735 * Unlike g_timeout_add(), this function operates at whole second granularity.
3736 * The initial starting point of the timer is determined by the implementation
3737 * and the implementation is expected to group multiple timers together so that
3738 * they fire all at the same time.
3739 * To allow this grouping, the @interval to the first timer is rounded
3740 * and can deviate up to one second from the specified interval.
3741 * Subsequent timer iterations will generally run at the specified interval.
3743 * Note that timeout functions may be delayed, due to the processing of other
3744 * event sources. Thus they should not be relied on for precise timing.
3745 * After each call to the timeout function, the time of the next
3746 * timeout is recalculated based on the current time and the given @interval
3748 * If you want timing more precise than whole seconds, use g_timeout_add()
3749 * instead.
3751 * The grouping of timers to fire at the same time results in a more power
3752 * and CPU efficient behavior so if your timer is in multiples of seconds
3753 * and you don't require the first timer exactly one second from now, the
3754 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
3756 * This internally creates a main loop source using
3757 * g_timeout_source_new_seconds() and attaches it to the main loop context
3758 * using g_source_attach(). You can do these steps manually if you need
3759 * greater control.
3761 * Return value: the ID (greater than 0) of the event source.
3763 * Since: 2.14
3765 guint
3766 g_timeout_add_seconds_full (gint priority,
3767 guint32 interval,
3768 GSourceFunc function,
3769 gpointer data,
3770 GDestroyNotify notify)
3772 GSource *source;
3773 guint id;
3775 g_return_val_if_fail (function != NULL, 0);
3777 source = g_timeout_source_new_seconds (interval);
3779 if (priority != G_PRIORITY_DEFAULT)
3780 g_source_set_priority (source, priority);
3782 g_source_set_callback (source, function, data, notify);
3783 id = g_source_attach (source, NULL);
3784 g_source_unref (source);
3786 return id;
3790 * g_timeout_add_seconds:
3791 * @interval: the time between calls to the function, in seconds
3792 * @function: function to call
3793 * @data: data to pass to @function
3795 * Sets a function to be called at regular intervals with the default
3796 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
3797 * it returns %FALSE, at which point the timeout is automatically destroyed
3798 * and the function will not be called again.
3800 * This internally creates a main loop source using
3801 * g_timeout_source_new_seconds() and attaches it to the main loop context
3802 * using g_source_attach(). You can do these steps manually if you need
3803 * greater control. Also see g_timout_add_seconds_full().
3805 * Return value: the ID (greater than 0) of the event source.
3807 * Since: 2.14
3809 guint
3810 g_timeout_add_seconds (guint interval,
3811 GSourceFunc function,
3812 gpointer data)
3814 g_return_val_if_fail (function != NULL, 0);
3816 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
3819 /* Child watch functions */
3821 #ifdef G_OS_WIN32
3823 static gboolean
3824 g_child_watch_prepare (GSource *source,
3825 gint *timeout)
3827 *timeout = -1;
3828 return FALSE;
3832 static gboolean
3833 g_child_watch_check (GSource *source)
3835 GChildWatchSource *child_watch_source;
3836 gboolean child_exited;
3838 child_watch_source = (GChildWatchSource *) source;
3840 child_exited = child_watch_source->poll.revents & G_IO_IN;
3842 if (child_exited)
3844 DWORD child_status;
3847 * Note: We do _not_ check for the special value of STILL_ACTIVE
3848 * since we know that the process has exited and doing so runs into
3849 * problems if the child process "happens to return STILL_ACTIVE(259)"
3850 * as Microsoft's Platform SDK puts it.
3852 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
3854 gchar *emsg = g_win32_error_message (GetLastError ());
3855 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
3856 g_free (emsg);
3858 child_watch_source->child_status = -1;
3860 else
3861 child_watch_source->child_status = child_status;
3864 return child_exited;
3867 #else /* G_OS_WIN32 */
3869 static gboolean
3870 check_for_child_exited (GSource *source)
3872 GChildWatchSource *child_watch_source;
3873 gint count;
3875 /* protect against another SIGCHLD in the middle of this call */
3876 count = child_watch_count;
3878 child_watch_source = (GChildWatchSource *) source;
3880 if (child_watch_source->child_exited)
3881 return TRUE;
3883 if (child_watch_source->count < count)
3885 gint child_status;
3887 if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
3889 child_watch_source->child_status = child_status;
3890 child_watch_source->child_exited = TRUE;
3892 child_watch_source->count = count;
3895 return child_watch_source->child_exited;
3898 static gboolean
3899 g_child_watch_prepare (GSource *source,
3900 gint *timeout)
3902 *timeout = -1;
3904 return check_for_child_exited (source);
3908 static gboolean
3909 g_child_watch_check (GSource *source)
3911 return check_for_child_exited (source);
3914 #endif /* G_OS_WIN32 */
3916 static gboolean
3917 g_child_watch_dispatch (GSource *source,
3918 GSourceFunc callback,
3919 gpointer user_data)
3921 GChildWatchSource *child_watch_source;
3922 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
3924 child_watch_source = (GChildWatchSource *) source;
3926 if (!callback)
3928 g_warning ("Child watch source dispatched without callback\n"
3929 "You must call g_source_set_callback().");
3930 return FALSE;
3933 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
3935 /* We never keep a child watch source around as the child is gone */
3936 return FALSE;
3939 #ifndef G_OS_WIN32
3941 static void
3942 g_child_watch_signal_handler (int signum)
3944 child_watch_count ++;
3946 if (child_watch_init_state == CHILD_WATCH_INITIALIZED_THREADED)
3948 write (child_watch_wake_up_pipe[1], "B", 1);
3950 else
3952 /* We count on the signal interrupting the poll in the same thread.
3957 static void
3958 g_child_watch_source_init_single (void)
3960 struct sigaction action;
3962 g_assert (! g_thread_supported());
3963 g_assert (child_watch_init_state == CHILD_WATCH_UNINITIALIZED);
3965 child_watch_init_state = CHILD_WATCH_INITIALIZED_SINGLE;
3967 action.sa_handler = g_child_watch_signal_handler;
3968 sigemptyset (&action.sa_mask);
3969 action.sa_flags = SA_NOCLDSTOP;
3970 sigaction (SIGCHLD, &action, NULL);
3973 G_GNUC_NORETURN static gpointer
3974 child_watch_helper_thread (gpointer data)
3976 while (1)
3978 gchar b[20];
3979 GSList *list;
3981 read (child_watch_wake_up_pipe[0], b, 20);
3983 /* We were woken up. Wake up all other contexts in all other threads */
3984 G_LOCK (main_context_list);
3985 for (list = main_context_list; list; list = list->next)
3987 GMainContext *context;
3989 context = list->data;
3990 if (g_atomic_int_get (&context->ref_count) > 0)
3991 /* Due to racing conditions we can find ref_count == 0, in
3992 * that case, however, the context is still not destroyed
3993 * and no poll can be active, otherwise the ref_count
3994 * wouldn't be 0 */
3995 g_main_context_wakeup (context);
3997 G_UNLOCK (main_context_list);
4001 static void
4002 g_child_watch_source_init_multi_threaded (void)
4004 GError *error = NULL;
4005 struct sigaction action;
4007 g_assert (g_thread_supported());
4009 if (pipe (child_watch_wake_up_pipe) < 0)
4010 g_error ("Cannot create wake up pipe: %s\n", g_strerror (errno));
4011 fcntl (child_watch_wake_up_pipe[1], F_SETFL, O_NONBLOCK | fcntl (child_watch_wake_up_pipe[1], F_GETFL));
4013 /* We create a helper thread that polls on the wakeup pipe indefinitely */
4014 /* FIXME: Think this through for races */
4015 if (g_thread_create (child_watch_helper_thread, NULL, FALSE, &error) == NULL)
4016 g_error ("Cannot create a thread to monitor child exit status: %s\n", error->message);
4017 child_watch_init_state = CHILD_WATCH_INITIALIZED_THREADED;
4019 action.sa_handler = g_child_watch_signal_handler;
4020 sigemptyset (&action.sa_mask);
4021 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4022 sigaction (SIGCHLD, &action, NULL);
4025 static void
4026 g_child_watch_source_init_promote_single_to_threaded (void)
4028 g_child_watch_source_init_multi_threaded ();
4031 static void
4032 g_child_watch_source_init (void)
4034 if (g_thread_supported())
4036 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
4037 g_child_watch_source_init_multi_threaded ();
4038 else if (child_watch_init_state == CHILD_WATCH_INITIALIZED_SINGLE)
4039 g_child_watch_source_init_promote_single_to_threaded ();
4041 else
4043 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
4044 g_child_watch_source_init_single ();
4048 #endif /* !G_OS_WIN32 */
4051 * g_child_watch_source_new:
4052 * @pid: process to watch. On POSIX the pid of a child process. On
4053 * Windows a handle for a process (which doesn't have to be a child).
4055 * Creates a new child_watch source.
4057 * The source will not initially be associated with any #GMainContext
4058 * and must be added to one with g_source_attach() before it will be
4059 * executed.
4061 * Note that child watch sources can only be used in conjunction with
4062 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4063 * flag is used.
4065 * Note that on platforms where #GPid must be explicitly closed
4066 * (see g_spawn_close_pid()) @pid must not be closed while the
4067 * source is still active. Typically, you will want to call
4068 * g_spawn_close_pid() in the callback function for the source.
4070 * Note further that using g_child_watch_source_new() is not
4071 * compatible with calling <literal>waitpid(-1)</literal> in
4072 * the application. Calling waitpid() for individual pids will
4073 * still work fine.
4075 * Return value: the newly-created child watch source
4077 * Since: 2.4
4079 GSource *
4080 g_child_watch_source_new (GPid pid)
4082 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4083 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4085 #ifdef G_OS_WIN32
4086 child_watch_source->poll.fd = (gintptr) pid;
4087 child_watch_source->poll.events = G_IO_IN;
4089 g_source_add_poll (source, &child_watch_source->poll);
4090 #else /* G_OS_WIN32 */
4091 g_child_watch_source_init ();
4092 #endif /* G_OS_WIN32 */
4094 child_watch_source->pid = pid;
4096 return source;
4100 * g_child_watch_add_full:
4101 * @priority: the priority of the idle source. Typically this will be in the
4102 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4103 * @pid: process to watch. On POSIX the pid of a child process. On
4104 * Windows a handle for a process (which doesn't have to be a child).
4105 * @function: function to call
4106 * @data: data to pass to @function
4107 * @notify: function to call when the idle is removed, or %NULL
4109 * Sets a function to be called when the child indicated by @pid
4110 * exits, at the priority @priority.
4112 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4113 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4114 * the spawn function for the child watching to work.
4116 * Note that on platforms where #GPid must be explicitly closed
4117 * (see g_spawn_close_pid()) @pid must not be closed while the
4118 * source is still active. Typically, you will want to call
4119 * g_spawn_close_pid() in the callback function for the source.
4121 * GLib supports only a single callback per process id.
4123 * This internally creates a main loop source using
4124 * g_child_watch_source_new() and attaches it to the main loop context
4125 * using g_source_attach(). You can do these steps manually if you
4126 * need greater control.
4128 * Return value: the ID (greater than 0) of the event source.
4130 * Since: 2.4
4132 guint
4133 g_child_watch_add_full (gint priority,
4134 GPid pid,
4135 GChildWatchFunc function,
4136 gpointer data,
4137 GDestroyNotify notify)
4139 GSource *source;
4140 guint id;
4142 g_return_val_if_fail (function != NULL, 0);
4144 source = g_child_watch_source_new (pid);
4146 if (priority != G_PRIORITY_DEFAULT)
4147 g_source_set_priority (source, priority);
4149 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4150 id = g_source_attach (source, NULL);
4151 g_source_unref (source);
4153 return id;
4157 * g_child_watch_add:
4158 * @pid: process id to watch. On POSIX the pid of a child process. On
4159 * Windows a handle for a process (which doesn't have to be a child).
4160 * @function: function to call
4161 * @data: data to pass to @function
4163 * Sets a function to be called when the child indicated by @pid
4164 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4166 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4167 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4168 * the spawn function for the child watching to work.
4170 * Note that on platforms where #GPid must be explicitly closed
4171 * (see g_spawn_close_pid()) @pid must not be closed while the
4172 * source is still active. Typically, you will want to call
4173 * g_spawn_close_pid() in the callback function for the source.
4175 * GLib supports only a single callback per process id.
4177 * This internally creates a main loop source using
4178 * g_child_watch_source_new() and attaches it to the main loop context
4179 * using g_source_attach(). You can do these steps manually if you
4180 * need greater control.
4182 * Return value: the ID (greater than 0) of the event source.
4184 * Since: 2.4
4186 guint
4187 g_child_watch_add (GPid pid,
4188 GChildWatchFunc function,
4189 gpointer data)
4191 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4195 /* Idle functions */
4197 static gboolean
4198 g_idle_prepare (GSource *source,
4199 gint *timeout)
4201 *timeout = 0;
4203 return TRUE;
4206 static gboolean
4207 g_idle_check (GSource *source)
4209 return TRUE;
4212 static gboolean
4213 g_idle_dispatch (GSource *source,
4214 GSourceFunc callback,
4215 gpointer user_data)
4217 if (!callback)
4219 g_warning ("Idle source dispatched without callback\n"
4220 "You must call g_source_set_callback().");
4221 return FALSE;
4224 return callback (user_data);
4228 * g_idle_source_new:
4230 * Creates a new idle source.
4232 * The source will not initially be associated with any #GMainContext
4233 * and must be added to one with g_source_attach() before it will be
4234 * executed. Note that the default priority for idle sources is
4235 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4236 * have a default priority of %G_PRIORITY_DEFAULT.
4238 * Return value: the newly-created idle source
4240 GSource *
4241 g_idle_source_new (void)
4243 GSource *source;
4245 source = g_source_new (&g_idle_funcs, sizeof (GSource));
4246 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4248 return source;
4252 * g_idle_add_full:
4253 * @priority: the priority of the idle source. Typically this will be in the
4254 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4255 * @function: function to call
4256 * @data: data to pass to @function
4257 * @notify: function to call when the idle is removed, or %NULL
4259 * Adds a function to be called whenever there are no higher priority
4260 * events pending. If the function returns %FALSE it is automatically
4261 * removed from the list of event sources and will not be called again.
4263 * This internally creates a main loop source using g_idle_source_new()
4264 * and attaches it to the main loop context using g_source_attach().
4265 * You can do these steps manually if you need greater control.
4267 * Return value: the ID (greater than 0) of the event source.
4269 guint
4270 g_idle_add_full (gint priority,
4271 GSourceFunc function,
4272 gpointer data,
4273 GDestroyNotify notify)
4275 GSource *source;
4276 guint id;
4278 g_return_val_if_fail (function != NULL, 0);
4280 source = g_idle_source_new ();
4282 if (priority != G_PRIORITY_DEFAULT_IDLE)
4283 g_source_set_priority (source, priority);
4285 g_source_set_callback (source, function, data, notify);
4286 id = g_source_attach (source, NULL);
4287 g_source_unref (source);
4289 return id;
4293 * g_idle_add:
4294 * @function: function to call
4295 * @data: data to pass to @function.
4297 * Adds a function to be called whenever there are no higher priority
4298 * events pending to the default main loop. The function is given the
4299 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4300 * returns %FALSE it is automatically removed from the list of event
4301 * sources and will not be called again.
4303 * This internally creates a main loop source using g_idle_source_new()
4304 * and attaches it to the main loop context using g_source_attach().
4305 * You can do these steps manually if you need greater control.
4307 * Return value: the ID (greater than 0) of the event source.
4309 guint
4310 g_idle_add (GSourceFunc function,
4311 gpointer data)
4313 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4317 * g_idle_remove_by_data:
4318 * @data: the data for the idle source's callback.
4320 * Removes the idle function with the given data.
4322 * Return value: %TRUE if an idle source was found and removed.
4324 gboolean
4325 g_idle_remove_by_data (gpointer data)
4327 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);