Revert addition of g_key_file_has_key_full
[glib.git] / glib / gmain.c
blob9efbff6bb9b62cc646145aaddea868ea6e5a2b87
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/.
31 * MT safe
34 #include "config.h"
35 #include "glibconfig.h"
37 /* Uncomment the next line (and the corresponding line in gpoll.c) to
38 * enable debugging printouts if the environment variable
39 * G_MAIN_POLL_DEBUG is set to some value.
41 /* #define G_MAIN_POLL_DEBUG */
43 #ifdef _WIN32
44 /* Always enable debugging printout on Windows, as it is more often
45 * needed there...
47 #define G_MAIN_POLL_DEBUG
48 #endif
50 #ifdef G_OS_UNIX
51 #include "glib-unix.h"
52 #ifdef HAVE_EVENTFD
53 #include <sys/eventfd.h>
54 #endif
55 #endif
57 #include <signal.h>
58 #include <sys/types.h>
59 #include <time.h>
60 #include <stdlib.h>
61 #ifdef HAVE_SYS_TIME_H
62 #include <sys/time.h>
63 #endif /* HAVE_SYS_TIME_H */
64 #ifdef HAVE_UNISTD_H
65 #include <unistd.h>
66 #endif /* HAVE_UNISTD_H */
67 #include <errno.h>
68 #include <string.h>
70 #ifdef G_OS_WIN32
71 #define STRICT
72 #include <windows.h>
73 #endif /* G_OS_WIN32 */
75 #ifdef G_OS_BEOS
76 #include <sys/socket.h>
77 #include <sys/wait.h>
78 #endif /* G_OS_BEOS */
80 #include "gmain.h"
82 #include "garray.h"
83 #include "giochannel.h"
84 #include "ghash.h"
85 #include "ghook.h"
86 #include "gqueue.h"
87 #include "gstrfuncs.h"
88 #include "gtestutils.h"
89 #include "gthreadprivate.h"
91 #ifdef G_OS_WIN32
92 #include "gwin32.h"
93 #endif
95 #ifdef G_MAIN_POLL_DEBUG
96 #include "gtimer.h"
97 #endif
99 /**
100 * SECTION:main
101 * @title: The Main Event Loop
102 * @short_description: manages all available sources of events
104 * The main event loop manages all the available sources of events for
105 * GLib and GTK+ applications. These events can come from any number of
106 * different types of sources such as file descriptors (plain files,
107 * pipes or sockets) and timeouts. New types of event sources can also
108 * be added using g_source_attach().
110 * To allow multiple independent sets of sources to be handled in
111 * different threads, each source is associated with a #GMainContext.
112 * A GMainContext can only be running in a single thread, but
113 * sources can be added to it and removed from it from other threads.
115 * Each event source is assigned a priority. The default priority,
116 * #G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
117 * Values greater than 0 denote lower priorities. Events from high priority
118 * sources are always processed before events from lower priority sources.
120 * Idle functions can also be added, and assigned a priority. These will
121 * be run whenever no events with a higher priority are ready to be processed.
123 * The #GMainLoop data type represents a main event loop. A GMainLoop is
124 * created with g_main_loop_new(). After adding the initial event sources,
125 * g_main_loop_run() is called. This continuously checks for new events from
126 * each of the event sources and dispatches them. Finally, the processing of
127 * an event from one of the sources leads to a call to g_main_loop_quit() to
128 * exit the main loop, and g_main_loop_run() returns.
130 * It is possible to create new instances of #GMainLoop recursively.
131 * This is often used in GTK+ applications when showing modal dialog
132 * boxes. Note that event sources are associated with a particular
133 * #GMainContext, and will be checked and dispatched for all main
134 * loops associated with that GMainContext.
136 * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
137 * gtk_main_quit() and gtk_events_pending().
139 * <refsect2><title>Creating new source types</title>
140 * <para>One of the unusual features of the #GMainLoop functionality
141 * is that new types of event source can be created and used in
142 * addition to the builtin type of event source. A new event source
143 * type is used for handling GDK events. A new source type is created
144 * by <firstterm>deriving</firstterm> from the #GSource structure.
145 * The derived type of source is represented by a structure that has
146 * the #GSource structure as a first element, and other elements specific
147 * to the new source type. To create an instance of the new source type,
148 * call g_source_new() passing in the size of the derived structure and
149 * a table of functions. These #GSourceFuncs determine the behavior of
150 * the new source type.</para>
151 * <para>New source types basically interact with the main context
152 * in two ways. Their prepare function in #GSourceFuncs can set a timeout
153 * to determine the maximum amount of time that the main loop will sleep
154 * before checking the source again. In addition, or as well, the source
155 * can add file descriptors to the set that the main context checks using
156 * g_source_add_poll().</para>
157 * </refsect2>
158 * <refsect2><title>Customizing the main loop iteration</title>
159 * <para>Single iterations of a #GMainContext can be run with
160 * g_main_context_iteration(). In some cases, more detailed control
161 * of exactly how the details of the main loop work is desired, for
162 * instance, when integrating the #GMainLoop with an external main loop.
163 * In such cases, you can call the component functions of
164 * g_main_context_iteration() directly. These functions are
165 * g_main_context_prepare(), g_main_context_query(),
166 * g_main_context_check() and g_main_context_dispatch().</para>
167 * <para>The operation of these functions can best be seen in terms
168 * of a state diagram, as shown in <xref linkend="mainloop-states"/>.</para>
169 * <figure id="mainloop-states"><title>States of a Main Context</title>
170 * <graphic fileref="mainloop-states.gif" format="GIF"></graphic>
171 * </figure>
172 * </refsect2>
175 /* Types */
177 typedef struct _GTimeoutSource GTimeoutSource;
178 typedef struct _GChildWatchSource GChildWatchSource;
179 typedef struct _GUnixSignalWatchSource GUnixSignalWatchSource;
180 typedef struct _GPollRec GPollRec;
181 typedef struct _GSourceCallback GSourceCallback;
183 typedef enum
185 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
186 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
187 } GSourceFlags;
189 #ifdef G_THREADS_ENABLED
190 typedef struct _GMainWaiter GMainWaiter;
192 struct _GMainWaiter
194 GCond *cond;
195 GMutex *mutex;
197 #endif
199 typedef struct _GMainDispatch GMainDispatch;
201 struct _GMainDispatch
203 gint depth;
204 GSList *dispatching_sources; /* stack of current sources */
207 #ifdef G_MAIN_POLL_DEBUG
208 gboolean _g_main_poll_debug = FALSE;
209 #endif
211 struct _GMainContext
213 #ifdef G_THREADS_ENABLED
214 /* The following lock is used for both the list of sources
215 * and the list of poll records
217 GStaticMutex mutex;
218 GCond *cond;
219 GThread *owner;
220 guint owner_count;
221 GSList *waiters;
222 #endif
224 gint ref_count;
226 GPtrArray *pending_dispatches;
227 gint timeout; /* Timeout for current iteration */
229 guint next_id;
230 GSource *source_list;
231 gint in_check_or_prepare;
233 GPollRec *poll_records, *poll_records_tail;
234 guint n_poll_records;
235 GPollFD *cached_poll_array;
236 guint cached_poll_array_size;
238 #ifdef G_THREADS_ENABLED
239 #ifndef G_OS_WIN32
240 /* this pipe is used to wake up the main loop when a source is added.
242 gint wake_up_pipe[2];
243 #else /* G_OS_WIN32 */
244 HANDLE wake_up_semaphore;
245 #endif /* G_OS_WIN32 */
247 GPollFD wake_up_rec;
248 gboolean poll_waiting;
250 /* Flag indicating whether the set of fd's changed during a poll */
251 gboolean poll_changed;
252 #endif /* G_THREADS_ENABLED */
254 GPollFunc poll_func;
256 gint64 time;
257 gboolean time_is_fresh;
258 gint64 real_time;
259 gboolean real_time_is_fresh;
262 struct _GSourceCallback
264 guint ref_count;
265 GSourceFunc func;
266 gpointer data;
267 GDestroyNotify notify;
270 struct _GMainLoop
272 GMainContext *context;
273 gboolean is_running;
274 gint ref_count;
277 struct _GTimeoutSource
279 GSource source;
280 gint64 expiration;
281 guint interval;
282 gboolean seconds;
285 struct _GChildWatchSource
287 GSource source;
288 GPid pid;
289 gint child_status;
290 #ifdef G_OS_WIN32
291 GPollFD poll;
292 #else /* G_OS_WIN32 */
293 gint count;
294 gboolean child_exited;
295 #endif /* G_OS_WIN32 */
298 struct _GUnixSignalWatchSource
300 GSource source;
301 int signum;
302 gboolean pending;
305 struct _GPollRec
307 GPollFD *fd;
308 GPollRec *prev;
309 GPollRec *next;
310 gint priority;
313 struct _GSourcePrivate
315 GSList *child_sources;
316 GSource *parent_source;
319 #ifdef G_THREADS_ENABLED
320 #define LOCK_CONTEXT(context) g_static_mutex_lock (&context->mutex)
321 #define UNLOCK_CONTEXT(context) g_static_mutex_unlock (&context->mutex)
322 #define G_THREAD_SELF g_thread_self ()
323 #else
324 #define LOCK_CONTEXT(context) (void)0
325 #define UNLOCK_CONTEXT(context) (void)0
326 #define G_THREAD_SELF NULL
327 #endif
329 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
330 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
331 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
333 #define SOURCE_UNREF(source, context) \
334 G_STMT_START { \
335 if ((source)->ref_count > 1) \
336 (source)->ref_count--; \
337 else \
338 g_source_unref_internal ((source), (context), TRUE); \
339 } G_STMT_END
342 /* Forward declarations */
344 static void g_source_unref_internal (GSource *source,
345 GMainContext *context,
346 gboolean have_lock);
347 static void g_source_destroy_internal (GSource *source,
348 GMainContext *context,
349 gboolean have_lock);
350 static void g_source_set_priority_unlocked (GSource *source,
351 GMainContext *context,
352 gint priority);
353 static void g_main_context_poll (GMainContext *context,
354 gint timeout,
355 gint priority,
356 GPollFD *fds,
357 gint n_fds);
358 static void g_main_context_add_poll_unlocked (GMainContext *context,
359 gint priority,
360 GPollFD *fd);
361 static void g_main_context_remove_poll_unlocked (GMainContext *context,
362 GPollFD *fd);
363 static void g_main_context_wakeup_unlocked (GMainContext *context);
365 static void _g_main_wake_up_all_contexts (void);
367 static gboolean g_timeout_prepare (GSource *source,
368 gint *timeout);
369 static gboolean g_timeout_check (GSource *source);
370 static gboolean g_timeout_dispatch (GSource *source,
371 GSourceFunc callback,
372 gpointer user_data);
373 static gboolean g_child_watch_prepare (GSource *source,
374 gint *timeout);
375 static gboolean g_child_watch_check (GSource *source);
376 static gboolean g_child_watch_dispatch (GSource *source,
377 GSourceFunc callback,
378 gpointer user_data);
379 #ifdef G_OS_UNIX
380 static gpointer unix_signal_helper_thread (gpointer data) G_GNUC_NORETURN;
381 static void g_unix_signal_handler (int signum);
382 static gboolean g_unix_signal_watch_prepare (GSource *source,
383 gint *timeout);
384 static gboolean g_unix_signal_watch_check (GSource *source);
385 static gboolean g_unix_signal_watch_dispatch (GSource *source,
386 GSourceFunc callback,
387 gpointer user_data);
388 static void g_unix_signal_watch_finalize (GSource *source);
389 #endif
390 static gboolean g_idle_prepare (GSource *source,
391 gint *timeout);
392 static gboolean g_idle_check (GSource *source);
393 static gboolean g_idle_dispatch (GSource *source,
394 GSourceFunc callback,
395 gpointer user_data);
397 G_LOCK_DEFINE_STATIC (main_loop);
398 static GMainContext *default_main_context;
399 static GSList *main_contexts_without_pipe = NULL;
401 #ifndef G_OS_WIN32
403 /* The UNIX signal pipe contains a single byte specifying which
404 * signal was received.
406 #define _UNIX_SIGNAL_PIPE_SIGCHLD_CHAR 'C'
407 #define _UNIX_SIGNAL_PIPE_SIGHUP_CHAR 'H'
408 #define _UNIX_SIGNAL_PIPE_SIGINT_CHAR 'I'
409 #define _UNIX_SIGNAL_PIPE_SIGTERM_CHAR 'T'
410 /* Guards all the data below */
411 G_LOCK_DEFINE_STATIC (unix_signal_lock);
412 enum {
413 UNIX_SIGNAL_UNINITIALIZED = 0,
414 UNIX_SIGNAL_INITIALIZED_SINGLE,
415 UNIX_SIGNAL_INITIALIZED_THREADED
417 static gint unix_signal_init_state = UNIX_SIGNAL_UNINITIALIZED;
418 typedef struct {
419 /* These are only used in the UNIX_SIGNAL_INITIALIZED_SINGLE case */
420 gboolean sighup_delivered : 1;
421 gboolean sigint_delivered : 1;
422 gboolean sigterm_delivered : 1;
423 } UnixSignalState;
424 static sigset_t unix_signal_mask;
425 static UnixSignalState unix_signal_state;
426 static gint unix_signal_wake_up_pipe[2];
427 GSList *unix_signal_watches;
429 /* Not guarded ( FIXME should it be? ) */
430 static gint child_watch_count = 1;
432 static GSourceFuncs g_unix_signal_funcs =
434 g_unix_signal_watch_prepare,
435 g_unix_signal_watch_check,
436 g_unix_signal_watch_dispatch,
437 g_unix_signal_watch_finalize
439 #endif /* !G_OS_WIN32 */
440 G_LOCK_DEFINE_STATIC (main_context_list);
441 static GSList *main_context_list = NULL;
443 GSourceFuncs g_timeout_funcs =
445 g_timeout_prepare,
446 g_timeout_check,
447 g_timeout_dispatch,
448 NULL
451 GSourceFuncs g_child_watch_funcs =
453 g_child_watch_prepare,
454 g_child_watch_check,
455 g_child_watch_dispatch,
456 NULL
459 GSourceFuncs g_idle_funcs =
461 g_idle_prepare,
462 g_idle_check,
463 g_idle_dispatch,
464 NULL
468 * g_main_context_ref:
469 * @context: a #GMainContext
471 * Increases the reference count on a #GMainContext object by one.
473 * Returns: the @context that was passed in (since 2.6)
475 GMainContext *
476 g_main_context_ref (GMainContext *context)
478 g_return_val_if_fail (context != NULL, NULL);
479 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
481 g_atomic_int_inc (&context->ref_count);
483 return context;
486 static inline void
487 poll_rec_list_free (GMainContext *context,
488 GPollRec *list)
490 g_slice_free_chain (GPollRec, list, next);
494 * g_main_context_unref:
495 * @context: a #GMainContext
497 * Decreases the reference count on a #GMainContext object by one. If
498 * the result is zero, free the context and free all associated memory.
500 void
501 g_main_context_unref (GMainContext *context)
503 GSource *source;
504 g_return_if_fail (context != NULL);
505 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
507 if (!g_atomic_int_dec_and_test (&context->ref_count))
508 return;
510 G_LOCK (main_context_list);
511 main_context_list = g_slist_remove (main_context_list, context);
512 G_UNLOCK (main_context_list);
514 source = context->source_list;
515 while (source)
517 GSource *next = source->next;
518 g_source_destroy_internal (source, context, FALSE);
519 source = next;
522 #ifdef G_THREADS_ENABLED
523 g_static_mutex_free (&context->mutex);
524 #endif
526 g_ptr_array_free (context->pending_dispatches, TRUE);
527 g_free (context->cached_poll_array);
529 poll_rec_list_free (context, context->poll_records);
531 #ifdef G_THREADS_ENABLED
532 if (g_thread_supported())
534 #ifndef G_OS_WIN32
535 if (context->wake_up_pipe[0] != -1)
536 close (context->wake_up_pipe[0]);
537 if (context->wake_up_pipe[1] != -1)
538 close (context->wake_up_pipe[1]);
539 #else
540 CloseHandle (context->wake_up_semaphore);
541 #endif
543 else
544 main_contexts_without_pipe = g_slist_remove (main_contexts_without_pipe,
545 context);
547 if (context->cond != NULL)
548 g_cond_free (context->cond);
549 #endif
551 g_free (context);
554 #ifdef G_THREADS_ENABLED
555 static void
556 g_main_context_init_pipe (GMainContext *context)
558 GError *error = NULL;
560 # ifndef G_OS_WIN32
561 if (context->wake_up_pipe[0] != -1)
562 return;
564 #ifdef HAVE_EVENTFD
566 int efd;
568 efd = eventfd (0, EFD_CLOEXEC);
569 /* Fall through on -EINVAL too in case kernel doesn't know EFD_CLOEXEC. Bug #653570 */
570 if (efd == -1 && (errno == ENOSYS || errno == EINVAL))
572 if (!g_unix_open_pipe (context->wake_up_pipe, FD_CLOEXEC, &error))
573 g_error ("Cannot create pipe main loop wake-up: %s", error->message);
575 else if (efd >= 0)
577 context->wake_up_pipe[0] = efd;
579 else
580 g_error ("Cannot create eventfd for main loop wake-up: %s", g_strerror (errno));
582 #else
583 if (!g_unix_open_pipe (context->wake_up_pipe, FD_CLOEXEC, &error))
584 g_error ("Cannot create pipe main loop wake-up: %s", error->message);
585 #endif
587 context->wake_up_rec.fd = context->wake_up_pipe[0];
588 context->wake_up_rec.events = G_IO_IN;
589 # else
590 if (context->wake_up_semaphore != NULL)
591 return;
592 context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
593 if (context->wake_up_semaphore == NULL)
594 g_error ("Cannot create wake-up semaphore: %s",
595 g_win32_error_message (GetLastError ()));
596 context->wake_up_rec.fd = (gintptr) context->wake_up_semaphore;
597 context->wake_up_rec.events = G_IO_IN;
599 if (_g_main_poll_debug)
600 g_print ("wake-up semaphore: %p\n", context->wake_up_semaphore);
601 # endif
602 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
605 void
606 _g_main_thread_init (void)
608 GSList *curr;
610 curr = main_contexts_without_pipe;
611 while (curr)
613 g_main_context_init_pipe ((GMainContext *)curr->data);
614 curr = curr->next;
616 g_slist_free (main_contexts_without_pipe);
617 main_contexts_without_pipe = NULL;
619 #endif /* G_THREADS_ENABLED */
622 * g_main_context_new:
624 * Creates a new #GMainContext structure.
626 * Return value: the new #GMainContext
628 GMainContext *
629 g_main_context_new (void)
631 GMainContext *context = g_new0 (GMainContext, 1);
633 #ifdef G_MAIN_POLL_DEBUG
635 static gboolean beenhere = FALSE;
637 if (!beenhere)
639 if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
640 _g_main_poll_debug = TRUE;
641 beenhere = TRUE;
644 #endif
646 #ifdef G_THREADS_ENABLED
647 g_static_mutex_init (&context->mutex);
649 context->owner = NULL;
650 context->waiters = NULL;
652 # ifndef G_OS_WIN32
653 context->wake_up_pipe[0] = -1;
654 context->wake_up_pipe[1] = -1;
655 # else
656 context->wake_up_semaphore = NULL;
657 # endif
658 #endif
660 context->ref_count = 1;
662 context->next_id = 1;
664 context->source_list = NULL;
666 context->poll_func = g_poll;
668 context->cached_poll_array = NULL;
669 context->cached_poll_array_size = 0;
671 context->pending_dispatches = g_ptr_array_new ();
673 context->time_is_fresh = FALSE;
674 context->real_time_is_fresh = FALSE;
676 #ifdef G_THREADS_ENABLED
677 if (g_thread_supported ())
678 g_main_context_init_pipe (context);
679 else
680 main_contexts_without_pipe = g_slist_prepend (main_contexts_without_pipe,
681 context);
682 #endif
684 G_LOCK (main_context_list);
685 main_context_list = g_slist_append (main_context_list, context);
687 #ifdef G_MAIN_POLL_DEBUG
688 if (_g_main_poll_debug)
689 g_print ("created context=%p\n", context);
690 #endif
692 G_UNLOCK (main_context_list);
694 return context;
698 * g_main_context_default:
700 * Returns the global default main context. This is the main context
701 * used for main loop functions when a main loop is not explicitly
702 * specified, and corresponds to the "main" main loop. See also
703 * g_main_context_get_thread_default().
705 * Return value: the global default main context.
707 GMainContext *
708 g_main_context_default (void)
710 /* Slow, but safe */
712 G_LOCK (main_loop);
714 if (!default_main_context)
716 default_main_context = g_main_context_new ();
717 #ifdef G_MAIN_POLL_DEBUG
718 if (_g_main_poll_debug)
719 g_print ("default context=%p\n", default_main_context);
720 #endif
723 G_UNLOCK (main_loop);
725 return default_main_context;
728 static GStaticPrivate thread_context_stack = G_STATIC_PRIVATE_INIT;
730 static void
731 free_context_stack (gpointer data)
733 GQueue *stack = data;
734 GMainContext *context;
736 while (!g_queue_is_empty (stack))
738 context = g_queue_pop_head (stack);
739 g_main_context_release (context);
740 if (context)
741 g_main_context_unref (context);
743 g_queue_free (stack);
747 * g_main_context_push_thread_default:
748 * @context: a #GMainContext, or %NULL for the global default context
750 * Acquires @context and sets it as the thread-default context for the
751 * current thread. This will cause certain asynchronous operations
752 * (such as most <link linkend="gio">gio</link>-based I/O) which are
753 * started in this thread to run under @context and deliver their
754 * results to its main loop, rather than running under the global
755 * default context in the main thread. Note that calling this function
756 * changes the context returned by
757 * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
758 * one returned by g_main_context_default(), so it does not affect the
759 * context used by functions like g_idle_add().
761 * Normally you would call this function shortly after creating a new
762 * thread, passing it a #GMainContext which will be run by a
763 * #GMainLoop in that thread, to set a new default context for all
764 * async operations in that thread. (In this case, you don't need to
765 * ever call g_main_context_pop_thread_default().) In some cases
766 * however, you may want to schedule a single operation in a
767 * non-default context, or temporarily use a non-default context in
768 * the main thread. In that case, you can wrap the call to the
769 * asynchronous operation inside a
770 * g_main_context_push_thread_default() /
771 * g_main_context_pop_thread_default() pair, but it is up to you to
772 * ensure that no other asynchronous operations accidentally get
773 * started while the non-default context is active.
775 * Beware that libraries that predate this function may not correctly
776 * handle being used from a thread with a thread-default context. Eg,
777 * see g_file_supports_thread_contexts().
779 * Since: 2.22
781 void
782 g_main_context_push_thread_default (GMainContext *context)
784 GQueue *stack;
785 gboolean acquired_context;
787 acquired_context = g_main_context_acquire (context);
788 g_return_if_fail (acquired_context);
790 if (context == g_main_context_default ())
791 context = NULL;
792 else if (context)
793 g_main_context_ref (context);
795 stack = g_static_private_get (&thread_context_stack);
796 if (!stack)
798 stack = g_queue_new ();
799 g_static_private_set (&thread_context_stack, stack,
800 free_context_stack);
803 g_queue_push_head (stack, context);
807 * g_main_context_pop_thread_default:
808 * @context: a #GMainContext object, or %NULL
810 * Pops @context off the thread-default context stack (verifying that
811 * it was on the top of the stack).
813 * Since: 2.22
815 void
816 g_main_context_pop_thread_default (GMainContext *context)
818 GQueue *stack;
820 if (context == g_main_context_default ())
821 context = NULL;
823 stack = g_static_private_get (&thread_context_stack);
825 g_return_if_fail (stack != NULL);
826 g_return_if_fail (g_queue_peek_head (stack) == context);
828 g_queue_pop_head (stack);
830 g_main_context_release (context);
831 if (context)
832 g_main_context_unref (context);
836 * g_main_context_get_thread_default:
838 * Gets the thread-default #GMainContext for this thread. Asynchronous
839 * operations that want to be able to be run in contexts other than
840 * the default one should call this method to get a #GMainContext to
841 * add their #GSource<!-- -->s to. (Note that even in single-threaded
842 * programs applications may sometimes want to temporarily push a
843 * non-default context, so it is not safe to assume that this will
844 * always return %NULL if threads are not initialized.)
846 * Returns: the thread-default #GMainContext, or %NULL if the
847 * thread-default context is the global default context.
849 * Since: 2.22
851 GMainContext *
852 g_main_context_get_thread_default (void)
854 GQueue *stack;
856 stack = g_static_private_get (&thread_context_stack);
857 if (stack)
858 return g_queue_peek_head (stack);
859 else
860 return NULL;
863 /* Hooks for adding to the main loop */
866 * g_source_new:
867 * @source_funcs: structure containing functions that implement
868 * the sources behavior.
869 * @struct_size: size of the #GSource structure to create.
871 * Creates a new #GSource structure. The size is specified to
872 * allow creating structures derived from #GSource that contain
873 * additional data. The size passed in must be at least
874 * <literal>sizeof (GSource)</literal>.
876 * The source will not initially be associated with any #GMainContext
877 * and must be added to one with g_source_attach() before it will be
878 * executed.
880 * Return value: the newly-created #GSource.
882 GSource *
883 g_source_new (GSourceFuncs *source_funcs,
884 guint struct_size)
886 GSource *source;
888 g_return_val_if_fail (source_funcs != NULL, NULL);
889 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
891 source = (GSource*) g_malloc0 (struct_size);
893 source->source_funcs = source_funcs;
894 source->ref_count = 1;
896 source->priority = G_PRIORITY_DEFAULT;
898 source->flags = G_HOOK_FLAG_ACTIVE;
900 /* NULL/0 initialization for all other fields */
902 return source;
905 /* Holds context's lock
907 static void
908 g_source_list_add (GSource *source,
909 GMainContext *context)
911 GSource *tmp_source, *last_source;
913 if (source->priv && source->priv->parent_source)
915 /* Put the source immediately before its parent */
916 tmp_source = source->priv->parent_source;
917 last_source = source->priv->parent_source->prev;
919 else
921 last_source = NULL;
922 tmp_source = context->source_list;
923 while (tmp_source && tmp_source->priority <= source->priority)
925 last_source = tmp_source;
926 tmp_source = tmp_source->next;
930 source->next = tmp_source;
931 if (tmp_source)
932 tmp_source->prev = source;
934 source->prev = last_source;
935 if (last_source)
936 last_source->next = source;
937 else
938 context->source_list = source;
941 /* Holds context's lock
943 static void
944 g_source_list_remove (GSource *source,
945 GMainContext *context)
947 if (source->prev)
948 source->prev->next = source->next;
949 else
950 context->source_list = source->next;
952 if (source->next)
953 source->next->prev = source->prev;
955 source->prev = NULL;
956 source->next = NULL;
959 static guint
960 g_source_attach_unlocked (GSource *source,
961 GMainContext *context)
963 guint result = 0;
964 GSList *tmp_list;
966 source->context = context;
967 result = source->source_id = context->next_id++;
969 source->ref_count++;
970 g_source_list_add (source, context);
972 tmp_list = source->poll_fds;
973 while (tmp_list)
975 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
976 tmp_list = tmp_list->next;
979 if (source->priv)
981 tmp_list = source->priv->child_sources;
982 while (tmp_list)
984 g_source_attach_unlocked (tmp_list->data, context);
985 tmp_list = tmp_list->next;
989 return result;
993 * g_source_attach:
994 * @source: a #GSource
995 * @context: a #GMainContext (if %NULL, the default context will be used)
997 * Adds a #GSource to a @context so that it will be executed within
998 * that context. Remove it by calling g_source_destroy().
1000 * Return value: the ID (greater than 0) for the source within the
1001 * #GMainContext.
1003 guint
1004 g_source_attach (GSource *source,
1005 GMainContext *context)
1007 guint result = 0;
1009 g_return_val_if_fail (source->context == NULL, 0);
1010 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
1012 if (!context)
1013 context = g_main_context_default ();
1015 LOCK_CONTEXT (context);
1017 result = g_source_attach_unlocked (source, context);
1019 #ifdef G_THREADS_ENABLED
1020 /* Now wake up the main loop if it is waiting in the poll() */
1021 g_main_context_wakeup_unlocked (context);
1022 #endif
1024 UNLOCK_CONTEXT (context);
1026 return result;
1029 static void
1030 g_source_destroy_internal (GSource *source,
1031 GMainContext *context,
1032 gboolean have_lock)
1034 if (!have_lock)
1035 LOCK_CONTEXT (context);
1037 if (!SOURCE_DESTROYED (source))
1039 GSList *tmp_list;
1040 gpointer old_cb_data;
1041 GSourceCallbackFuncs *old_cb_funcs;
1043 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1045 old_cb_data = source->callback_data;
1046 old_cb_funcs = source->callback_funcs;
1048 source->callback_data = NULL;
1049 source->callback_funcs = NULL;
1051 if (old_cb_funcs)
1053 UNLOCK_CONTEXT (context);
1054 old_cb_funcs->unref (old_cb_data);
1055 LOCK_CONTEXT (context);
1058 if (!SOURCE_BLOCKED (source))
1060 tmp_list = source->poll_fds;
1061 while (tmp_list)
1063 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1064 tmp_list = tmp_list->next;
1068 if (source->priv && source->priv->child_sources)
1070 /* This is safe because even if a child_source finalizer or
1071 * closure notify tried to modify source->priv->child_sources
1072 * from outside the lock, it would fail since
1073 * SOURCE_DESTROYED(source) is now TRUE.
1075 tmp_list = source->priv->child_sources;
1076 while (tmp_list)
1078 g_source_destroy_internal (tmp_list->data, context, TRUE);
1079 g_source_unref_internal (tmp_list->data, context, TRUE);
1080 tmp_list = tmp_list->next;
1082 g_slist_free (source->priv->child_sources);
1083 source->priv->child_sources = NULL;
1086 g_source_unref_internal (source, context, TRUE);
1089 if (!have_lock)
1090 UNLOCK_CONTEXT (context);
1094 * g_source_destroy:
1095 * @source: a #GSource
1097 * Removes a source from its #GMainContext, if any, and mark it as
1098 * destroyed. The source cannot be subsequently added to another
1099 * context.
1101 void
1102 g_source_destroy (GSource *source)
1104 GMainContext *context;
1106 g_return_if_fail (source != NULL);
1108 context = source->context;
1110 if (context)
1111 g_source_destroy_internal (source, context, FALSE);
1112 else
1113 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1117 * g_source_get_id:
1118 * @source: a #GSource
1120 * Returns the numeric ID for a particular source. The ID of a source
1121 * is a positive integer which is unique within a particular main loop
1122 * context. The reverse
1123 * mapping from ID to source is done by g_main_context_find_source_by_id().
1125 * Return value: the ID (greater than 0) for the source
1127 guint
1128 g_source_get_id (GSource *source)
1130 guint result;
1132 g_return_val_if_fail (source != NULL, 0);
1133 g_return_val_if_fail (source->context != NULL, 0);
1135 LOCK_CONTEXT (source->context);
1136 result = source->source_id;
1137 UNLOCK_CONTEXT (source->context);
1139 return result;
1143 * g_source_get_context:
1144 * @source: a #GSource
1146 * Gets the #GMainContext with which the source is associated.
1147 * Calling this function on a destroyed source is an error.
1149 * Return value: the #GMainContext with which the source is associated,
1150 * or %NULL if the context has not yet been added
1151 * to a source.
1153 GMainContext *
1154 g_source_get_context (GSource *source)
1156 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1158 return source->context;
1162 * g_source_add_poll:
1163 * @source:a #GSource
1164 * @fd: a #GPollFD structure holding information about a file
1165 * descriptor to watch.
1167 * Adds a file descriptor to the set of file descriptors polled for
1168 * this source. This is usually combined with g_source_new() to add an
1169 * event source. The event source's check function will typically test
1170 * the @revents field in the #GPollFD struct and return %TRUE if events need
1171 * to be processed.
1173 void
1174 g_source_add_poll (GSource *source,
1175 GPollFD *fd)
1177 GMainContext *context;
1179 g_return_if_fail (source != NULL);
1180 g_return_if_fail (fd != NULL);
1181 g_return_if_fail (!SOURCE_DESTROYED (source));
1183 context = source->context;
1185 if (context)
1186 LOCK_CONTEXT (context);
1188 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1190 if (context)
1192 if (!SOURCE_BLOCKED (source))
1193 g_main_context_add_poll_unlocked (context, source->priority, fd);
1194 UNLOCK_CONTEXT (context);
1199 * g_source_remove_poll:
1200 * @source:a #GSource
1201 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1203 * Removes a file descriptor from the set of file descriptors polled for
1204 * this source.
1206 void
1207 g_source_remove_poll (GSource *source,
1208 GPollFD *fd)
1210 GMainContext *context;
1212 g_return_if_fail (source != NULL);
1213 g_return_if_fail (fd != NULL);
1214 g_return_if_fail (!SOURCE_DESTROYED (source));
1216 context = source->context;
1218 if (context)
1219 LOCK_CONTEXT (context);
1221 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1223 if (context)
1225 if (!SOURCE_BLOCKED (source))
1226 g_main_context_remove_poll_unlocked (context, fd);
1227 UNLOCK_CONTEXT (context);
1232 * g_source_add_child_source:
1233 * @source:a #GSource
1234 * @child_source: a second #GSource that @source should "poll"
1236 * Adds @child_source to @source as a "polled" source; when @source is
1237 * added to a #GMainContext, @child_source will be automatically added
1238 * with the same priority, when @child_source is triggered, it will
1239 * cause @source to dispatch (in addition to calling its own
1240 * callback), and when @source is destroyed, it will destroy
1241 * @child_source as well. (@source will also still be dispatched if
1242 * its own prepare/check functions indicate that it is ready.)
1244 * If you don't need @child_source to do anything on its own when it
1245 * triggers, you can call g_source_set_dummy_callback() on it to set a
1246 * callback that does nothing (except return %TRUE if appropriate).
1248 * @source will hold a reference on @child_source while @child_source
1249 * is attached to it.
1251 * Since: 2.28
1253 void
1254 g_source_add_child_source (GSource *source,
1255 GSource *child_source)
1257 GMainContext *context;
1259 g_return_if_fail (source != NULL);
1260 g_return_if_fail (child_source != NULL);
1261 g_return_if_fail (!SOURCE_DESTROYED (source));
1262 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1263 g_return_if_fail (child_source->context == NULL);
1264 g_return_if_fail (child_source->priv == NULL || child_source->priv->parent_source == NULL);
1266 context = source->context;
1268 if (context)
1269 LOCK_CONTEXT (context);
1271 if (!source->priv)
1272 source->priv = g_slice_new0 (GSourcePrivate);
1273 if (!child_source->priv)
1274 child_source->priv = g_slice_new0 (GSourcePrivate);
1276 source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1277 g_source_ref (child_source));
1278 child_source->priv->parent_source = source;
1279 g_source_set_priority_unlocked (child_source, context, source->priority);
1281 if (context)
1283 UNLOCK_CONTEXT (context);
1284 g_source_attach (child_source, context);
1289 * g_source_remove_child_source:
1290 * @source:a #GSource
1291 * @child_source: a #GSource previously passed to
1292 * g_source_add_child_source().
1294 * Detaches @child_source from @source and destroys it.
1296 * Since: 2.28
1298 void
1299 g_source_remove_child_source (GSource *source,
1300 GSource *child_source)
1302 GMainContext *context;
1304 g_return_if_fail (source != NULL);
1305 g_return_if_fail (child_source != NULL);
1306 g_return_if_fail (child_source->priv != NULL && child_source->priv->parent_source == source);
1307 g_return_if_fail (!SOURCE_DESTROYED (source));
1308 g_return_if_fail (!SOURCE_DESTROYED (child_source));
1310 context = source->context;
1312 if (context)
1313 LOCK_CONTEXT (context);
1315 source->priv->child_sources = g_slist_remove (source->priv->child_sources, child_source);
1316 g_source_destroy_internal (child_source, context, TRUE);
1317 g_source_unref_internal (child_source, context, TRUE);
1319 if (context)
1320 UNLOCK_CONTEXT (context);
1324 * g_source_set_callback_indirect:
1325 * @source: the source
1326 * @callback_data: pointer to callback data "object"
1327 * @callback_funcs: functions for reference counting @callback_data
1328 * and getting the callback and data
1330 * Sets the callback function storing the data as a refcounted callback
1331 * "object". This is used internally. Note that calling
1332 * g_source_set_callback_indirect() assumes
1333 * an initial reference count on @callback_data, and thus
1334 * @callback_funcs->unref will eventually be called once more
1335 * than @callback_funcs->ref.
1337 void
1338 g_source_set_callback_indirect (GSource *source,
1339 gpointer callback_data,
1340 GSourceCallbackFuncs *callback_funcs)
1342 GMainContext *context;
1343 gpointer old_cb_data;
1344 GSourceCallbackFuncs *old_cb_funcs;
1346 g_return_if_fail (source != NULL);
1347 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1349 context = source->context;
1351 if (context)
1352 LOCK_CONTEXT (context);
1354 old_cb_data = source->callback_data;
1355 old_cb_funcs = source->callback_funcs;
1357 source->callback_data = callback_data;
1358 source->callback_funcs = callback_funcs;
1360 if (context)
1361 UNLOCK_CONTEXT (context);
1363 if (old_cb_funcs)
1364 old_cb_funcs->unref (old_cb_data);
1367 static void
1368 g_source_callback_ref (gpointer cb_data)
1370 GSourceCallback *callback = cb_data;
1372 callback->ref_count++;
1376 static void
1377 g_source_callback_unref (gpointer cb_data)
1379 GSourceCallback *callback = cb_data;
1381 callback->ref_count--;
1382 if (callback->ref_count == 0)
1384 if (callback->notify)
1385 callback->notify (callback->data);
1386 g_free (callback);
1390 static void
1391 g_source_callback_get (gpointer cb_data,
1392 GSource *source,
1393 GSourceFunc *func,
1394 gpointer *data)
1396 GSourceCallback *callback = cb_data;
1398 *func = callback->func;
1399 *data = callback->data;
1402 static GSourceCallbackFuncs g_source_callback_funcs = {
1403 g_source_callback_ref,
1404 g_source_callback_unref,
1405 g_source_callback_get,
1409 * g_source_set_callback:
1410 * @source: the source
1411 * @func: a callback function
1412 * @data: the data to pass to callback function
1413 * @notify: a function to call when @data is no longer in use, or %NULL.
1415 * Sets the callback function for a source. The callback for a source is
1416 * called from the source's dispatch function.
1418 * The exact type of @func depends on the type of source; ie. you
1419 * should not count on @func being called with @data as its first
1420 * parameter.
1422 * Typically, you won't use this function. Instead use functions specific
1423 * to the type of source you are using.
1425 void
1426 g_source_set_callback (GSource *source,
1427 GSourceFunc func,
1428 gpointer data,
1429 GDestroyNotify notify)
1431 GSourceCallback *new_callback;
1433 g_return_if_fail (source != NULL);
1435 new_callback = g_new (GSourceCallback, 1);
1437 new_callback->ref_count = 1;
1438 new_callback->func = func;
1439 new_callback->data = data;
1440 new_callback->notify = notify;
1442 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1447 * g_source_set_funcs:
1448 * @source: a #GSource
1449 * @funcs: the new #GSourceFuncs
1451 * Sets the source functions (can be used to override
1452 * default implementations) of an unattached source.
1454 * Since: 2.12
1456 void
1457 g_source_set_funcs (GSource *source,
1458 GSourceFuncs *funcs)
1460 g_return_if_fail (source != NULL);
1461 g_return_if_fail (source->context == NULL);
1462 g_return_if_fail (source->ref_count > 0);
1463 g_return_if_fail (funcs != NULL);
1465 source->source_funcs = funcs;
1468 static void
1469 g_source_set_priority_unlocked (GSource *source,
1470 GMainContext *context,
1471 gint priority)
1473 GSList *tmp_list;
1475 source->priority = priority;
1477 if (context)
1479 /* Remove the source from the context's source and then
1480 * add it back so it is sorted in the correct place
1482 g_source_list_remove (source, source->context);
1483 g_source_list_add (source, source->context);
1485 if (!SOURCE_BLOCKED (source))
1487 tmp_list = source->poll_fds;
1488 while (tmp_list)
1490 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1491 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1493 tmp_list = tmp_list->next;
1498 if (source->priv && source->priv->child_sources)
1500 tmp_list = source->priv->child_sources;
1501 while (tmp_list)
1503 g_source_set_priority_unlocked (tmp_list->data, context, priority);
1504 tmp_list = tmp_list->next;
1510 * g_source_set_priority:
1511 * @source: a #GSource
1512 * @priority: the new priority.
1514 * Sets the priority of a source. While the main loop is being run, a
1515 * source will be dispatched if it is ready to be dispatched and no
1516 * sources at a higher (numerically smaller) priority are ready to be
1517 * dispatched.
1519 void
1520 g_source_set_priority (GSource *source,
1521 gint priority)
1523 GMainContext *context;
1525 g_return_if_fail (source != NULL);
1527 context = source->context;
1529 if (context)
1530 LOCK_CONTEXT (context);
1531 g_source_set_priority_unlocked (source, context, priority);
1532 if (context)
1533 UNLOCK_CONTEXT (source->context);
1537 * g_source_get_priority:
1538 * @source: a #GSource
1540 * Gets the priority of a source.
1542 * Return value: the priority of the source
1544 gint
1545 g_source_get_priority (GSource *source)
1547 g_return_val_if_fail (source != NULL, 0);
1549 return source->priority;
1553 * g_source_set_can_recurse:
1554 * @source: a #GSource
1555 * @can_recurse: whether recursion is allowed for this source
1557 * Sets whether a source can be called recursively. If @can_recurse is
1558 * %TRUE, then while the source is being dispatched then this source
1559 * will be processed normally. Otherwise, all processing of this
1560 * source is blocked until the dispatch function returns.
1562 void
1563 g_source_set_can_recurse (GSource *source,
1564 gboolean can_recurse)
1566 GMainContext *context;
1568 g_return_if_fail (source != NULL);
1570 context = source->context;
1572 if (context)
1573 LOCK_CONTEXT (context);
1575 if (can_recurse)
1576 source->flags |= G_SOURCE_CAN_RECURSE;
1577 else
1578 source->flags &= ~G_SOURCE_CAN_RECURSE;
1580 if (context)
1581 UNLOCK_CONTEXT (context);
1585 * g_source_get_can_recurse:
1586 * @source: a #GSource
1588 * Checks whether a source is allowed to be called recursively.
1589 * see g_source_set_can_recurse().
1591 * Return value: whether recursion is allowed.
1593 gboolean
1594 g_source_get_can_recurse (GSource *source)
1596 g_return_val_if_fail (source != NULL, FALSE);
1598 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1603 * g_source_set_name:
1604 * @source: a #GSource
1605 * @name: debug name for the source
1607 * Sets a name for the source, used in debugging and profiling.
1608 * The name defaults to #NULL.
1610 * The source name should describe in a human-readable way
1611 * what the source does. For example, "X11 event queue"
1612 * or "GTK+ repaint idle handler" or whatever it is.
1614 * It is permitted to call this function multiple times, but is not
1615 * recommended due to the potential performance impact. For example,
1616 * one could change the name in the "check" function of a #GSourceFuncs
1617 * to include details like the event type in the source name.
1619 * Since: 2.26
1621 void
1622 g_source_set_name (GSource *source,
1623 const char *name)
1625 g_return_if_fail (source != NULL);
1627 /* setting back to NULL is allowed, just because it's
1628 * weird if get_name can return NULL but you can't
1629 * set that.
1632 g_free (source->name);
1633 source->name = g_strdup (name);
1637 * g_source_get_name:
1638 * @source: a #GSource
1640 * Gets a name for the source, used in debugging and profiling.
1641 * The name may be #NULL if it has never been set with
1642 * g_source_set_name().
1644 * Return value: the name of the source
1645 * Since: 2.26
1647 const char *
1648 g_source_get_name (GSource *source)
1650 g_return_val_if_fail (source != NULL, NULL);
1652 return source->name;
1656 * g_source_set_name_by_id:
1657 * @tag: a #GSource ID
1658 * @name: debug name for the source
1660 * Sets the name of a source using its ID.
1662 * This is a convenience utility to set source names from the return
1663 * value of g_idle_add(), g_timeout_add(), etc.
1665 * Since: 2.26
1667 void
1668 g_source_set_name_by_id (guint tag,
1669 const char *name)
1671 GSource *source;
1673 g_return_if_fail (tag > 0);
1675 source = g_main_context_find_source_by_id (NULL, tag);
1676 if (source == NULL)
1677 return;
1679 g_source_set_name (source, name);
1684 * g_source_ref:
1685 * @source: a #GSource
1687 * Increases the reference count on a source by one.
1689 * Return value: @source
1691 GSource *
1692 g_source_ref (GSource *source)
1694 GMainContext *context;
1696 g_return_val_if_fail (source != NULL, NULL);
1698 context = source->context;
1700 if (context)
1701 LOCK_CONTEXT (context);
1703 source->ref_count++;
1705 if (context)
1706 UNLOCK_CONTEXT (context);
1708 return source;
1711 /* g_source_unref() but possible to call within context lock
1713 static void
1714 g_source_unref_internal (GSource *source,
1715 GMainContext *context,
1716 gboolean have_lock)
1718 gpointer old_cb_data = NULL;
1719 GSourceCallbackFuncs *old_cb_funcs = NULL;
1721 g_return_if_fail (source != NULL);
1723 if (!have_lock && context)
1724 LOCK_CONTEXT (context);
1726 source->ref_count--;
1727 if (source->ref_count == 0)
1729 old_cb_data = source->callback_data;
1730 old_cb_funcs = source->callback_funcs;
1732 source->callback_data = NULL;
1733 source->callback_funcs = NULL;
1735 if (context)
1737 if (!SOURCE_DESTROYED (source))
1738 g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
1739 g_source_list_remove (source, context);
1742 if (source->source_funcs->finalize)
1744 if (context)
1745 UNLOCK_CONTEXT (context);
1746 source->source_funcs->finalize (source);
1747 if (context)
1748 LOCK_CONTEXT (context);
1751 g_free (source->name);
1752 source->name = NULL;
1754 g_slist_free (source->poll_fds);
1755 source->poll_fds = NULL;
1757 if (source->priv)
1759 g_slice_free (GSourcePrivate, source->priv);
1760 source->priv = NULL;
1763 g_free (source);
1766 if (!have_lock && context)
1767 UNLOCK_CONTEXT (context);
1769 if (old_cb_funcs)
1771 if (have_lock)
1772 UNLOCK_CONTEXT (context);
1774 old_cb_funcs->unref (old_cb_data);
1776 if (have_lock)
1777 LOCK_CONTEXT (context);
1782 * g_source_unref:
1783 * @source: a #GSource
1785 * Decreases the reference count of a source by one. If the
1786 * resulting reference count is zero the source and associated
1787 * memory will be destroyed.
1789 void
1790 g_source_unref (GSource *source)
1792 g_return_if_fail (source != NULL);
1794 g_source_unref_internal (source, source->context, FALSE);
1798 * g_main_context_find_source_by_id:
1799 * @context: a #GMainContext (if %NULL, the default context will be used)
1800 * @source_id: the source ID, as returned by g_source_get_id().
1802 * Finds a #GSource given a pair of context and ID.
1804 * Return value: the #GSource if found, otherwise, %NULL
1806 GSource *
1807 g_main_context_find_source_by_id (GMainContext *context,
1808 guint source_id)
1810 GSource *source;
1812 g_return_val_if_fail (source_id > 0, NULL);
1814 if (context == NULL)
1815 context = g_main_context_default ();
1817 LOCK_CONTEXT (context);
1819 source = context->source_list;
1820 while (source)
1822 if (!SOURCE_DESTROYED (source) &&
1823 source->source_id == source_id)
1824 break;
1825 source = source->next;
1828 UNLOCK_CONTEXT (context);
1830 return source;
1834 * g_main_context_find_source_by_funcs_user_data:
1835 * @context: a #GMainContext (if %NULL, the default context will be used).
1836 * @funcs: the @source_funcs passed to g_source_new().
1837 * @user_data: the user data from the callback.
1839 * Finds a source with the given source functions and user data. If
1840 * multiple sources exist with the same source function and user data,
1841 * the first one found will be returned.
1843 * Return value: the source, if one was found, otherwise %NULL
1845 GSource *
1846 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1847 GSourceFuncs *funcs,
1848 gpointer user_data)
1850 GSource *source;
1852 g_return_val_if_fail (funcs != NULL, NULL);
1854 if (context == NULL)
1855 context = g_main_context_default ();
1857 LOCK_CONTEXT (context);
1859 source = context->source_list;
1860 while (source)
1862 if (!SOURCE_DESTROYED (source) &&
1863 source->source_funcs == funcs &&
1864 source->callback_funcs)
1866 GSourceFunc callback;
1867 gpointer callback_data;
1869 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1871 if (callback_data == user_data)
1872 break;
1874 source = source->next;
1877 UNLOCK_CONTEXT (context);
1879 return source;
1883 * g_main_context_find_source_by_user_data:
1884 * @context: a #GMainContext
1885 * @user_data: the user_data for the callback.
1887 * Finds a source with the given user data for the callback. If
1888 * multiple sources exist with the same user data, the first
1889 * one found will be returned.
1891 * Return value: the source, if one was found, otherwise %NULL
1893 GSource *
1894 g_main_context_find_source_by_user_data (GMainContext *context,
1895 gpointer user_data)
1897 GSource *source;
1899 if (context == NULL)
1900 context = g_main_context_default ();
1902 LOCK_CONTEXT (context);
1904 source = context->source_list;
1905 while (source)
1907 if (!SOURCE_DESTROYED (source) &&
1908 source->callback_funcs)
1910 GSourceFunc callback;
1911 gpointer callback_data = NULL;
1913 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1915 if (callback_data == user_data)
1916 break;
1918 source = source->next;
1921 UNLOCK_CONTEXT (context);
1923 return source;
1927 * g_source_remove:
1928 * @tag: the ID of the source to remove.
1930 * Removes the source with the given id from the default main context.
1931 * The id of
1932 * a #GSource is given by g_source_get_id(), or will be returned by the
1933 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1934 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1935 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1937 * See also g_source_destroy(). You must use g_source_destroy() for sources
1938 * added to a non-default main context.
1940 * Return value: %TRUE if the source was found and removed.
1942 gboolean
1943 g_source_remove (guint tag)
1945 GSource *source;
1947 g_return_val_if_fail (tag > 0, FALSE);
1949 source = g_main_context_find_source_by_id (NULL, tag);
1950 if (source)
1951 g_source_destroy (source);
1953 return source != NULL;
1957 * g_source_remove_by_user_data:
1958 * @user_data: the user_data for the callback.
1960 * Removes a source from the default main loop context given the user
1961 * data for the callback. If multiple sources exist with the same user
1962 * data, only one will be destroyed.
1964 * Return value: %TRUE if a source was found and removed.
1966 gboolean
1967 g_source_remove_by_user_data (gpointer user_data)
1969 GSource *source;
1971 source = g_main_context_find_source_by_user_data (NULL, user_data);
1972 if (source)
1974 g_source_destroy (source);
1975 return TRUE;
1977 else
1978 return FALSE;
1982 * g_source_remove_by_funcs_user_data:
1983 * @funcs: The @source_funcs passed to g_source_new()
1984 * @user_data: the user data for the callback
1986 * Removes a source from the default main loop context given the
1987 * source functions and user data. If multiple sources exist with the
1988 * same source functions and user data, only one will be destroyed.
1990 * Return value: %TRUE if a source was found and removed.
1992 gboolean
1993 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1994 gpointer user_data)
1996 GSource *source;
1998 g_return_val_if_fail (funcs != NULL, FALSE);
2000 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
2001 if (source)
2003 g_source_destroy (source);
2004 return TRUE;
2006 else
2007 return FALSE;
2011 * g_get_current_time:
2012 * @result: #GTimeVal structure in which to store current time.
2014 * Equivalent to the UNIX gettimeofday() function, but portable.
2016 * You may find g_get_real_time() to be more convenient.
2018 void
2019 g_get_current_time (GTimeVal *result)
2021 #ifndef G_OS_WIN32
2022 struct timeval r;
2024 g_return_if_fail (result != NULL);
2026 /*this is required on alpha, there the timeval structs are int's
2027 not longs and a cast only would fail horribly*/
2028 gettimeofday (&r, NULL);
2029 result->tv_sec = r.tv_sec;
2030 result->tv_usec = r.tv_usec;
2031 #else
2032 FILETIME ft;
2033 guint64 time64;
2035 g_return_if_fail (result != NULL);
2037 GetSystemTimeAsFileTime (&ft);
2038 memmove (&time64, &ft, sizeof (FILETIME));
2040 /* Convert from 100s of nanoseconds since 1601-01-01
2041 * to Unix epoch. Yes, this is Y2038 unsafe.
2043 time64 -= G_GINT64_CONSTANT (116444736000000000);
2044 time64 /= 10;
2046 result->tv_sec = time64 / 1000000;
2047 result->tv_usec = time64 % 1000000;
2048 #endif
2052 * g_get_real_time:
2054 * Queries the system wall-clock time.
2056 * This call is functionally equivalent to g_get_current_time() except
2057 * that the return value is often more convenient than dealing with a
2058 * #GTimeVal.
2060 * You should only use this call if you are actually interested in the real
2061 * wall-clock time. g_get_monotonic_time() is probably more useful for
2062 * measuring intervals.
2064 * Returns: the number of microseconds since January 1, 1970 UTC.
2066 * Since: 2.28
2068 gint64
2069 g_get_real_time (void)
2071 GTimeVal tv;
2073 g_get_current_time (&tv);
2075 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2079 * g_get_monotonic_time:
2081 * Queries the system monotonic time, if available.
2083 * On POSIX systems with clock_gettime() and %CLOCK_MONOTONIC this call
2084 * is a very shallow wrapper for that. Otherwise, we make a best effort
2085 * that probably involves returning the wall clock time (with at least
2086 * microsecond accuracy, subject to the limitations of the OS kernel).
2088 * Note that, on Windows, "limitations of the OS kernel" is a rather
2089 * substantial statement. Depending on the configuration of the system,
2090 * the wall clock time is updated as infrequently as 64 times a second
2091 * (which is approximately every 16ms).
2093 * Returns: the monotonic time, in microseconds
2095 * Since: 2.28
2097 gint64
2098 g_get_monotonic_time (void)
2100 #ifdef HAVE_CLOCK_GETTIME
2101 /* librt clock_gettime() is our first choice */
2103 static int clockid = CLOCK_REALTIME;
2104 struct timespec ts;
2106 #ifdef HAVE_MONOTONIC_CLOCK
2107 /* We have to check if we actually have monotonic clock support.
2109 * There is no thread safety issue here since there is no harm if we
2110 * check twice.
2113 static gboolean checked;
2115 if G_UNLIKELY (!checked)
2117 if (sysconf (_SC_MONOTONIC_CLOCK) >= 0)
2118 clockid = CLOCK_MONOTONIC;
2119 checked = TRUE;
2122 #endif
2124 clock_gettime (clockid, &ts);
2126 /* In theory monotonic time can have any epoch.
2128 * glib presently assumes the following:
2130 * 1) The epoch comes some time after the birth of Jesus of Nazareth, but
2131 * not more than 10000 years later.
2133 * 2) The current time also falls sometime within this range.
2135 * These two reasonable assumptions leave us with a maximum deviation from
2136 * the epoch of 10000 years, or 315569520000000000 seconds.
2138 * If we restrict ourselves to this range then the number of microseconds
2139 * will always fit well inside the constraints of a int64 (by a factor of
2140 * about 29).
2142 * If you actually hit the following assertion, probably you should file a
2143 * bug against your operating system for being excessively silly.
2145 g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts.tv_sec &&
2146 ts.tv_sec < G_GINT64_CONSTANT (315569520000000000));
2148 return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2150 #else
2151 /* It may look like we are discarding accuracy on Windows (since its
2152 * current time is expressed in 100s of nanoseconds) but according to
2153 * many sources, the time is only updated 64 times per second, so
2154 * microsecond accuracy is more than enough.
2157 GTimeVal tv;
2159 g_get_current_time (&tv);
2161 return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2163 #endif
2166 static void
2167 g_main_dispatch_free (gpointer dispatch)
2169 g_slice_free (GMainDispatch, dispatch);
2172 /* Running the main loop */
2174 static GMainDispatch *
2175 get_dispatch (void)
2177 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
2178 GMainDispatch *dispatch = g_static_private_get (&depth_private);
2179 if (!dispatch)
2181 dispatch = g_slice_new0 (GMainDispatch);
2182 g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
2185 return dispatch;
2189 * g_main_depth:
2191 * Returns the depth of the stack of calls to
2192 * g_main_context_dispatch() on any #GMainContext in the current thread.
2193 * That is, when called from the toplevel, it gives 0. When
2194 * called from within a callback from g_main_context_iteration()
2195 * (or g_main_loop_run(), etc.) it returns 1. When called from within
2196 * a callback to a recursive call to g_main_context_iteration(),
2197 * it returns 2. And so forth.
2199 * This function is useful in a situation like the following:
2200 * Imagine an extremely simple "garbage collected" system.
2202 * |[
2203 * static GList *free_list;
2205 * gpointer
2206 * allocate_memory (gsize size)
2207 * {
2208 * gpointer result = g_malloc (size);
2209 * free_list = g_list_prepend (free_list, result);
2210 * return result;
2213 * void
2214 * free_allocated_memory (void)
2216 * GList *l;
2217 * for (l = free_list; l; l = l->next);
2218 * g_free (l->data);
2219 * g_list_free (free_list);
2220 * free_list = NULL;
2223 * [...]
2225 * while (TRUE);
2227 * g_main_context_iteration (NULL, TRUE);
2228 * free_allocated_memory();
2230 * ]|
2232 * This works from an application, however, if you want to do the same
2233 * thing from a library, it gets more difficult, since you no longer
2234 * control the main loop. You might think you can simply use an idle
2235 * function to make the call to free_allocated_memory(), but that
2236 * doesn't work, since the idle function could be called from a
2237 * recursive callback. This can be fixed by using g_main_depth()
2239 * |[
2240 * gpointer
2241 * allocate_memory (gsize size)
2242 * {
2243 * FreeListBlock *block = g_new (FreeListBlock, 1);
2244 * block->mem = g_malloc (size);
2245 * block->depth = g_main_depth ();
2246 * free_list = g_list_prepend (free_list, block);
2247 * return block->mem;
2250 * void
2251 * free_allocated_memory (void)
2253 * GList *l;
2255 * int depth = g_main_depth ();
2256 * for (l = free_list; l; );
2258 * GList *next = l->next;
2259 * FreeListBlock *block = l->data;
2260 * if (block->depth > depth)
2262 * g_free (block->mem);
2263 * g_free (block);
2264 * free_list = g_list_delete_link (free_list, l);
2267 * l = next;
2270 * ]|
2272 * There is a temptation to use g_main_depth() to solve
2273 * problems with reentrancy. For instance, while waiting for data
2274 * to be received from the network in response to a menu item,
2275 * the menu item might be selected again. It might seem that
2276 * one could make the menu item's callback return immediately
2277 * and do nothing if g_main_depth() returns a value greater than 1.
2278 * However, this should be avoided since the user then sees selecting
2279 * the menu item do nothing. Furthermore, you'll find yourself adding
2280 * these checks all over your code, since there are doubtless many,
2281 * many things that the user could do. Instead, you can use the
2282 * following techniques:
2284 * <orderedlist>
2285 * <listitem>
2286 * <para>
2287 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
2288 * the user from interacting with elements while the main
2289 * loop is recursing.
2290 * </para>
2291 * </listitem>
2292 * <listitem>
2293 * <para>
2294 * Avoid main loop recursion in situations where you can't handle
2295 * arbitrary callbacks. Instead, structure your code so that you
2296 * simply return to the main loop and then get called again when
2297 * there is more work to do.
2298 * </para>
2299 * </listitem>
2300 * </orderedlist>
2302 * Return value: The main loop recursion level in the current thread
2305 g_main_depth (void)
2307 GMainDispatch *dispatch = get_dispatch ();
2308 return dispatch->depth;
2312 * g_main_current_source:
2314 * Returns the currently firing source for this thread.
2316 * Return value: The currently firing source or %NULL.
2318 * Since: 2.12
2320 GSource *
2321 g_main_current_source (void)
2323 GMainDispatch *dispatch = get_dispatch ();
2324 return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
2328 * g_source_is_destroyed:
2329 * @source: a #GSource
2331 * Returns whether @source has been destroyed.
2333 * This is important when you operate upon your objects
2334 * from within idle handlers, but may have freed the object
2335 * before the dispatch of your idle handler.
2337 * |[
2338 * static gboolean
2339 * idle_callback (gpointer data)
2341 * SomeWidget *self = data;
2343 * GDK_THREADS_ENTER (<!-- -->);
2344 * /<!-- -->* do stuff with self *<!-- -->/
2345 * self->idle_id = 0;
2346 * GDK_THREADS_LEAVE (<!-- -->);
2348 * return FALSE;
2351 * static void
2352 * some_widget_do_stuff_later (SomeWidget *self)
2354 * self->idle_id = g_idle_add (idle_callback, self);
2357 * static void
2358 * some_widget_finalize (GObject *object)
2360 * SomeWidget *self = SOME_WIDGET (object);
2362 * if (self->idle_id)
2363 * g_source_remove (self->idle_id);
2365 * G_OBJECT_CLASS (parent_class)->finalize (object);
2367 * ]|
2369 * This will fail in a multi-threaded application if the
2370 * widget is destroyed before the idle handler fires due
2371 * to the use after free in the callback. A solution, to
2372 * this particular problem, is to check to if the source
2373 * has already been destroy within the callback.
2375 * |[
2376 * static gboolean
2377 * idle_callback (gpointer data)
2379 * SomeWidget *self = data;
2381 * GDK_THREADS_ENTER ();
2382 * if (!g_source_is_destroyed (g_main_current_source ()))
2384 * /<!-- -->* do stuff with self *<!-- -->/
2386 * GDK_THREADS_LEAVE ();
2388 * return FALSE;
2390 * ]|
2392 * Return value: %TRUE if the source has been destroyed
2394 * Since: 2.12
2396 gboolean
2397 g_source_is_destroyed (GSource *source)
2399 return SOURCE_DESTROYED (source);
2402 /* Temporarily remove all this source's file descriptors from the
2403 * poll(), so that if data comes available for one of the file descriptors
2404 * we don't continually spin in the poll()
2406 /* HOLDS: source->context's lock */
2407 static void
2408 block_source (GSource *source)
2410 GSList *tmp_list;
2412 g_return_if_fail (!SOURCE_BLOCKED (source));
2414 tmp_list = source->poll_fds;
2415 while (tmp_list)
2417 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2418 tmp_list = tmp_list->next;
2422 /* HOLDS: source->context's lock */
2423 static void
2424 unblock_source (GSource *source)
2426 GSList *tmp_list;
2428 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
2429 g_return_if_fail (!SOURCE_DESTROYED (source));
2431 tmp_list = source->poll_fds;
2432 while (tmp_list)
2434 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2435 tmp_list = tmp_list->next;
2439 /* HOLDS: context's lock */
2440 static void
2441 g_main_dispatch (GMainContext *context)
2443 GMainDispatch *current = get_dispatch ();
2444 guint i;
2446 for (i = 0; i < context->pending_dispatches->len; i++)
2448 GSource *source = context->pending_dispatches->pdata[i];
2450 context->pending_dispatches->pdata[i] = NULL;
2451 g_assert (source);
2453 source->flags &= ~G_SOURCE_READY;
2455 if (!SOURCE_DESTROYED (source))
2457 gboolean was_in_call;
2458 gpointer user_data = NULL;
2459 GSourceFunc callback = NULL;
2460 GSourceCallbackFuncs *cb_funcs;
2461 gpointer cb_data;
2462 gboolean need_destroy;
2464 gboolean (*dispatch) (GSource *,
2465 GSourceFunc,
2466 gpointer);
2467 GSList current_source_link;
2469 dispatch = source->source_funcs->dispatch;
2470 cb_funcs = source->callback_funcs;
2471 cb_data = source->callback_data;
2473 if (cb_funcs)
2474 cb_funcs->ref (cb_data);
2476 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2477 block_source (source);
2479 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2480 source->flags |= G_HOOK_FLAG_IN_CALL;
2482 if (cb_funcs)
2483 cb_funcs->get (cb_data, source, &callback, &user_data);
2485 UNLOCK_CONTEXT (context);
2487 current->depth++;
2488 /* The on-stack allocation of the GSList is unconventional, but
2489 * we know that the lifetime of the link is bounded to this
2490 * function as the link is kept in a thread specific list and
2491 * not manipulated outside of this function and its descendants.
2492 * Avoiding the overhead of a g_slist_alloc() is useful as many
2493 * applications do little more than dispatch events.
2495 * This is a performance hack - do not revert to g_slist_prepend()!
2497 current_source_link.data = source;
2498 current_source_link.next = current->dispatching_sources;
2499 current->dispatching_sources = &current_source_link;
2500 need_destroy = ! dispatch (source,
2501 callback,
2502 user_data);
2503 g_assert (current->dispatching_sources == &current_source_link);
2504 current->dispatching_sources = current_source_link.next;
2505 current->depth--;
2507 if (cb_funcs)
2508 cb_funcs->unref (cb_data);
2510 LOCK_CONTEXT (context);
2512 if (!was_in_call)
2513 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2515 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2516 !SOURCE_DESTROYED (source))
2517 unblock_source (source);
2519 /* Note: this depends on the fact that we can't switch
2520 * sources from one main context to another
2522 if (need_destroy && !SOURCE_DESTROYED (source))
2524 g_assert (source->context == context);
2525 g_source_destroy_internal (source, context, TRUE);
2529 SOURCE_UNREF (source, context);
2532 g_ptr_array_set_size (context->pending_dispatches, 0);
2535 /* Holds context's lock */
2536 static inline GSource *
2537 next_valid_source (GMainContext *context,
2538 GSource *source)
2540 GSource *new_source = source ? source->next : context->source_list;
2542 while (new_source)
2544 if (!SOURCE_DESTROYED (new_source))
2546 new_source->ref_count++;
2547 break;
2550 new_source = new_source->next;
2553 if (source)
2554 SOURCE_UNREF (source, context);
2556 return new_source;
2560 * g_main_context_acquire:
2561 * @context: a #GMainContext
2563 * Tries to become the owner of the specified context.
2564 * If some other thread is the owner of the context,
2565 * returns %FALSE immediately. Ownership is properly
2566 * recursive: the owner can require ownership again
2567 * and will release ownership when g_main_context_release()
2568 * is called as many times as g_main_context_acquire().
2570 * You must be the owner of a context before you
2571 * can call g_main_context_prepare(), g_main_context_query(),
2572 * g_main_context_check(), g_main_context_dispatch().
2574 * Return value: %TRUE if the operation succeeded, and
2575 * this thread is now the owner of @context.
2577 gboolean
2578 g_main_context_acquire (GMainContext *context)
2580 #ifdef G_THREADS_ENABLED
2581 gboolean result = FALSE;
2582 GThread *self = G_THREAD_SELF;
2584 if (context == NULL)
2585 context = g_main_context_default ();
2587 LOCK_CONTEXT (context);
2589 if (!context->owner)
2591 context->owner = self;
2592 g_assert (context->owner_count == 0);
2595 if (context->owner == self)
2597 context->owner_count++;
2598 result = TRUE;
2601 UNLOCK_CONTEXT (context);
2603 return result;
2604 #else /* !G_THREADS_ENABLED */
2605 return TRUE;
2606 #endif /* G_THREADS_ENABLED */
2610 * g_main_context_release:
2611 * @context: a #GMainContext
2613 * Releases ownership of a context previously acquired by this thread
2614 * with g_main_context_acquire(). If the context was acquired multiple
2615 * times, the ownership will be released only when g_main_context_release()
2616 * is called as many times as it was acquired.
2618 void
2619 g_main_context_release (GMainContext *context)
2621 #ifdef G_THREADS_ENABLED
2622 if (context == NULL)
2623 context = g_main_context_default ();
2625 LOCK_CONTEXT (context);
2627 context->owner_count--;
2628 if (context->owner_count == 0)
2630 context->owner = NULL;
2632 if (context->waiters)
2634 GMainWaiter *waiter = context->waiters->data;
2635 gboolean loop_internal_waiter =
2636 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
2637 context->waiters = g_slist_delete_link (context->waiters,
2638 context->waiters);
2639 if (!loop_internal_waiter)
2640 g_mutex_lock (waiter->mutex);
2642 g_cond_signal (waiter->cond);
2644 if (!loop_internal_waiter)
2645 g_mutex_unlock (waiter->mutex);
2649 UNLOCK_CONTEXT (context);
2650 #endif /* G_THREADS_ENABLED */
2654 * g_main_context_wait:
2655 * @context: a #GMainContext
2656 * @cond: a condition variable
2657 * @mutex: a mutex, currently held
2659 * Tries to become the owner of the specified context,
2660 * as with g_main_context_acquire(). But if another thread
2661 * is the owner, atomically drop @mutex and wait on @cond until
2662 * that owner releases ownership or until @cond is signaled, then
2663 * try again (once) to become the owner.
2665 * Return value: %TRUE if the operation succeeded, and
2666 * this thread is now the owner of @context.
2668 gboolean
2669 g_main_context_wait (GMainContext *context,
2670 GCond *cond,
2671 GMutex *mutex)
2673 #ifdef G_THREADS_ENABLED
2674 gboolean result = FALSE;
2675 GThread *self = G_THREAD_SELF;
2676 gboolean loop_internal_waiter;
2678 if (context == NULL)
2679 context = g_main_context_default ();
2681 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2683 if (!loop_internal_waiter)
2684 LOCK_CONTEXT (context);
2686 if (context->owner && context->owner != self)
2688 GMainWaiter waiter;
2690 waiter.cond = cond;
2691 waiter.mutex = mutex;
2693 context->waiters = g_slist_append (context->waiters, &waiter);
2695 if (!loop_internal_waiter)
2696 UNLOCK_CONTEXT (context);
2697 g_cond_wait (cond, mutex);
2698 if (!loop_internal_waiter)
2699 LOCK_CONTEXT (context);
2701 context->waiters = g_slist_remove (context->waiters, &waiter);
2704 if (!context->owner)
2706 context->owner = self;
2707 g_assert (context->owner_count == 0);
2710 if (context->owner == self)
2712 context->owner_count++;
2713 result = TRUE;
2716 if (!loop_internal_waiter)
2717 UNLOCK_CONTEXT (context);
2719 return result;
2720 #else /* !G_THREADS_ENABLED */
2721 return TRUE;
2722 #endif /* G_THREADS_ENABLED */
2726 * g_main_context_prepare:
2727 * @context: a #GMainContext
2728 * @priority: location to store priority of highest priority
2729 * source already ready.
2731 * Prepares to poll sources within a main loop. The resulting information
2732 * for polling is determined by calling g_main_context_query ().
2734 * Return value: %TRUE if some source is ready to be dispatched
2735 * prior to polling.
2737 gboolean
2738 g_main_context_prepare (GMainContext *context,
2739 gint *priority)
2741 gint i;
2742 gint n_ready = 0;
2743 gint current_priority = G_MAXINT;
2744 GSource *source;
2746 if (context == NULL)
2747 context = g_main_context_default ();
2749 LOCK_CONTEXT (context);
2751 context->time_is_fresh = FALSE;
2752 context->real_time_is_fresh = FALSE;
2754 if (context->in_check_or_prepare)
2756 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2757 "prepare() member.");
2758 UNLOCK_CONTEXT (context);
2759 return FALSE;
2762 #ifdef G_THREADS_ENABLED
2763 if (context->poll_waiting)
2765 g_warning("g_main_context_prepare(): main loop already active in another thread");
2766 UNLOCK_CONTEXT (context);
2767 return FALSE;
2770 context->poll_waiting = TRUE;
2771 #endif /* G_THREADS_ENABLED */
2773 #if 0
2774 /* If recursing, finish up current dispatch, before starting over */
2775 if (context->pending_dispatches)
2777 if (dispatch)
2778 g_main_dispatch (context, &current_time);
2780 UNLOCK_CONTEXT (context);
2781 return TRUE;
2783 #endif
2785 /* If recursing, clear list of pending dispatches */
2787 for (i = 0; i < context->pending_dispatches->len; i++)
2789 if (context->pending_dispatches->pdata[i])
2790 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2792 g_ptr_array_set_size (context->pending_dispatches, 0);
2794 /* Prepare all sources */
2796 context->timeout = -1;
2798 source = next_valid_source (context, NULL);
2799 while (source)
2801 gint source_timeout = -1;
2803 if ((n_ready > 0) && (source->priority > current_priority))
2805 SOURCE_UNREF (source, context);
2806 break;
2808 if (SOURCE_BLOCKED (source))
2809 goto next;
2811 if (!(source->flags & G_SOURCE_READY))
2813 gboolean result;
2814 gboolean (*prepare) (GSource *source,
2815 gint *timeout);
2817 prepare = source->source_funcs->prepare;
2818 context->in_check_or_prepare++;
2819 UNLOCK_CONTEXT (context);
2821 result = (*prepare) (source, &source_timeout);
2823 LOCK_CONTEXT (context);
2824 context->in_check_or_prepare--;
2826 if (result)
2828 GSource *ready_source = source;
2830 while (ready_source)
2832 ready_source->flags |= G_SOURCE_READY;
2833 ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2838 if (source->flags & G_SOURCE_READY)
2840 n_ready++;
2841 current_priority = source->priority;
2842 context->timeout = 0;
2845 if (source_timeout >= 0)
2847 if (context->timeout < 0)
2848 context->timeout = source_timeout;
2849 else
2850 context->timeout = MIN (context->timeout, source_timeout);
2853 next:
2854 source = next_valid_source (context, source);
2857 UNLOCK_CONTEXT (context);
2859 if (priority)
2860 *priority = current_priority;
2862 return (n_ready > 0);
2866 * g_main_context_query:
2867 * @context: a #GMainContext
2868 * @max_priority: maximum priority source to check
2869 * @timeout_: location to store timeout to be used in polling
2870 * @fds: location to store #GPollFD records that need to be polled.
2871 * @n_fds: length of @fds.
2873 * Determines information necessary to poll this main loop.
2875 * Return value: the number of records actually stored in @fds,
2876 * or, if more than @n_fds records need to be stored, the number
2877 * of records that need to be stored.
2879 gint
2880 g_main_context_query (GMainContext *context,
2881 gint max_priority,
2882 gint *timeout,
2883 GPollFD *fds,
2884 gint n_fds)
2886 gint n_poll;
2887 GPollRec *pollrec;
2889 LOCK_CONTEXT (context);
2891 pollrec = context->poll_records;
2892 n_poll = 0;
2893 while (pollrec && max_priority >= pollrec->priority)
2895 /* We need to include entries with fd->events == 0 in the array because
2896 * otherwise if the application changes fd->events behind our back and
2897 * makes it non-zero, we'll be out of sync when we check the fds[] array.
2898 * (Changing fd->events after adding an FD wasn't an anticipated use of
2899 * this API, but it occurs in practice.) */
2900 if (n_poll < n_fds)
2902 fds[n_poll].fd = pollrec->fd->fd;
2903 /* In direct contradiction to the Unix98 spec, IRIX runs into
2904 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2905 * flags in the events field of the pollfd while it should
2906 * just ignoring them. So we mask them out here.
2908 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2909 fds[n_poll].revents = 0;
2912 pollrec = pollrec->next;
2913 n_poll++;
2916 #ifdef G_THREADS_ENABLED
2917 context->poll_changed = FALSE;
2918 #endif
2920 if (timeout)
2922 *timeout = context->timeout;
2923 if (*timeout != 0)
2925 context->time_is_fresh = FALSE;
2926 context->real_time_is_fresh = FALSE;
2930 UNLOCK_CONTEXT (context);
2932 return n_poll;
2936 * g_main_context_check:
2937 * @context: a #GMainContext
2938 * @max_priority: the maximum numerical priority of sources to check
2939 * @fds: array of #GPollFD's that was passed to the last call to
2940 * g_main_context_query()
2941 * @n_fds: return value of g_main_context_query()
2943 * Passes the results of polling back to the main loop.
2945 * Return value: %TRUE if some sources are ready to be dispatched.
2947 gboolean
2948 g_main_context_check (GMainContext *context,
2949 gint max_priority,
2950 GPollFD *fds,
2951 gint n_fds)
2953 GSource *source;
2954 GPollRec *pollrec;
2955 gint n_ready = 0;
2956 gint i;
2958 LOCK_CONTEXT (context);
2960 if (context->in_check_or_prepare)
2962 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2963 "prepare() member.");
2964 UNLOCK_CONTEXT (context);
2965 return FALSE;
2968 #ifdef G_THREADS_ENABLED
2969 if (!context->poll_waiting)
2971 #ifndef G_OS_WIN32
2972 #ifdef HAVE_EVENTFD
2973 if (context->wake_up_pipe[1] == -1)
2975 guint64 buf;
2976 read (context->wake_up_pipe[0], &buf, sizeof(guint64));
2978 else
2979 #endif
2981 gchar a;
2982 read (context->wake_up_pipe[0], &a, 1);
2984 #endif
2986 else
2987 context->poll_waiting = FALSE;
2989 /* If the set of poll file descriptors changed, bail out
2990 * and let the main loop rerun
2992 if (context->poll_changed)
2994 UNLOCK_CONTEXT (context);
2995 return FALSE;
2997 #endif /* G_THREADS_ENABLED */
2999 pollrec = context->poll_records;
3000 i = 0;
3001 while (i < n_fds)
3003 if (pollrec->fd->events)
3004 pollrec->fd->revents = fds[i].revents;
3006 pollrec = pollrec->next;
3007 i++;
3010 source = next_valid_source (context, NULL);
3011 while (source)
3013 if ((n_ready > 0) && (source->priority > max_priority))
3015 SOURCE_UNREF (source, context);
3016 break;
3018 if (SOURCE_BLOCKED (source))
3019 goto next;
3021 if (!(source->flags & G_SOURCE_READY))
3023 gboolean result;
3024 gboolean (*check) (GSource *source);
3026 check = source->source_funcs->check;
3028 context->in_check_or_prepare++;
3029 UNLOCK_CONTEXT (context);
3031 result = (*check) (source);
3033 LOCK_CONTEXT (context);
3034 context->in_check_or_prepare--;
3036 if (result)
3038 GSource *ready_source = source;
3040 while (ready_source)
3042 ready_source->flags |= G_SOURCE_READY;
3043 ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
3048 if (source->flags & G_SOURCE_READY)
3050 source->ref_count++;
3051 g_ptr_array_add (context->pending_dispatches, source);
3053 n_ready++;
3055 /* never dispatch sources with less priority than the first
3056 * one we choose to dispatch
3058 max_priority = source->priority;
3061 next:
3062 source = next_valid_source (context, source);
3065 UNLOCK_CONTEXT (context);
3067 return n_ready > 0;
3071 * g_main_context_dispatch:
3072 * @context: a #GMainContext
3074 * Dispatches all pending sources.
3076 void
3077 g_main_context_dispatch (GMainContext *context)
3079 LOCK_CONTEXT (context);
3081 if (context->pending_dispatches->len > 0)
3083 g_main_dispatch (context);
3086 UNLOCK_CONTEXT (context);
3089 /* HOLDS context lock */
3090 static gboolean
3091 g_main_context_iterate (GMainContext *context,
3092 gboolean block,
3093 gboolean dispatch,
3094 GThread *self)
3096 gint max_priority;
3097 gint timeout;
3098 gboolean some_ready;
3099 gint nfds, allocated_nfds;
3100 GPollFD *fds = NULL;
3102 UNLOCK_CONTEXT (context);
3104 #ifdef G_THREADS_ENABLED
3105 if (!g_main_context_acquire (context))
3107 gboolean got_ownership;
3109 LOCK_CONTEXT (context);
3111 g_return_val_if_fail (g_thread_supported (), FALSE);
3113 if (!block)
3114 return FALSE;
3116 if (!context->cond)
3117 context->cond = g_cond_new ();
3119 got_ownership = g_main_context_wait (context,
3120 context->cond,
3121 g_static_mutex_get_mutex (&context->mutex));
3123 if (!got_ownership)
3124 return FALSE;
3126 else
3127 LOCK_CONTEXT (context);
3128 #endif /* G_THREADS_ENABLED */
3130 if (!context->cached_poll_array)
3132 context->cached_poll_array_size = context->n_poll_records;
3133 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
3136 allocated_nfds = context->cached_poll_array_size;
3137 fds = context->cached_poll_array;
3139 UNLOCK_CONTEXT (context);
3141 g_main_context_prepare (context, &max_priority);
3143 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
3144 allocated_nfds)) > allocated_nfds)
3146 LOCK_CONTEXT (context);
3147 g_free (fds);
3148 context->cached_poll_array_size = allocated_nfds = nfds;
3149 context->cached_poll_array = fds = g_new (GPollFD, nfds);
3150 UNLOCK_CONTEXT (context);
3153 if (!block)
3154 timeout = 0;
3156 g_main_context_poll (context, timeout, max_priority, fds, nfds);
3158 some_ready = g_main_context_check (context, max_priority, fds, nfds);
3160 if (dispatch)
3161 g_main_context_dispatch (context);
3163 #ifdef G_THREADS_ENABLED
3164 g_main_context_release (context);
3165 #endif /* G_THREADS_ENABLED */
3167 LOCK_CONTEXT (context);
3169 return some_ready;
3173 * g_main_context_pending:
3174 * @context: a #GMainContext (if %NULL, the default context will be used)
3176 * Checks if any sources have pending events for the given context.
3178 * Return value: %TRUE if events are pending.
3180 gboolean
3181 g_main_context_pending (GMainContext *context)
3183 gboolean retval;
3185 if (!context)
3186 context = g_main_context_default();
3188 LOCK_CONTEXT (context);
3189 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3190 UNLOCK_CONTEXT (context);
3192 return retval;
3196 * g_main_context_iteration:
3197 * @context: a #GMainContext (if %NULL, the default context will be used)
3198 * @may_block: whether the call may block.
3200 * Runs a single iteration for the given main loop. This involves
3201 * checking to see if any event sources are ready to be processed,
3202 * then if no events sources are ready and @may_block is %TRUE, waiting
3203 * for a source to become ready, then dispatching the highest priority
3204 * events sources that are ready. Otherwise, if @may_block is %FALSE
3205 * sources are not waited to become ready, only those highest priority
3206 * events sources will be dispatched (if any), that are ready at this
3207 * given moment without further waiting.
3209 * Note that even when @may_block is %TRUE, it is still possible for
3210 * g_main_context_iteration() to return %FALSE, since the the wait may
3211 * be interrupted for other reasons than an event source becoming ready.
3213 * Return value: %TRUE if events were dispatched.
3215 gboolean
3216 g_main_context_iteration (GMainContext *context, gboolean may_block)
3218 gboolean retval;
3220 if (!context)
3221 context = g_main_context_default();
3223 LOCK_CONTEXT (context);
3224 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3225 UNLOCK_CONTEXT (context);
3227 return retval;
3231 * g_main_loop_new:
3232 * @context: (allow-none): a #GMainContext (if %NULL, the default context will be used).
3233 * @is_running: set to %TRUE to indicate that the loop is running. This
3234 * is not very important since calling g_main_loop_run() will set this to
3235 * %TRUE anyway.
3237 * Creates a new #GMainLoop structure.
3239 * Return value: a new #GMainLoop.
3241 GMainLoop *
3242 g_main_loop_new (GMainContext *context,
3243 gboolean is_running)
3245 GMainLoop *loop;
3247 if (!context)
3248 context = g_main_context_default();
3250 g_main_context_ref (context);
3252 loop = g_new0 (GMainLoop, 1);
3253 loop->context = context;
3254 loop->is_running = is_running != FALSE;
3255 loop->ref_count = 1;
3257 return loop;
3261 * g_main_loop_ref:
3262 * @loop: a #GMainLoop
3264 * Increases the reference count on a #GMainLoop object by one.
3266 * Return value: @loop
3268 GMainLoop *
3269 g_main_loop_ref (GMainLoop *loop)
3271 g_return_val_if_fail (loop != NULL, NULL);
3272 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3274 g_atomic_int_inc (&loop->ref_count);
3276 return loop;
3280 * g_main_loop_unref:
3281 * @loop: a #GMainLoop
3283 * Decreases the reference count on a #GMainLoop object by one. If
3284 * the result is zero, free the loop and free all associated memory.
3286 void
3287 g_main_loop_unref (GMainLoop *loop)
3289 g_return_if_fail (loop != NULL);
3290 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3292 if (!g_atomic_int_dec_and_test (&loop->ref_count))
3293 return;
3295 g_main_context_unref (loop->context);
3296 g_free (loop);
3300 * g_main_loop_run:
3301 * @loop: a #GMainLoop
3303 * Runs a main loop until g_main_loop_quit() is called on the loop.
3304 * If this is called for the thread of the loop's #GMainContext,
3305 * it will process events from the loop, otherwise it will
3306 * simply wait.
3308 void
3309 g_main_loop_run (GMainLoop *loop)
3311 GThread *self = G_THREAD_SELF;
3313 g_return_if_fail (loop != NULL);
3314 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3316 #ifdef G_THREADS_ENABLED
3317 if (!g_main_context_acquire (loop->context))
3319 gboolean got_ownership = FALSE;
3321 /* Another thread owns this context */
3322 if (!g_thread_supported ())
3324 g_warning ("g_main_loop_run() was called from second thread but "
3325 "g_thread_init() was never called.");
3326 return;
3329 LOCK_CONTEXT (loop->context);
3331 g_atomic_int_inc (&loop->ref_count);
3333 if (!loop->is_running)
3334 loop->is_running = TRUE;
3336 if (!loop->context->cond)
3337 loop->context->cond = g_cond_new ();
3339 while (loop->is_running && !got_ownership)
3340 got_ownership = g_main_context_wait (loop->context,
3341 loop->context->cond,
3342 g_static_mutex_get_mutex (&loop->context->mutex));
3344 if (!loop->is_running)
3346 UNLOCK_CONTEXT (loop->context);
3347 if (got_ownership)
3348 g_main_context_release (loop->context);
3349 g_main_loop_unref (loop);
3350 return;
3353 g_assert (got_ownership);
3355 else
3356 LOCK_CONTEXT (loop->context);
3357 #endif /* G_THREADS_ENABLED */
3359 if (loop->context->in_check_or_prepare)
3361 g_warning ("g_main_loop_run(): called recursively from within a source's "
3362 "check() or prepare() member, iteration not possible.");
3363 return;
3366 g_atomic_int_inc (&loop->ref_count);
3367 loop->is_running = TRUE;
3368 while (loop->is_running)
3369 g_main_context_iterate (loop->context, TRUE, TRUE, self);
3371 UNLOCK_CONTEXT (loop->context);
3373 #ifdef G_THREADS_ENABLED
3374 g_main_context_release (loop->context);
3375 #endif /* G_THREADS_ENABLED */
3377 g_main_loop_unref (loop);
3381 * g_main_loop_quit:
3382 * @loop: a #GMainLoop
3384 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3385 * for the loop will return.
3387 * Note that sources that have already been dispatched when
3388 * g_main_loop_quit() is called will still be executed.
3390 void
3391 g_main_loop_quit (GMainLoop *loop)
3393 g_return_if_fail (loop != NULL);
3394 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3396 LOCK_CONTEXT (loop->context);
3397 loop->is_running = FALSE;
3398 g_main_context_wakeup_unlocked (loop->context);
3400 #ifdef G_THREADS_ENABLED
3401 if (loop->context->cond)
3402 g_cond_broadcast (loop->context->cond);
3403 #endif /* G_THREADS_ENABLED */
3405 UNLOCK_CONTEXT (loop->context);
3409 * g_main_loop_is_running:
3410 * @loop: a #GMainLoop.
3412 * Checks to see if the main loop is currently being run via g_main_loop_run().
3414 * Return value: %TRUE if the mainloop is currently being run.
3416 gboolean
3417 g_main_loop_is_running (GMainLoop *loop)
3419 g_return_val_if_fail (loop != NULL, FALSE);
3420 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3422 return loop->is_running;
3426 * g_main_loop_get_context:
3427 * @loop: a #GMainLoop.
3429 * Returns the #GMainContext of @loop.
3431 * Return value: the #GMainContext of @loop
3433 GMainContext *
3434 g_main_loop_get_context (GMainLoop *loop)
3436 g_return_val_if_fail (loop != NULL, NULL);
3437 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3439 return loop->context;
3442 /* HOLDS: context's lock */
3443 static void
3444 g_main_context_poll (GMainContext *context,
3445 gint timeout,
3446 gint priority,
3447 GPollFD *fds,
3448 gint n_fds)
3450 #ifdef G_MAIN_POLL_DEBUG
3451 GTimer *poll_timer;
3452 GPollRec *pollrec;
3453 gint i;
3454 #endif
3456 GPollFunc poll_func;
3458 if (n_fds || timeout != 0)
3460 #ifdef G_MAIN_POLL_DEBUG
3461 if (_g_main_poll_debug)
3463 g_print ("polling context=%p n=%d timeout=%d\n",
3464 context, n_fds, timeout);
3465 poll_timer = g_timer_new ();
3467 #endif
3469 LOCK_CONTEXT (context);
3471 poll_func = context->poll_func;
3473 UNLOCK_CONTEXT (context);
3474 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3476 #ifndef G_OS_WIN32
3477 g_warning ("poll(2) failed due to: %s.",
3478 g_strerror (errno));
3479 #else
3480 /* If g_poll () returns -1, it has already called g_warning() */
3481 #endif
3484 #ifdef G_MAIN_POLL_DEBUG
3485 if (_g_main_poll_debug)
3487 LOCK_CONTEXT (context);
3489 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3490 n_fds,
3491 timeout,
3492 g_timer_elapsed (poll_timer, NULL));
3493 g_timer_destroy (poll_timer);
3494 pollrec = context->poll_records;
3496 while (pollrec != NULL)
3498 i = 0;
3499 while (i < n_fds)
3501 if (fds[i].fd == pollrec->fd->fd &&
3502 pollrec->fd->events &&
3503 fds[i].revents)
3505 g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3506 if (fds[i].revents & G_IO_IN)
3507 g_print ("i");
3508 if (fds[i].revents & G_IO_OUT)
3509 g_print ("o");
3510 if (fds[i].revents & G_IO_PRI)
3511 g_print ("p");
3512 if (fds[i].revents & G_IO_ERR)
3513 g_print ("e");
3514 if (fds[i].revents & G_IO_HUP)
3515 g_print ("h");
3516 if (fds[i].revents & G_IO_NVAL)
3517 g_print ("n");
3518 g_print ("]");
3520 i++;
3522 pollrec = pollrec->next;
3524 g_print ("\n");
3526 UNLOCK_CONTEXT (context);
3528 #endif
3529 } /* if (n_fds || timeout != 0) */
3533 * g_main_context_add_poll:
3534 * @context: a #GMainContext (or %NULL for the default context)
3535 * @fd: a #GPollFD structure holding information about a file
3536 * descriptor to watch.
3537 * @priority: the priority for this file descriptor which should be
3538 * the same as the priority used for g_source_attach() to ensure that the
3539 * file descriptor is polled whenever the results may be needed.
3541 * Adds a file descriptor to the set of file descriptors polled for
3542 * this context. This will very seldomly be used directly. Instead
3543 * a typical event source will use g_source_add_poll() instead.
3545 void
3546 g_main_context_add_poll (GMainContext *context,
3547 GPollFD *fd,
3548 gint priority)
3550 if (!context)
3551 context = g_main_context_default ();
3553 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3554 g_return_if_fail (fd);
3556 LOCK_CONTEXT (context);
3557 g_main_context_add_poll_unlocked (context, priority, fd);
3558 UNLOCK_CONTEXT (context);
3561 /* HOLDS: main_loop_lock */
3562 static void
3563 g_main_context_add_poll_unlocked (GMainContext *context,
3564 gint priority,
3565 GPollFD *fd)
3567 GPollRec *prevrec, *nextrec;
3568 GPollRec *newrec = g_slice_new (GPollRec);
3570 /* This file descriptor may be checked before we ever poll */
3571 fd->revents = 0;
3572 newrec->fd = fd;
3573 newrec->priority = priority;
3575 prevrec = context->poll_records_tail;
3576 nextrec = NULL;
3577 while (prevrec && priority < prevrec->priority)
3579 nextrec = prevrec;
3580 prevrec = prevrec->prev;
3583 if (prevrec)
3584 prevrec->next = newrec;
3585 else
3586 context->poll_records = newrec;
3588 newrec->prev = prevrec;
3589 newrec->next = nextrec;
3591 if (nextrec)
3592 nextrec->prev = newrec;
3593 else
3594 context->poll_records_tail = newrec;
3596 context->n_poll_records++;
3598 #ifdef G_THREADS_ENABLED
3599 context->poll_changed = TRUE;
3601 /* Now wake up the main loop if it is waiting in the poll() */
3602 g_main_context_wakeup_unlocked (context);
3603 #endif
3607 * g_main_context_remove_poll:
3608 * @context:a #GMainContext
3609 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3611 * Removes file descriptor from the set of file descriptors to be
3612 * polled for a particular context.
3614 void
3615 g_main_context_remove_poll (GMainContext *context,
3616 GPollFD *fd)
3618 if (!context)
3619 context = g_main_context_default ();
3621 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3622 g_return_if_fail (fd);
3624 LOCK_CONTEXT (context);
3625 g_main_context_remove_poll_unlocked (context, fd);
3626 UNLOCK_CONTEXT (context);
3629 static void
3630 g_main_context_remove_poll_unlocked (GMainContext *context,
3631 GPollFD *fd)
3633 GPollRec *pollrec, *prevrec, *nextrec;
3635 prevrec = NULL;
3636 pollrec = context->poll_records;
3638 while (pollrec)
3640 nextrec = pollrec->next;
3641 if (pollrec->fd == fd)
3643 if (prevrec != NULL)
3644 prevrec->next = nextrec;
3645 else
3646 context->poll_records = nextrec;
3648 if (nextrec != NULL)
3649 nextrec->prev = prevrec;
3650 else
3651 context->poll_records_tail = prevrec;
3653 g_slice_free (GPollRec, pollrec);
3655 context->n_poll_records--;
3656 break;
3658 prevrec = pollrec;
3659 pollrec = nextrec;
3662 #ifdef G_THREADS_ENABLED
3663 context->poll_changed = TRUE;
3665 /* Now wake up the main loop if it is waiting in the poll() */
3666 g_main_context_wakeup_unlocked (context);
3667 #endif
3671 * g_source_get_current_time:
3672 * @source: a #GSource
3673 * @timeval: #GTimeVal structure in which to store current time.
3675 * Gets the "current time" to be used when checking
3676 * this source. The advantage of calling this function over
3677 * calling g_get_current_time() directly is that when
3678 * checking multiple sources, GLib can cache a single value
3679 * instead of having to repeatedly get the system time.
3681 * Deprecated: 2.28: use g_source_get_time() instead
3683 void
3684 g_source_get_current_time (GSource *source,
3685 GTimeVal *timeval)
3687 GMainContext *context;
3689 g_return_if_fail (source->context != NULL);
3691 context = source->context;
3693 LOCK_CONTEXT (context);
3695 if (!context->real_time_is_fresh)
3697 context->real_time = g_get_real_time ();
3698 context->real_time_is_fresh = TRUE;
3701 timeval->tv_sec = context->real_time / 1000000;
3702 timeval->tv_usec = context->real_time % 1000000;
3704 UNLOCK_CONTEXT (context);
3708 * g_source_get_time:
3709 * @source: a #GSource
3711 * Gets the time to be used when checking this source. The advantage of
3712 * calling this function over calling g_get_monotonic_time() directly is
3713 * that when checking multiple sources, GLib can cache a single value
3714 * instead of having to repeatedly get the system monotonic time.
3716 * The time here is the system monotonic time, if available, or some
3717 * other reasonable alternative otherwise. See g_get_monotonic_time().
3719 * Returns: the monotonic time in microseconds
3721 * Since: 2.28
3723 gint64
3724 g_source_get_time (GSource *source)
3726 GMainContext *context;
3727 gint64 result;
3729 g_return_val_if_fail (source->context != NULL, 0);
3731 context = source->context;
3733 LOCK_CONTEXT (context);
3735 if (!context->time_is_fresh)
3737 context->time = g_get_monotonic_time ();
3738 context->time_is_fresh = TRUE;
3741 result = context->time;
3743 UNLOCK_CONTEXT (context);
3745 return result;
3749 * g_main_context_set_poll_func:
3750 * @context: a #GMainContext
3751 * @func: the function to call to poll all file descriptors
3753 * Sets the function to use to handle polling of file descriptors. It
3754 * will be used instead of the poll() system call
3755 * (or GLib's replacement function, which is used where
3756 * poll() isn't available).
3758 * This function could possibly be used to integrate the GLib event
3759 * loop with an external event loop.
3761 void
3762 g_main_context_set_poll_func (GMainContext *context,
3763 GPollFunc func)
3765 if (!context)
3766 context = g_main_context_default ();
3768 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3770 LOCK_CONTEXT (context);
3772 if (func)
3773 context->poll_func = func;
3774 else
3775 context->poll_func = g_poll;
3777 UNLOCK_CONTEXT (context);
3781 * g_main_context_get_poll_func:
3782 * @context: a #GMainContext
3784 * Gets the poll function set by g_main_context_set_poll_func().
3786 * Return value: the poll function
3788 GPollFunc
3789 g_main_context_get_poll_func (GMainContext *context)
3791 GPollFunc result;
3793 if (!context)
3794 context = g_main_context_default ();
3796 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3798 LOCK_CONTEXT (context);
3799 result = context->poll_func;
3800 UNLOCK_CONTEXT (context);
3802 return result;
3805 static void
3806 _g_main_wake_up_all_contexts (void)
3808 GSList *list;
3810 /* We were woken up. Wake up all other contexts in all other threads */
3811 G_LOCK (main_context_list);
3812 for (list = main_context_list; list; list = list->next)
3814 GMainContext *context = list->data;
3816 LOCK_CONTEXT (context);
3817 g_main_context_wakeup_unlocked (context);
3818 UNLOCK_CONTEXT (context);
3820 G_UNLOCK (main_context_list);
3824 /* HOLDS: context's lock */
3825 /* Wake the main loop up from a poll() */
3826 static void
3827 g_main_context_wakeup_unlocked (GMainContext *context)
3829 #ifdef G_THREADS_ENABLED
3830 if (g_thread_supported() && context->poll_waiting)
3832 context->poll_waiting = FALSE;
3833 #ifndef G_OS_WIN32
3834 #ifdef HAVE_EVENTFD
3835 if (context->wake_up_pipe[1] == -1)
3837 guint64 buf = 1;
3838 write (context->wake_up_pipe[0], &buf, sizeof(buf));
3840 else
3841 #endif
3842 write (context->wake_up_pipe[1], "A", 1);
3843 #else
3844 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
3845 #endif
3847 #endif
3851 * g_main_context_wakeup:
3852 * @context: a #GMainContext
3854 * If @context is currently waiting in a poll(), interrupt
3855 * the poll(), and continue the iteration process.
3857 void
3858 g_main_context_wakeup (GMainContext *context)
3860 if (!context)
3861 context = g_main_context_default ();
3863 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3865 LOCK_CONTEXT (context);
3866 g_main_context_wakeup_unlocked (context);
3867 UNLOCK_CONTEXT (context);
3871 * g_main_context_is_owner:
3872 * @context: a #GMainContext
3874 * Determines whether this thread holds the (recursive)
3875 * ownership of this #GMaincontext. This is useful to
3876 * know before waiting on another thread that may be
3877 * blocking to get ownership of @context.
3879 * Returns: %TRUE if current thread is owner of @context.
3881 * Since: 2.10
3883 gboolean
3884 g_main_context_is_owner (GMainContext *context)
3886 gboolean is_owner;
3888 if (!context)
3889 context = g_main_context_default ();
3891 #ifdef G_THREADS_ENABLED
3892 LOCK_CONTEXT (context);
3893 is_owner = context->owner == G_THREAD_SELF;
3894 UNLOCK_CONTEXT (context);
3895 #else
3896 is_owner = TRUE;
3897 #endif
3899 return is_owner;
3902 /* Timeouts */
3904 static void
3905 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3906 gint64 current_time)
3908 timeout_source->expiration = current_time +
3909 (guint64) timeout_source->interval * 1000;
3911 if (timeout_source->seconds)
3913 gint64 remainder;
3914 static gint timer_perturb = -1;
3916 if (timer_perturb == -1)
3919 * we want a per machine/session unique 'random' value; try the dbus
3920 * address first, that has a UUID in it. If there is no dbus, use the
3921 * hostname for hashing.
3923 const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3924 if (!session_bus_address)
3925 session_bus_address = g_getenv ("HOSTNAME");
3926 if (session_bus_address)
3927 timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
3928 else
3929 timer_perturb = 0;
3932 /* We want the microseconds part of the timeout to land on the
3933 * 'timer_perturb' mark, but we need to make sure we don't try to
3934 * set the timeout in the past. We do this by ensuring that we
3935 * always only *increase* the expiration time by adding a full
3936 * second in the case that the microsecond portion decreases.
3938 timeout_source->expiration -= timer_perturb;
3940 remainder = timeout_source->expiration % 1000000;
3941 if (remainder >= 1000000/4)
3942 timeout_source->expiration += 1000000;
3944 timeout_source->expiration -= remainder;
3945 timeout_source->expiration += timer_perturb;
3949 static gboolean
3950 g_timeout_prepare (GSource *source,
3951 gint *timeout)
3953 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3954 gint64 now = g_source_get_time (source);
3956 if (now < timeout_source->expiration)
3958 /* Round up to ensure that we don't try again too early */
3959 *timeout = (timeout_source->expiration - now + 999) / 1000;
3960 return FALSE;
3963 *timeout = 0;
3964 return TRUE;
3967 static gboolean
3968 g_timeout_check (GSource *source)
3970 GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3971 gint64 now = g_source_get_time (source);
3973 return timeout_source->expiration <= now;
3976 static gboolean
3977 g_timeout_dispatch (GSource *source,
3978 GSourceFunc callback,
3979 gpointer user_data)
3981 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3982 gboolean again;
3984 if (!callback)
3986 g_warning ("Timeout source dispatched without callback\n"
3987 "You must call g_source_set_callback().");
3988 return FALSE;
3991 again = callback (user_data);
3993 if (again)
3994 g_timeout_set_expiration (timeout_source, g_source_get_time (source));
3996 return again;
4000 * g_timeout_source_new:
4001 * @interval: the timeout interval in milliseconds.
4003 * Creates a new timeout source.
4005 * The source will not initially be associated with any #GMainContext
4006 * and must be added to one with g_source_attach() before it will be
4007 * executed.
4009 * Return value: the newly-created timeout source
4011 GSource *
4012 g_timeout_source_new (guint interval)
4014 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4015 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4017 timeout_source->interval = interval;
4018 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4020 return source;
4024 * g_timeout_source_new_seconds:
4025 * @interval: the timeout interval in seconds
4027 * Creates a new timeout source.
4029 * The source will not initially be associated with any #GMainContext
4030 * and must be added to one with g_source_attach() before it will be
4031 * executed.
4033 * The scheduling granularity/accuracy of this timeout source will be
4034 * in seconds.
4036 * Return value: the newly-created timeout source
4038 * Since: 2.14
4040 GSource *
4041 g_timeout_source_new_seconds (guint interval)
4043 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
4044 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
4046 timeout_source->interval = 1000 * interval;
4047 timeout_source->seconds = TRUE;
4049 g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
4051 return source;
4056 * g_timeout_add_full:
4057 * @priority: the priority of the timeout source. Typically this will be in
4058 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4059 * @interval: the time between calls to the function, in milliseconds
4060 * (1/1000ths of a second)
4061 * @function: function to call
4062 * @data: data to pass to @function
4063 * @notify: function to call when the timeout is removed, or %NULL
4065 * Sets a function to be called at regular intervals, with the given
4066 * priority. The function is called repeatedly until it returns
4067 * %FALSE, at which point the timeout is automatically destroyed and
4068 * the function will not be called again. The @notify function is
4069 * called when the timeout is destroyed. The first call to the
4070 * function will be at the end of the first @interval.
4072 * Note that timeout functions may be delayed, due to the processing of other
4073 * event sources. Thus they should not be relied on for precise timing.
4074 * After each call to the timeout function, the time of the next
4075 * timeout is recalculated based on the current time and the given interval
4076 * (it does not try to 'catch up' time lost in delays).
4078 * This internally creates a main loop source using g_timeout_source_new()
4079 * and attaches it to the main loop context using g_source_attach(). You can
4080 * do these steps manually if you need greater control.
4082 * Return value: the ID (greater than 0) of the event source.
4083 * Rename to: g_timeout_add
4085 guint
4086 g_timeout_add_full (gint priority,
4087 guint interval,
4088 GSourceFunc function,
4089 gpointer data,
4090 GDestroyNotify notify)
4092 GSource *source;
4093 guint id;
4095 g_return_val_if_fail (function != NULL, 0);
4097 source = g_timeout_source_new (interval);
4099 if (priority != G_PRIORITY_DEFAULT)
4100 g_source_set_priority (source, priority);
4102 g_source_set_callback (source, function, data, notify);
4103 id = g_source_attach (source, NULL);
4104 g_source_unref (source);
4106 return id;
4110 * g_timeout_add:
4111 * @interval: the time between calls to the function, in milliseconds
4112 * (1/1000ths of a second)
4113 * @function: function to call
4114 * @data: data to pass to @function
4116 * Sets a function to be called at regular intervals, with the default
4117 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
4118 * until it returns %FALSE, at which point the timeout is automatically
4119 * destroyed and the function will not be called again. The first call
4120 * to the function will be at the end of the first @interval.
4122 * Note that timeout functions may be delayed, due to the processing of other
4123 * event sources. Thus they should not be relied on for precise timing.
4124 * After each call to the timeout function, the time of the next
4125 * timeout is recalculated based on the current time and the given interval
4126 * (it does not try to 'catch up' time lost in delays).
4128 * If you want to have a timer in the "seconds" range and do not care
4129 * about the exact time of the first call of the timer, use the
4130 * g_timeout_add_seconds() function; this function allows for more
4131 * optimizations and more efficient system power usage.
4133 * This internally creates a main loop source using g_timeout_source_new()
4134 * and attaches it to the main loop context using g_source_attach(). You can
4135 * do these steps manually if you need greater control.
4137 * Return value: the ID (greater than 0) of the event source.
4139 guint
4140 g_timeout_add (guint32 interval,
4141 GSourceFunc function,
4142 gpointer data)
4144 return g_timeout_add_full (G_PRIORITY_DEFAULT,
4145 interval, function, data, NULL);
4149 * g_timeout_add_seconds_full:
4150 * @priority: the priority of the timeout source. Typically this will be in
4151 * the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4152 * @interval: the time between calls to the function, in seconds
4153 * @function: function to call
4154 * @data: data to pass to @function
4155 * @notify: function to call when the timeout is removed, or %NULL
4157 * Sets a function to be called at regular intervals, with @priority.
4158 * The function is called repeatedly until it returns %FALSE, at which
4159 * point the timeout is automatically destroyed and the function will
4160 * not be called again.
4162 * Unlike g_timeout_add(), this function operates at whole second granularity.
4163 * The initial starting point of the timer is determined by the implementation
4164 * and the implementation is expected to group multiple timers together so that
4165 * they fire all at the same time.
4166 * To allow this grouping, the @interval to the first timer is rounded
4167 * and can deviate up to one second from the specified interval.
4168 * Subsequent timer iterations will generally run at the specified interval.
4170 * Note that timeout functions may be delayed, due to the processing of other
4171 * event sources. Thus they should not be relied on for precise timing.
4172 * After each call to the timeout function, the time of the next
4173 * timeout is recalculated based on the current time and the given @interval
4175 * If you want timing more precise than whole seconds, use g_timeout_add()
4176 * instead.
4178 * The grouping of timers to fire at the same time results in a more power
4179 * and CPU efficient behavior so if your timer is in multiples of seconds
4180 * and you don't require the first timer exactly one second from now, the
4181 * use of g_timeout_add_seconds() is preferred over g_timeout_add().
4183 * This internally creates a main loop source using
4184 * g_timeout_source_new_seconds() and attaches it to the main loop context
4185 * using g_source_attach(). You can do these steps manually if you need
4186 * greater control.
4188 * Return value: the ID (greater than 0) of the event source.
4190 * Rename to: g_timeout_add_seconds
4191 * Since: 2.14
4193 guint
4194 g_timeout_add_seconds_full (gint priority,
4195 guint32 interval,
4196 GSourceFunc function,
4197 gpointer data,
4198 GDestroyNotify notify)
4200 GSource *source;
4201 guint id;
4203 g_return_val_if_fail (function != NULL, 0);
4205 source = g_timeout_source_new_seconds (interval);
4207 if (priority != G_PRIORITY_DEFAULT)
4208 g_source_set_priority (source, priority);
4210 g_source_set_callback (source, function, data, notify);
4211 id = g_source_attach (source, NULL);
4212 g_source_unref (source);
4214 return id;
4218 * g_timeout_add_seconds:
4219 * @interval: the time between calls to the function, in seconds
4220 * @function: function to call
4221 * @data: data to pass to @function
4223 * Sets a function to be called at regular intervals with the default
4224 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4225 * it returns %FALSE, at which point the timeout is automatically destroyed
4226 * and the function will not be called again.
4228 * This internally creates a main loop source using
4229 * g_timeout_source_new_seconds() and attaches it to the main loop context
4230 * using g_source_attach(). You can do these steps manually if you need
4231 * greater control. Also see g_timeout_add_seconds_full().
4233 * Note that the first call of the timer may not be precise for timeouts
4234 * of one second. If you need finer precision and have such a timeout,
4235 * you may want to use g_timeout_add() instead.
4237 * Return value: the ID (greater than 0) of the event source.
4239 * Since: 2.14
4241 guint
4242 g_timeout_add_seconds (guint interval,
4243 GSourceFunc function,
4244 gpointer data)
4246 g_return_val_if_fail (function != NULL, 0);
4248 return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4251 /* Child watch functions */
4253 #ifdef G_OS_WIN32
4255 static gboolean
4256 g_child_watch_prepare (GSource *source,
4257 gint *timeout)
4259 *timeout = -1;
4260 return FALSE;
4264 static gboolean
4265 g_child_watch_check (GSource *source)
4267 GChildWatchSource *child_watch_source;
4268 gboolean child_exited;
4270 child_watch_source = (GChildWatchSource *) source;
4272 child_exited = child_watch_source->poll.revents & G_IO_IN;
4274 if (child_exited)
4276 DWORD child_status;
4279 * Note: We do _not_ check for the special value of STILL_ACTIVE
4280 * since we know that the process has exited and doing so runs into
4281 * problems if the child process "happens to return STILL_ACTIVE(259)"
4282 * as Microsoft's Platform SDK puts it.
4284 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4286 gchar *emsg = g_win32_error_message (GetLastError ());
4287 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4288 g_free (emsg);
4290 child_watch_source->child_status = -1;
4292 else
4293 child_watch_source->child_status = child_status;
4296 return child_exited;
4299 #else /* G_OS_WIN32 */
4301 static gboolean
4302 check_for_child_exited (GSource *source)
4304 GChildWatchSource *child_watch_source;
4305 gint count;
4307 /* protect against another SIGCHLD in the middle of this call */
4308 count = child_watch_count;
4310 child_watch_source = (GChildWatchSource *) source;
4312 if (child_watch_source->child_exited)
4313 return TRUE;
4315 if (child_watch_source->count < count)
4317 gint child_status;
4319 if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
4321 child_watch_source->child_status = child_status;
4322 child_watch_source->child_exited = TRUE;
4324 child_watch_source->count = count;
4327 return child_watch_source->child_exited;
4330 static gboolean
4331 g_child_watch_prepare (GSource *source,
4332 gint *timeout)
4334 *timeout = -1;
4336 return check_for_child_exited (source);
4339 static gboolean
4340 g_child_watch_check (GSource *source)
4342 return check_for_child_exited (source);
4345 static gboolean
4346 check_for_signal_delivery (GSource *source)
4348 GUnixSignalWatchSource *unix_signal_source = (GUnixSignalWatchSource*) source;
4349 gboolean delivered;
4351 G_LOCK (unix_signal_lock);
4352 if (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_SINGLE)
4354 switch (unix_signal_source->signum)
4356 case SIGHUP:
4357 delivered = unix_signal_state.sighup_delivered;
4358 break;
4359 case SIGINT:
4360 delivered = unix_signal_state.sigint_delivered;
4361 break;
4362 case SIGTERM:
4363 delivered = unix_signal_state.sigterm_delivered;
4364 break;
4365 default:
4366 g_assert_not_reached ();
4367 delivered = FALSE;
4368 break;
4371 else
4373 g_assert (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_THREADED);
4374 delivered = unix_signal_source->pending;
4376 G_UNLOCK (unix_signal_lock);
4378 return delivered;
4381 static gboolean
4382 g_unix_signal_watch_prepare (GSource *source,
4383 gint *timeout)
4385 *timeout = -1;
4387 return check_for_signal_delivery (source);
4390 static gboolean
4391 g_unix_signal_watch_check (GSource *source)
4393 return check_for_signal_delivery (source);
4396 static gboolean
4397 g_unix_signal_watch_dispatch (GSource *source,
4398 GSourceFunc callback,
4399 gpointer user_data)
4401 GUnixSignalWatchSource *unix_signal_source;
4403 unix_signal_source = (GUnixSignalWatchSource *) source;
4405 if (!callback)
4407 g_warning ("Unix signal source dispatched without callback\n"
4408 "You must call g_source_set_callback().");
4409 return FALSE;
4412 (callback) (user_data);
4414 G_LOCK (unix_signal_lock);
4415 if (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_SINGLE)
4417 switch (unix_signal_source->signum)
4419 case SIGHUP:
4420 unix_signal_state.sighup_delivered = FALSE;
4421 break;
4422 case SIGINT:
4423 unix_signal_state.sigint_delivered = FALSE;
4424 break;
4425 case SIGTERM:
4426 unix_signal_state.sigterm_delivered = FALSE;
4427 break;
4430 else
4432 g_assert (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_THREADED);
4433 unix_signal_source->pending = FALSE;
4435 G_UNLOCK (unix_signal_lock);
4437 return TRUE;
4440 static void
4441 ensure_unix_signal_handler_installed_unlocked (int signum)
4443 struct sigaction action;
4444 GError *error = NULL;
4446 if (unix_signal_init_state == UNIX_SIGNAL_UNINITIALIZED)
4448 sigemptyset (&unix_signal_mask);
4451 if (unix_signal_init_state == UNIX_SIGNAL_UNINITIALIZED
4452 || unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_SINGLE)
4454 if (!g_thread_supported ())
4456 /* There is nothing to do for initializing in the non-threaded
4457 * case.
4459 if (unix_signal_init_state == UNIX_SIGNAL_UNINITIALIZED)
4460 unix_signal_init_state = UNIX_SIGNAL_INITIALIZED_SINGLE;
4462 else
4464 if (!g_unix_open_pipe (unix_signal_wake_up_pipe, FD_CLOEXEC, &error))
4465 g_error ("Cannot create UNIX signal wake up pipe: %s\n", error->message);
4466 g_unix_set_fd_nonblocking (unix_signal_wake_up_pipe[1], TRUE, NULL);
4468 /* We create a helper thread that polls on the wakeup pipe indefinitely */
4469 if (g_thread_create (unix_signal_helper_thread, NULL, FALSE, &error) == NULL)
4470 g_error ("Cannot create a thread to monitor UNIX signals: %s\n", error->message);
4472 unix_signal_init_state = UNIX_SIGNAL_INITIALIZED_THREADED;
4476 if (sigismember (&unix_signal_mask, signum))
4477 return;
4479 sigaddset (&unix_signal_mask, signum);
4481 action.sa_handler = g_unix_signal_handler;
4482 sigemptyset (&action.sa_mask);
4483 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4484 sigaction (signum, &action, NULL);
4487 GSource *
4488 _g_main_create_unix_signal_watch (int signum)
4490 GSource *source;
4491 GUnixSignalWatchSource *unix_signal_source;
4493 source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
4494 unix_signal_source = (GUnixSignalWatchSource *) source;
4496 unix_signal_source->signum = signum;
4497 unix_signal_source->pending = FALSE;
4499 G_LOCK (unix_signal_lock);
4500 ensure_unix_signal_handler_installed_unlocked (signum);
4501 unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
4502 G_UNLOCK (unix_signal_lock);
4504 return source;
4507 static void
4508 g_unix_signal_watch_finalize (GSource *source)
4510 G_LOCK (unix_signal_lock);
4511 unix_signal_watches = g_slist_remove (unix_signal_watches, source);
4512 G_UNLOCK (unix_signal_lock);
4515 #endif /* G_OS_WIN32 */
4517 static gboolean
4518 g_child_watch_dispatch (GSource *source,
4519 GSourceFunc callback,
4520 gpointer user_data)
4522 GChildWatchSource *child_watch_source;
4523 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
4525 child_watch_source = (GChildWatchSource *) source;
4527 if (!callback)
4529 g_warning ("Child watch source dispatched without callback\n"
4530 "You must call g_source_set_callback().");
4531 return FALSE;
4534 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
4536 /* We never keep a child watch source around as the child is gone */
4537 return FALSE;
4540 #ifndef G_OS_WIN32
4542 static void
4543 g_unix_signal_handler (int signum)
4545 if (signum == SIGCHLD)
4546 child_watch_count ++;
4548 if (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_THREADED)
4550 char buf[1];
4551 switch (signum)
4553 case SIGCHLD:
4554 buf[0] = _UNIX_SIGNAL_PIPE_SIGCHLD_CHAR;
4555 break;
4556 case SIGHUP:
4557 buf[0] = _UNIX_SIGNAL_PIPE_SIGHUP_CHAR;
4558 break;
4559 case SIGINT:
4560 buf[0] = _UNIX_SIGNAL_PIPE_SIGINT_CHAR;
4561 break;
4562 case SIGTERM:
4563 buf[0] = _UNIX_SIGNAL_PIPE_SIGTERM_CHAR;
4564 break;
4565 default:
4566 /* Shouldn't happen */
4567 return;
4569 write (unix_signal_wake_up_pipe[1], buf, 1);
4571 else
4573 /* We count on the signal interrupting the poll in the same thread. */
4574 switch (signum)
4576 case SIGCHLD:
4577 /* Nothing to do - the handler will call waitpid() */
4578 break;
4579 case SIGHUP:
4580 unix_signal_state.sighup_delivered = TRUE;
4581 break;
4582 case SIGINT:
4583 unix_signal_state.sigint_delivered = TRUE;
4584 break;
4585 case SIGTERM:
4586 unix_signal_state.sigterm_delivered = TRUE;
4587 break;
4588 default:
4589 g_assert_not_reached ();
4590 break;
4595 static void
4596 deliver_unix_signal (int signum)
4598 GSList *iter;
4599 g_assert (signum == SIGHUP || signum == SIGINT || signum == SIGTERM);
4601 G_LOCK (unix_signal_lock);
4602 for (iter = unix_signal_watches; iter; iter = iter->next)
4604 GUnixSignalWatchSource *source = iter->data;
4606 if (source->signum != signum)
4607 continue;
4609 source->pending = TRUE;
4611 G_UNLOCK (unix_signal_lock);
4615 * This thread is created whenever anything in GLib needs
4616 * to deal with UNIX signals; at present, just SIGCHLD
4617 * from g_child_watch_source_new().
4619 * Note: We could eventually make this thread a more public interface
4620 * and allow e.g. GDBus to use it instead of its own worker thread.
4622 static gpointer
4623 unix_signal_helper_thread (gpointer data)
4625 while (1)
4627 gchar b[128];
4628 ssize_t i, bytes_read;
4629 gboolean sigterm_received = FALSE;
4630 gboolean sigint_received = FALSE;
4631 gboolean sighup_received = FALSE;
4633 bytes_read = read (unix_signal_wake_up_pipe[0], b, sizeof (b));
4634 if (bytes_read < 0)
4636 g_warning ("Failed to read from child watch wake up pipe: %s",
4637 strerror (errno));
4638 /* Not much we can do here sanely; just wait a second and hope
4639 * it was transient.
4641 g_usleep (G_USEC_PER_SEC);
4642 continue;
4644 for (i = 0; i < bytes_read; i++)
4646 switch (b[i])
4648 case _UNIX_SIGNAL_PIPE_SIGCHLD_CHAR:
4649 /* The child watch source will call waitpid() in its
4650 * prepare() and check() methods; however, we don't
4651 * know which pid exited, so we need to wake up
4652 * all contexts. Note: actually we could get the pid
4653 * from the "siginfo_t" via the handler, but to pass
4654 * that info down the pipe would require a more structured
4655 * data stream (as opposed to a single byte).
4657 break;
4658 case _UNIX_SIGNAL_PIPE_SIGTERM_CHAR:
4659 sigterm_received = TRUE;
4660 break;
4661 case _UNIX_SIGNAL_PIPE_SIGHUP_CHAR:
4662 sighup_received = TRUE;
4663 break;
4664 case _UNIX_SIGNAL_PIPE_SIGINT_CHAR:
4665 sigint_received = TRUE;
4666 break;
4667 default:
4668 g_warning ("Invalid char '%c' read from child watch pipe", b[i]);
4669 break;
4672 if (sigterm_received)
4673 deliver_unix_signal (SIGTERM);
4674 if (sigint_received)
4675 deliver_unix_signal (SIGINT);
4676 if (sighup_received)
4677 deliver_unix_signal (SIGHUP);
4678 _g_main_wake_up_all_contexts ();
4682 static void
4683 g_child_watch_source_init (void)
4685 G_LOCK (unix_signal_lock);
4686 ensure_unix_signal_handler_installed_unlocked (SIGCHLD);
4687 G_UNLOCK (unix_signal_lock);
4690 #endif /* !G_OS_WIN32 */
4693 * g_child_watch_source_new:
4694 * @pid: process to watch. On POSIX the pid of a child process. On
4695 * Windows a handle for a process (which doesn't have to be a child).
4697 * Creates a new child_watch source.
4699 * The source will not initially be associated with any #GMainContext
4700 * and must be added to one with g_source_attach() before it will be
4701 * executed.
4703 * Note that child watch sources can only be used in conjunction with
4704 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4705 * flag is used.
4707 * Note that on platforms where #GPid must be explicitly closed
4708 * (see g_spawn_close_pid()) @pid must not be closed while the
4709 * source is still active. Typically, you will want to call
4710 * g_spawn_close_pid() in the callback function for the source.
4712 * Note further that using g_child_watch_source_new() is not
4713 * compatible with calling <literal>waitpid(-1)</literal> in
4714 * the application. Calling waitpid() for individual pids will
4715 * still work fine.
4717 * Return value: the newly-created child watch source
4719 * Since: 2.4
4721 GSource *
4722 g_child_watch_source_new (GPid pid)
4724 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4725 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4727 #ifdef G_OS_WIN32
4728 child_watch_source->poll.fd = (gintptr) pid;
4729 child_watch_source->poll.events = G_IO_IN;
4731 g_source_add_poll (source, &child_watch_source->poll);
4732 #else /* G_OS_WIN32 */
4733 g_child_watch_source_init ();
4734 #endif /* G_OS_WIN32 */
4736 child_watch_source->pid = pid;
4738 return source;
4742 * g_child_watch_add_full:
4743 * @priority: the priority of the idle source. Typically this will be in the
4744 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4745 * @pid: process to watch. On POSIX the pid of a child process. On
4746 * Windows a handle for a process (which doesn't have to be a child).
4747 * @function: function to call
4748 * @data: data to pass to @function
4749 * @notify: function to call when the idle is removed, or %NULL
4751 * Sets a function to be called when the child indicated by @pid
4752 * exits, at the priority @priority.
4754 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4755 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4756 * the spawn function for the child watching to work.
4758 * Note that on platforms where #GPid must be explicitly closed
4759 * (see g_spawn_close_pid()) @pid must not be closed while the
4760 * source is still active. Typically, you will want to call
4761 * g_spawn_close_pid() in the callback function for the source.
4763 * GLib supports only a single callback per process id.
4765 * This internally creates a main loop source using
4766 * g_child_watch_source_new() and attaches it to the main loop context
4767 * using g_source_attach(). You can do these steps manually if you
4768 * need greater control.
4770 * Return value: the ID (greater than 0) of the event source.
4772 * Rename to: g_child_watch_add
4773 * Since: 2.4
4775 guint
4776 g_child_watch_add_full (gint priority,
4777 GPid pid,
4778 GChildWatchFunc function,
4779 gpointer data,
4780 GDestroyNotify notify)
4782 GSource *source;
4783 guint id;
4785 g_return_val_if_fail (function != NULL, 0);
4787 source = g_child_watch_source_new (pid);
4789 if (priority != G_PRIORITY_DEFAULT)
4790 g_source_set_priority (source, priority);
4792 g_source_set_callback (source, (GSourceFunc) function, data, notify);
4793 id = g_source_attach (source, NULL);
4794 g_source_unref (source);
4796 return id;
4800 * g_child_watch_add:
4801 * @pid: process id to watch. On POSIX the pid of a child process. On
4802 * Windows a handle for a process (which doesn't have to be a child).
4803 * @function: function to call
4804 * @data: data to pass to @function
4806 * Sets a function to be called when the child indicated by @pid
4807 * exits, at a default priority, #G_PRIORITY_DEFAULT.
4809 * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes()
4810 * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to
4811 * the spawn function for the child watching to work.
4813 * Note that on platforms where #GPid must be explicitly closed
4814 * (see g_spawn_close_pid()) @pid must not be closed while the
4815 * source is still active. Typically, you will want to call
4816 * g_spawn_close_pid() in the callback function for the source.
4818 * GLib supports only a single callback per process id.
4820 * This internally creates a main loop source using
4821 * g_child_watch_source_new() and attaches it to the main loop context
4822 * using g_source_attach(). You can do these steps manually if you
4823 * need greater control.
4825 * Return value: the ID (greater than 0) of the event source.
4827 * Since: 2.4
4829 guint
4830 g_child_watch_add (GPid pid,
4831 GChildWatchFunc function,
4832 gpointer data)
4834 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4838 /* Idle functions */
4840 static gboolean
4841 g_idle_prepare (GSource *source,
4842 gint *timeout)
4844 *timeout = 0;
4846 return TRUE;
4849 static gboolean
4850 g_idle_check (GSource *source)
4852 return TRUE;
4855 static gboolean
4856 g_idle_dispatch (GSource *source,
4857 GSourceFunc callback,
4858 gpointer user_data)
4860 if (!callback)
4862 g_warning ("Idle source dispatched without callback\n"
4863 "You must call g_source_set_callback().");
4864 return FALSE;
4867 return callback (user_data);
4871 * g_idle_source_new:
4873 * Creates a new idle source.
4875 * The source will not initially be associated with any #GMainContext
4876 * and must be added to one with g_source_attach() before it will be
4877 * executed. Note that the default priority for idle sources is
4878 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4879 * have a default priority of %G_PRIORITY_DEFAULT.
4881 * Return value: the newly-created idle source
4883 GSource *
4884 g_idle_source_new (void)
4886 GSource *source;
4888 source = g_source_new (&g_idle_funcs, sizeof (GSource));
4889 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4891 return source;
4895 * g_idle_add_full:
4896 * @priority: the priority of the idle source. Typically this will be in the
4897 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4898 * @function: function to call
4899 * @data: data to pass to @function
4900 * @notify: function to call when the idle is removed, or %NULL
4902 * Adds a function to be called whenever there are no higher priority
4903 * events pending. If the function returns %FALSE it is automatically
4904 * removed from the list of event sources and will not be called again.
4906 * This internally creates a main loop source using g_idle_source_new()
4907 * and attaches it to the main loop context using g_source_attach().
4908 * You can do these steps manually if you need greater control.
4910 * Return value: the ID (greater than 0) of the event source.
4911 * Rename to: g_idle_add
4913 guint
4914 g_idle_add_full (gint priority,
4915 GSourceFunc function,
4916 gpointer data,
4917 GDestroyNotify notify)
4919 GSource *source;
4920 guint id;
4922 g_return_val_if_fail (function != NULL, 0);
4924 source = g_idle_source_new ();
4926 if (priority != G_PRIORITY_DEFAULT_IDLE)
4927 g_source_set_priority (source, priority);
4929 g_source_set_callback (source, function, data, notify);
4930 id = g_source_attach (source, NULL);
4931 g_source_unref (source);
4933 return id;
4937 * g_idle_add:
4938 * @function: function to call
4939 * @data: data to pass to @function.
4941 * Adds a function to be called whenever there are no higher priority
4942 * events pending to the default main loop. The function is given the
4943 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
4944 * returns %FALSE it is automatically removed from the list of event
4945 * sources and will not be called again.
4947 * This internally creates a main loop source using g_idle_source_new()
4948 * and attaches it to the main loop context using g_source_attach().
4949 * You can do these steps manually if you need greater control.
4951 * Return value: the ID (greater than 0) of the event source.
4953 guint
4954 g_idle_add (GSourceFunc function,
4955 gpointer data)
4957 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4961 * g_idle_remove_by_data:
4962 * @data: the data for the idle source's callback.
4964 * Removes the idle function with the given data.
4966 * Return value: %TRUE if an idle source was found and removed.
4968 gboolean
4969 g_idle_remove_by_data (gpointer data)
4971 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4975 * g_main_context_invoke:
4976 * @context: a #GMainContext, or %NULL
4977 * @function: function to call
4978 * @data: data to pass to @function
4980 * Invokes a function in such a way that @context is owned during the
4981 * invocation of @function.
4983 * If @context is %NULL then the global default main context — as
4984 * returned by g_main_context_default() — is used.
4986 * If @context is owned by the current thread, @function is called
4987 * directly. Otherwise, if @context is the thread-default main context
4988 * of the current thread and g_main_context_acquire() succeeds, then
4989 * @function is called and g_main_context_release() is called
4990 * afterwards.
4992 * In any other case, an idle source is created to call @function and
4993 * that source is attached to @context (presumably to be run in another
4994 * thread). The idle source is attached with #G_PRIORITY_DEFAULT
4995 * priority. If you want a different priority, use
4996 * g_main_context_invoke_full().
4998 * Note that, as with normal idle functions, @function should probably
4999 * return %FALSE. If it returns %TRUE, it will be continuously run in a
5000 * loop (and may prevent this call from returning).
5002 * Since: 2.28
5004 void
5005 g_main_context_invoke (GMainContext *context,
5006 GSourceFunc function,
5007 gpointer data)
5009 g_main_context_invoke_full (context,
5010 G_PRIORITY_DEFAULT,
5011 function, data, NULL);
5015 * g_main_context_invoke_full:
5016 * @context: a #GMainContext, or %NULL
5017 * @priority: the priority at which to run @function
5018 * @function: function to call
5019 * @data: data to pass to @function
5020 * @notify: a function to call when @data is no longer in use, or %NULL.
5022 * Invokes a function in such a way that @context is owned during the
5023 * invocation of @function.
5025 * This function is the same as g_main_context_invoke() except that it
5026 * lets you specify the priority incase @function ends up being
5027 * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
5029 * @notify should not assume that it is called from any particular
5030 * thread or with any particular context acquired.
5032 * Since: 2.28
5034 void
5035 g_main_context_invoke_full (GMainContext *context,
5036 gint priority,
5037 GSourceFunc function,
5038 gpointer data,
5039 GDestroyNotify notify)
5041 g_return_if_fail (function != NULL);
5043 if (!context)
5044 context = g_main_context_default ();
5046 if (g_main_context_is_owner (context))
5048 while (function (data));
5049 if (notify != NULL)
5050 notify (data);
5053 else
5055 GMainContext *thread_default;
5057 thread_default = g_main_context_get_thread_default ();
5059 if (!thread_default)
5060 thread_default = g_main_context_default ();
5062 if (thread_default == context && g_main_context_acquire (context))
5064 while (function (data));
5066 g_main_context_release (context);
5068 if (notify != NULL)
5069 notify (data);
5071 else
5073 GSource *source;
5075 source = g_idle_source_new ();
5076 g_source_set_priority (source, priority);
5077 g_source_set_callback (source, function, data, notify);
5078 g_source_attach (source, context);
5079 g_source_unref (source);