If a character can't be converted, don't replace it with a NUL byte, but
[glib.git] / glib / gmain.c
blob40484fb0dcc7eccc61a161e59dffa329e96fc8f5
1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * gmain.c: Main loop abstraction, timeouts, and idle functions
5 * Copyright 1998 Owen Taylor
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the
19 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 * Boston, MA 02111-1307, USA.
24 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
25 * file for a list of people on the GLib Team. See the ChangeLog
26 * files for a list of changes. These files are distributed with
27 * GLib at ftp://ftp.gtk.org/pub/gtk/.
30 /*
31 * MT safe
34 #include "config.h"
36 /* uncomment the next line to get poll() debugging info */
37 /* #define G_MAIN_POLL_DEBUG */
39 #include "glib.h"
40 #include "gthreadprivate.h"
41 #include <signal.h>
42 #include <sys/types.h>
43 #include <time.h>
44 #ifdef HAVE_SYS_TIME_H
45 #include <sys/time.h>
46 #endif /* HAVE_SYS_TIME_H */
47 #ifdef GLIB_HAVE_SYS_POLL_H
48 # include <sys/poll.h>
49 # undef events /* AIX 4.1.5 & 4.3.2 define this for SVR3,4 compatibility */
50 # undef revents /* AIX 4.1.5 & 4.3.2 define this for SVR3,4 compatibility */
52 /* The poll() emulation on OS/X doesn't handle fds=NULL, nfds=0,
53 * so we prefer our own poll emulation.
55 #ifdef _POLL_EMUL_H_
56 #undef HAVE_POLL
57 #endif
59 #endif /* GLIB_HAVE_SYS_POLL_H */
60 #ifdef HAVE_UNISTD_H
61 #include <unistd.h>
62 #endif /* HAVE_UNISTD_H */
63 #include <errno.h>
65 #ifdef G_OS_WIN32
66 #define STRICT
67 #include <windows.h>
68 #endif /* G_OS_WIN32 */
70 #ifdef G_OS_BEOS
71 #include <sys/socket.h>
72 #include <sys/wait.h>
73 #endif /* G_OS_BEOS */
75 #ifdef G_OS_UNIX
76 #include <fcntl.h>
77 #include <sys/wait.h>
78 #endif
80 #include "galias.h"
82 /* Types */
84 typedef struct _GTimeoutSource GTimeoutSource;
85 typedef struct _GChildWatchSource GChildWatchSource;
86 typedef struct _GPollRec GPollRec;
87 typedef struct _GSourceCallback GSourceCallback;
89 typedef enum
91 G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
92 G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
93 } GSourceFlags;
95 #ifdef G_THREADS_ENABLED
96 typedef struct _GMainWaiter GMainWaiter;
98 struct _GMainWaiter
100 GCond *cond;
101 GMutex *mutex;
103 #endif
105 typedef struct _GMainDispatch GMainDispatch;
107 struct _GMainDispatch
109 gint depth;
110 GSList *source; /* stack of current sources */
113 struct _GMainContext
115 #ifdef G_THREADS_ENABLED
116 /* The following lock is used for both the list of sources
117 * and the list of poll records
119 GStaticMutex mutex;
120 GCond *cond;
121 GThread *owner;
122 guint owner_count;
123 GSList *waiters;
124 #endif
126 gint ref_count;
128 GPtrArray *pending_dispatches;
129 gint timeout; /* Timeout for current iteration */
131 guint next_id;
132 GSource *source_list;
133 gint in_check_or_prepare;
135 GPollRec *poll_records;
136 guint n_poll_records;
137 GPollFD *cached_poll_array;
138 guint cached_poll_array_size;
140 #ifdef G_THREADS_ENABLED
141 #ifndef G_OS_WIN32
142 /* this pipe is used to wake up the main loop when a source is added.
144 gint wake_up_pipe[2];
145 #else /* G_OS_WIN32 */
146 HANDLE wake_up_semaphore;
147 #endif /* G_OS_WIN32 */
149 GPollFD wake_up_rec;
150 gboolean poll_waiting;
152 /* Flag indicating whether the set of fd's changed during a poll */
153 gboolean poll_changed;
154 #endif /* G_THREADS_ENABLED */
156 GPollFunc poll_func;
158 GTimeVal current_time;
159 gboolean time_is_current;
162 struct _GSourceCallback
164 guint ref_count;
165 GSourceFunc func;
166 gpointer data;
167 GDestroyNotify notify;
170 struct _GMainLoop
172 GMainContext *context;
173 gboolean is_running;
174 gint ref_count;
177 struct _GTimeoutSource
179 GSource source;
180 GTimeVal expiration;
181 guint interval;
184 struct _GChildWatchSource
186 GSource source;
187 GPid pid;
188 gint child_status;
189 #ifdef G_OS_WIN32
190 GPollFD poll;
191 #else /* G_OS_WIN32 */
192 gint count;
193 gboolean child_exited;
194 #endif /* G_OS_WIN32 */
197 struct _GPollRec
199 GPollFD *fd;
200 GPollRec *next;
201 gint priority;
204 #ifdef G_THREADS_ENABLED
205 #define LOCK_CONTEXT(context) g_static_mutex_lock (&context->mutex)
206 #define UNLOCK_CONTEXT(context) g_static_mutex_unlock (&context->mutex)
207 #define G_THREAD_SELF g_thread_self ()
208 #else
209 #define LOCK_CONTEXT(context) (void)0
210 #define UNLOCK_CONTEXT(context) (void)0
211 #define G_THREAD_SELF NULL
212 #endif
214 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
215 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
216 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
218 #define SOURCE_UNREF(source, context) \
219 G_STMT_START { \
220 if ((source)->ref_count > 1) \
221 (source)->ref_count--; \
222 else \
223 g_source_unref_internal ((source), (context), TRUE); \
224 } G_STMT_END
227 /* Forward declarations */
229 static void g_source_unref_internal (GSource *source,
230 GMainContext *context,
231 gboolean have_lock);
232 static void g_source_destroy_internal (GSource *source,
233 GMainContext *context,
234 gboolean have_lock);
235 static void g_main_context_poll (GMainContext *context,
236 gint timeout,
237 gint priority,
238 GPollFD *fds,
239 gint n_fds);
240 static void g_main_context_add_poll_unlocked (GMainContext *context,
241 gint priority,
242 GPollFD *fd);
243 static void g_main_context_remove_poll_unlocked (GMainContext *context,
244 GPollFD *fd);
245 static void g_main_context_wakeup_unlocked (GMainContext *context);
247 static gboolean g_timeout_prepare (GSource *source,
248 gint *timeout);
249 static gboolean g_timeout_check (GSource *source);
250 static gboolean g_timeout_dispatch (GSource *source,
251 GSourceFunc callback,
252 gpointer user_data);
253 static gboolean g_child_watch_prepare (GSource *source,
254 gint *timeout);
255 static gboolean g_child_watch_check (GSource *source);
256 static gboolean g_child_watch_dispatch (GSource *source,
257 GSourceFunc callback,
258 gpointer user_data);
259 static gboolean g_idle_prepare (GSource *source,
260 gint *timeout);
261 static gboolean g_idle_check (GSource *source);
262 static gboolean g_idle_dispatch (GSource *source,
263 GSourceFunc callback,
264 gpointer user_data);
266 G_LOCK_DEFINE_STATIC (main_loop);
267 static GMainContext *default_main_context;
268 static GSList *main_contexts_without_pipe = NULL;
270 #ifndef G_OS_WIN32
271 /* Child status monitoring code */
272 enum {
273 CHILD_WATCH_UNINITIALIZED,
274 CHILD_WATCH_INITIALIZED_SINGLE,
275 CHILD_WATCH_INITIALIZED_THREADED
277 static gint child_watch_init_state = CHILD_WATCH_UNINITIALIZED;
278 static gint child_watch_count = 1;
279 static gint child_watch_wake_up_pipe[2] = {0, 0};
280 #endif /* !G_OS_WIN32 */
281 G_LOCK_DEFINE_STATIC (main_context_list);
282 static GSList *main_context_list = NULL;
284 GSourceFuncs g_timeout_funcs =
286 g_timeout_prepare,
287 g_timeout_check,
288 g_timeout_dispatch,
289 NULL
292 GSourceFuncs g_child_watch_funcs =
294 g_child_watch_prepare,
295 g_child_watch_check,
296 g_child_watch_dispatch,
297 NULL
300 GSourceFuncs g_idle_funcs =
302 g_idle_prepare,
303 g_idle_check,
304 g_idle_dispatch,
305 NULL
308 #ifdef HAVE_POLL
309 /* SunOS has poll, but doesn't provide a prototype. */
310 # if defined (sun) && !defined (__SVR4)
311 extern gint poll (GPollFD *ufds, guint nfsd, gint timeout);
312 # endif /* !sun */
313 #else /* !HAVE_POLL */
315 #ifdef G_OS_WIN32
317 static gint
318 g_poll (GPollFD *fds,
319 guint nfds,
320 gint timeout)
322 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
323 gboolean poll_msgs = FALSE;
324 GPollFD *f;
325 DWORD ready;
326 MSG msg;
327 UINT timer;
328 gint nhandles = 0;
330 for (f = fds; f < &fds[nfds]; ++f)
331 if (f->fd >= 0)
333 if (f->fd == G_WIN32_MSG_HANDLE)
334 poll_msgs = TRUE;
335 else if (nhandles == MAXIMUM_WAIT_OBJECTS)
337 g_warning (G_STRLOC ": Too many handles to wait for!\n");
338 break;
340 else
342 #ifdef G_MAIN_POLL_DEBUG
343 g_print ("g_poll: waiting for %#x\n", f->fd);
344 #endif
345 handles[nhandles++] = (HANDLE) f->fd;
349 if (timeout == -1)
350 timeout = INFINITE;
352 if (poll_msgs)
354 /* Waiting for messages, and maybe events
355 * -> First PeekMessage
357 #ifdef G_MAIN_POLL_DEBUG
358 g_print ("PeekMessage\n");
359 #endif
360 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
361 ready = WAIT_OBJECT_0 + nhandles;
362 else
364 if (nhandles == 0)
366 /* Waiting just for messages */
367 if (timeout == INFINITE)
369 /* Infinite timeout
370 * -> WaitMessage
372 #ifdef G_MAIN_POLL_DEBUG
373 g_print ("WaitMessage\n");
374 #endif
375 if (!WaitMessage ())
377 gchar *emsg = g_win32_error_message (GetLastError ());
378 g_warning (G_STRLOC ": WaitMessage() failed: %s", emsg);
379 g_free (emsg);
381 ready = WAIT_OBJECT_0 + nhandles;
383 else if (timeout == 0)
385 /* Waiting just for messages, zero timeout.
386 * If we got here, there was no message
388 ready = WAIT_TIMEOUT;
390 else
392 /* Waiting just for messages, some timeout
393 * -> Set a timer, wait for message,
394 * kill timer, use PeekMessage
396 timer = SetTimer (NULL, 0, timeout, NULL);
397 if (timer == 0)
399 gchar *emsg = g_win32_error_message (GetLastError ());
400 g_warning (G_STRLOC ": SetTimer() failed: %s", emsg);
401 g_free (emsg);
402 ready = WAIT_TIMEOUT;
404 else
406 #ifdef G_MAIN_POLL_DEBUG
407 g_print ("WaitMessage\n");
408 #endif
409 WaitMessage ();
410 KillTimer (NULL, timer);
411 #ifdef G_MAIN_POLL_DEBUG
412 g_print ("PeekMessage\n");
413 #endif
414 if (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE)
415 && msg.message != WM_TIMER)
416 ready = WAIT_OBJECT_0;
417 else
418 ready = WAIT_TIMEOUT;
422 else
424 /* Wait for either message or event
425 * -> Use MsgWaitForMultipleObjects
427 #ifdef G_MAIN_POLL_DEBUG
428 g_print ("MsgWaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
429 #endif
430 ready = MsgWaitForMultipleObjects (nhandles, handles, FALSE,
431 timeout, QS_ALLINPUT);
433 if (ready == WAIT_FAILED)
435 gchar *emsg = g_win32_error_message (GetLastError ());
436 g_warning (G_STRLOC ": MsgWaitForMultipleObjects() failed: %s", emsg);
437 g_free (emsg);
442 else if (nhandles == 0)
444 /* Wait for nothing (huh?) */
445 return 0;
447 else
449 /* Wait for just events
450 * -> Use WaitForMultipleObjects
452 #ifdef G_MAIN_POLL_DEBUG
453 g_print ("WaitForMultipleObjects(%d, %d)\n", nhandles, timeout);
454 #endif
455 ready = WaitForMultipleObjects (nhandles, handles, FALSE, timeout);
456 if (ready == WAIT_FAILED)
458 gchar *emsg = g_win32_error_message (GetLastError ());
459 g_warning (G_STRLOC ": WaitForMultipleObjects() failed: %s", emsg);
460 g_free (emsg);
464 #ifdef G_MAIN_POLL_DEBUG
465 g_print ("wait returns %ld%s\n",
466 ready,
467 (ready == WAIT_FAILED ? " (WAIT_FAILED)" :
468 (ready == WAIT_TIMEOUT ? " (WAIT_TIMEOUT)" :
469 (poll_msgs && ready == WAIT_OBJECT_0 + nhandles ? " (msg)" : ""))));
470 #endif
471 for (f = fds; f < &fds[nfds]; ++f)
472 f->revents = 0;
474 if (ready == WAIT_FAILED)
475 return -1;
476 else if (ready == WAIT_TIMEOUT)
477 return 0;
478 else if (poll_msgs && ready == WAIT_OBJECT_0 + nhandles)
480 for (f = fds; f < &fds[nfds]; ++f)
481 if (f->fd >= 0)
483 if (f->events & G_IO_IN)
484 if (f->fd == G_WIN32_MSG_HANDLE)
485 f->revents |= G_IO_IN;
488 else if (ready >= WAIT_OBJECT_0 && ready < WAIT_OBJECT_0 + nhandles)
489 for (f = fds; f < &fds[nfds]; ++f)
491 if (f->fd == (gint) handles[ready - WAIT_OBJECT_0])
493 f->revents = f->events;
494 #ifdef G_MAIN_POLL_DEBUG
495 g_print ("g_poll: got event %#x\n", f->fd);
496 #endif
500 return 1;
503 #else /* !G_OS_WIN32 */
505 /* The following implementation of poll() comes from the GNU C Library.
506 * Copyright (C) 1994, 1996, 1997 Free Software Foundation, Inc.
509 #include <string.h> /* for bzero on BSD systems */
511 #ifdef HAVE_SYS_SELECT_H
512 #include <sys/select.h>
513 #endif /* HAVE_SYS_SELECT_H */
515 #ifdef G_OS_BEOS
516 #undef NO_FD_SET
517 #endif /* G_OS_BEOS */
519 #ifndef NO_FD_SET
520 # define SELECT_MASK fd_set
521 #else /* !NO_FD_SET */
522 # ifndef _AIX
523 typedef long fd_mask;
524 # endif /* _AIX */
525 # ifdef _IBMR2
526 # define SELECT_MASK void
527 # else /* !_IBMR2 */
528 # define SELECT_MASK int
529 # endif /* !_IBMR2 */
530 #endif /* !NO_FD_SET */
532 static gint
533 g_poll (GPollFD *fds,
534 guint nfds,
535 gint timeout)
537 struct timeval tv;
538 SELECT_MASK rset, wset, xset;
539 GPollFD *f;
540 int ready;
541 int maxfd = 0;
543 FD_ZERO (&rset);
544 FD_ZERO (&wset);
545 FD_ZERO (&xset);
547 for (f = fds; f < &fds[nfds]; ++f)
548 if (f->fd >= 0)
550 if (f->events & G_IO_IN)
551 FD_SET (f->fd, &rset);
552 if (f->events & G_IO_OUT)
553 FD_SET (f->fd, &wset);
554 if (f->events & G_IO_PRI)
555 FD_SET (f->fd, &xset);
556 if (f->fd > maxfd && (f->events & (G_IO_IN|G_IO_OUT|G_IO_PRI)))
557 maxfd = f->fd;
560 tv.tv_sec = timeout / 1000;
561 tv.tv_usec = (timeout % 1000) * 1000;
563 ready = select (maxfd + 1, &rset, &wset, &xset,
564 timeout == -1 ? NULL : &tv);
565 if (ready > 0)
566 for (f = fds; f < &fds[nfds]; ++f)
568 f->revents = 0;
569 if (f->fd >= 0)
571 if (FD_ISSET (f->fd, &rset))
572 f->revents |= G_IO_IN;
573 if (FD_ISSET (f->fd, &wset))
574 f->revents |= G_IO_OUT;
575 if (FD_ISSET (f->fd, &xset))
576 f->revents |= G_IO_PRI;
580 return ready;
583 #endif /* !G_OS_WIN32 */
585 #endif /* !HAVE_POLL */
588 * g_main_context_ref:
589 * @context: a #GMainContext
591 * Increases the reference count on a #GMainContext object by one.
593 * Returns: the @context that was passed in (since 2.6)
595 GMainContext *
596 g_main_context_ref (GMainContext *context)
598 g_return_val_if_fail (context != NULL, NULL);
599 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
601 g_atomic_int_inc (&context->ref_count);
603 return context;
606 static inline void
607 poll_rec_list_free (GMainContext *context,
608 GPollRec *list)
610 g_slice_free_chain (GPollRec, list, next);
614 * g_main_context_unref:
615 * @context: a #GMainContext
617 * Decreases the reference count on a #GMainContext object by one. If
618 * the result is zero, free the context and free all associated memory.
620 void
621 g_main_context_unref (GMainContext *context)
623 GSource *source;
624 g_return_if_fail (context != NULL);
625 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
627 if (!g_atomic_int_dec_and_test (&context->ref_count))
628 return;
630 G_LOCK (main_context_list);
631 main_context_list = g_slist_remove (main_context_list, context);
632 G_UNLOCK (main_context_list);
634 source = context->source_list;
635 while (source)
637 GSource *next = source->next;
638 g_source_destroy_internal (source, context, FALSE);
639 source = next;
642 #ifdef G_THREADS_ENABLED
643 g_static_mutex_free (&context->mutex);
644 #endif
646 g_ptr_array_free (context->pending_dispatches, TRUE);
647 g_free (context->cached_poll_array);
649 poll_rec_list_free (context, context->poll_records);
651 #ifdef G_THREADS_ENABLED
652 if (g_thread_supported())
654 #ifndef G_OS_WIN32
655 close (context->wake_up_pipe[0]);
656 close (context->wake_up_pipe[1]);
657 #else
658 CloseHandle (context->wake_up_semaphore);
659 #endif
661 else
662 main_contexts_without_pipe = g_slist_remove (main_contexts_without_pipe,
663 context);
664 #endif
666 g_free (context);
669 #ifdef G_THREADS_ENABLED
670 static void
671 g_main_context_init_pipe (GMainContext *context)
673 # ifndef G_OS_WIN32
674 if (context->wake_up_pipe[0] != -1)
675 return;
676 if (pipe (context->wake_up_pipe) < 0)
677 g_error ("Cannot create pipe main loop wake-up: %s\n",
678 g_strerror (errno));
680 context->wake_up_rec.fd = context->wake_up_pipe[0];
681 context->wake_up_rec.events = G_IO_IN;
682 # else
683 if (context->wake_up_semaphore != NULL)
684 return;
685 context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
686 if (context->wake_up_semaphore == NULL)
687 g_error ("Cannot create wake-up semaphore: %s",
688 g_win32_error_message (GetLastError ()));
689 context->wake_up_rec.fd = (gint) context->wake_up_semaphore;
690 context->wake_up_rec.events = G_IO_IN;
691 # ifdef G_MAIN_POLL_DEBUG
692 g_print ("wake-up semaphore: %#x\n", (guint) context->wake_up_semaphore);
693 # endif
694 # endif
695 g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
698 void
699 _g_main_thread_init (void)
701 GSList *curr = main_contexts_without_pipe;
702 while (curr)
704 g_main_context_init_pipe ((GMainContext *)curr->data);
705 curr = curr->next;
707 g_slist_free (main_contexts_without_pipe);
708 main_contexts_without_pipe = NULL;
710 #endif /* G_THREADS_ENABLED */
713 * g_main_context_new:
715 * Creates a new #GMainContext strcuture
717 * Return value: the new #GMainContext
719 GMainContext *
720 g_main_context_new (void)
722 GMainContext *context = g_new0 (GMainContext, 1);
724 #ifdef G_THREADS_ENABLED
725 g_static_mutex_init (&context->mutex);
727 context->owner = NULL;
728 context->waiters = NULL;
730 # ifndef G_OS_WIN32
731 context->wake_up_pipe[0] = -1;
732 context->wake_up_pipe[1] = -1;
733 # else
734 context->wake_up_semaphore = NULL;
735 # endif
736 #endif
738 context->ref_count = 1;
740 context->next_id = 1;
742 context->source_list = NULL;
744 #if HAVE_POLL
745 context->poll_func = (GPollFunc)poll;
746 #else
747 context->poll_func = g_poll;
748 #endif
750 context->cached_poll_array = NULL;
751 context->cached_poll_array_size = 0;
753 context->pending_dispatches = g_ptr_array_new ();
755 context->time_is_current = FALSE;
757 #ifdef G_THREADS_ENABLED
758 if (g_thread_supported ())
759 g_main_context_init_pipe (context);
760 else
761 main_contexts_without_pipe = g_slist_prepend (main_contexts_without_pipe,
762 context);
763 #endif
765 G_LOCK (main_context_list);
766 main_context_list = g_slist_append (main_context_list, context);
767 G_UNLOCK (main_context_list);
769 return context;
773 * g_main_context_default:
775 * Returns the default main context. This is the main context used
776 * for main loop functions when a main loop is not explicitly
777 * specified.
779 * Return value: the default main context.
781 GMainContext *
782 g_main_context_default (void)
784 /* Slow, but safe */
786 G_LOCK (main_loop);
788 if (!default_main_context)
789 default_main_context = g_main_context_new ();
791 G_UNLOCK (main_loop);
793 return default_main_context;
796 /* Hooks for adding to the main loop */
799 * g_source_new:
800 * @source_funcs: structure containing functions that implement
801 * the sources behavior.
802 * @struct_size: size of the #GSource structure to create.
804 * Creates a new #GSource structure. The size is specified to
805 * allow creating structures derived from #GSource that contain
806 * additional data. The size passed in must be at least
807 * <literal>sizeof (GSource)</literal>.
809 * The source will not initially be associated with any #GMainContext
810 * and must be added to one with g_source_attach() before it will be
811 * executed.
813 * Return value: the newly-created #GSource.
815 GSource *
816 g_source_new (GSourceFuncs *source_funcs,
817 guint struct_size)
819 GSource *source;
821 g_return_val_if_fail (source_funcs != NULL, NULL);
822 g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
824 source = (GSource*) g_malloc0 (struct_size);
826 source->source_funcs = source_funcs;
827 source->ref_count = 1;
829 source->priority = G_PRIORITY_DEFAULT;
831 source->flags = G_HOOK_FLAG_ACTIVE;
833 /* NULL/0 initialization for all other fields */
835 return source;
838 /* Holds context's lock
840 static void
841 g_source_list_add (GSource *source,
842 GMainContext *context)
844 GSource *tmp_source, *last_source;
846 last_source = NULL;
847 tmp_source = context->source_list;
848 while (tmp_source && tmp_source->priority <= source->priority)
850 last_source = tmp_source;
851 tmp_source = tmp_source->next;
854 source->next = tmp_source;
855 if (tmp_source)
856 tmp_source->prev = source;
858 source->prev = last_source;
859 if (last_source)
860 last_source->next = source;
861 else
862 context->source_list = source;
865 /* Holds context's lock
867 static void
868 g_source_list_remove (GSource *source,
869 GMainContext *context)
871 if (source->prev)
872 source->prev->next = source->next;
873 else
874 context->source_list = source->next;
876 if (source->next)
877 source->next->prev = source->prev;
879 source->prev = NULL;
880 source->next = NULL;
884 * g_source_attach:
885 * @source: a #GSource
886 * @context: a #GMainContext (if %NULL, the default context will be used)
888 * Adds a #GSource to a @context so that it will be executed within
889 * that context.
891 * Return value: the ID (greater than 0) for the source within the
892 * #GMainContext.
894 guint
895 g_source_attach (GSource *source,
896 GMainContext *context)
898 guint result = 0;
899 GSList *tmp_list;
901 g_return_val_if_fail (source->context == NULL, 0);
902 g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
904 if (!context)
905 context = g_main_context_default ();
907 LOCK_CONTEXT (context);
909 source->context = context;
910 result = source->source_id = context->next_id++;
912 source->ref_count++;
913 g_source_list_add (source, context);
915 tmp_list = source->poll_fds;
916 while (tmp_list)
918 g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
919 tmp_list = tmp_list->next;
922 #ifdef G_THREADS_ENABLED
923 /* Now wake up the main loop if it is waiting in the poll() */
924 g_main_context_wakeup_unlocked (context);
925 #endif
927 UNLOCK_CONTEXT (context);
929 return result;
932 static void
933 g_source_destroy_internal (GSource *source,
934 GMainContext *context,
935 gboolean have_lock)
937 if (!have_lock)
938 LOCK_CONTEXT (context);
940 if (!SOURCE_DESTROYED (source))
942 GSList *tmp_list;
943 gpointer old_cb_data;
944 GSourceCallbackFuncs *old_cb_funcs;
946 source->flags &= ~G_HOOK_FLAG_ACTIVE;
948 old_cb_data = source->callback_data;
949 old_cb_funcs = source->callback_funcs;
951 source->callback_data = NULL;
952 source->callback_funcs = NULL;
954 if (old_cb_funcs)
956 UNLOCK_CONTEXT (context);
957 old_cb_funcs->unref (old_cb_data);
958 LOCK_CONTEXT (context);
961 if (!SOURCE_BLOCKED (source))
963 tmp_list = source->poll_fds;
964 while (tmp_list)
966 g_main_context_remove_poll_unlocked (context, tmp_list->data);
967 tmp_list = tmp_list->next;
971 g_source_unref_internal (source, context, TRUE);
974 if (!have_lock)
975 UNLOCK_CONTEXT (context);
979 * g_source_destroy:
980 * @source: a #GSource
982 * Removes a source from its #GMainContext, if any, and mark it as
983 * destroyed. The source cannot be subsequently added to another
984 * context.
986 void
987 g_source_destroy (GSource *source)
989 GMainContext *context;
991 g_return_if_fail (source != NULL);
993 context = source->context;
995 if (context)
996 g_source_destroy_internal (source, context, FALSE);
997 else
998 source->flags &= ~G_HOOK_FLAG_ACTIVE;
1002 * g_source_get_id:
1003 * @source: a #GSource
1005 * Returns the numeric ID for a particular source. The ID of a source
1006 * is a positive integer which is unique within a particular main loop
1007 * context. The reverse
1008 * mapping from ID to source is done by g_main_context_find_source_by_id().
1010 * Return value: the ID (greater than 0) for the source
1012 guint
1013 g_source_get_id (GSource *source)
1015 guint result;
1017 g_return_val_if_fail (source != NULL, 0);
1018 g_return_val_if_fail (source->context != NULL, 0);
1020 LOCK_CONTEXT (source->context);
1021 result = source->source_id;
1022 UNLOCK_CONTEXT (source->context);
1024 return result;
1028 * g_source_get_context:
1029 * @source: a #GSource
1031 * Gets the #GMainContext with which the source is associated.
1032 * Calling this function on a destroyed source is an error.
1034 * Return value: the #GMainContext with which the source is associated,
1035 * or %NULL if the context has not yet been added
1036 * to a source.
1038 GMainContext *
1039 g_source_get_context (GSource *source)
1041 g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1043 return source->context;
1047 * g_source_add_poll:
1048 * @source:a #GSource
1049 * @fd: a #GPollFD structure holding information about a file
1050 * descriptor to watch.
1052 * Adds a file descriptor to the set of file descriptors polled for
1053 * this source. This is usually combined with g_source_new() to add an
1054 * event source. The event source's check function will typically test
1055 * the @revents field in the #GPollFD struct and return %TRUE if events need
1056 * to be processed.
1058 void
1059 g_source_add_poll (GSource *source,
1060 GPollFD *fd)
1062 GMainContext *context;
1064 g_return_if_fail (source != NULL);
1065 g_return_if_fail (fd != NULL);
1066 g_return_if_fail (!SOURCE_DESTROYED (source));
1068 context = source->context;
1070 if (context)
1071 LOCK_CONTEXT (context);
1073 source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1075 if (context)
1077 if (!SOURCE_BLOCKED (source))
1078 g_main_context_add_poll_unlocked (context, source->priority, fd);
1079 UNLOCK_CONTEXT (context);
1084 * g_source_remove_poll:
1085 * @source:a #GSource
1086 * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1088 * Removes a file descriptor from the set of file descriptors polled for
1089 * this source.
1091 void
1092 g_source_remove_poll (GSource *source,
1093 GPollFD *fd)
1095 GMainContext *context;
1097 g_return_if_fail (source != NULL);
1098 g_return_if_fail (fd != NULL);
1099 g_return_if_fail (!SOURCE_DESTROYED (source));
1101 context = source->context;
1103 if (context)
1104 LOCK_CONTEXT (context);
1106 source->poll_fds = g_slist_remove (source->poll_fds, fd);
1108 if (context)
1110 if (!SOURCE_BLOCKED (source))
1111 g_main_context_remove_poll_unlocked (context, fd);
1112 UNLOCK_CONTEXT (context);
1117 * g_source_set_callback_indirect:
1118 * @source: the source
1119 * @callback_data: pointer to callback data "object"
1120 * @callback_funcs: functions for reference counting @callback_data
1121 * and getting the callback and data
1123 * Sets the callback function storing the data as a refcounted callback
1124 * "object". This is used internally. Note that calling
1125 * g_source_set_callback_indirect() assumes
1126 * an initial reference count on @callback_data, and thus
1127 * @callback_funcs->unref will eventually be called once more
1128 * than @callback_funcs->ref.
1130 void
1131 g_source_set_callback_indirect (GSource *source,
1132 gpointer callback_data,
1133 GSourceCallbackFuncs *callback_funcs)
1135 GMainContext *context;
1136 gpointer old_cb_data;
1137 GSourceCallbackFuncs *old_cb_funcs;
1139 g_return_if_fail (source != NULL);
1140 g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1142 context = source->context;
1144 if (context)
1145 LOCK_CONTEXT (context);
1147 old_cb_data = source->callback_data;
1148 old_cb_funcs = source->callback_funcs;
1150 source->callback_data = callback_data;
1151 source->callback_funcs = callback_funcs;
1153 if (context)
1154 UNLOCK_CONTEXT (context);
1156 if (old_cb_funcs)
1157 old_cb_funcs->unref (old_cb_data);
1160 static void
1161 g_source_callback_ref (gpointer cb_data)
1163 GSourceCallback *callback = cb_data;
1165 callback->ref_count++;
1169 static void
1170 g_source_callback_unref (gpointer cb_data)
1172 GSourceCallback *callback = cb_data;
1174 callback->ref_count--;
1175 if (callback->ref_count == 0)
1177 if (callback->notify)
1178 callback->notify (callback->data);
1179 g_free (callback);
1183 static void
1184 g_source_callback_get (gpointer cb_data,
1185 GSource *source,
1186 GSourceFunc *func,
1187 gpointer *data)
1189 GSourceCallback *callback = cb_data;
1191 *func = callback->func;
1192 *data = callback->data;
1195 static GSourceCallbackFuncs g_source_callback_funcs = {
1196 g_source_callback_ref,
1197 g_source_callback_unref,
1198 g_source_callback_get,
1202 * g_source_set_callback:
1203 * @source: the source
1204 * @func: a callback function
1205 * @data: the data to pass to callback function
1206 * @notify: a function to call when @data is no longer in use, or %NULL.
1208 * Sets the callback function for a source. The callback for a source is
1209 * called from the source's dispatch function.
1211 * The exact type of @func depends on the type of source; ie. you
1212 * should not count on @func being called with @data as its first
1213 * parameter.
1215 * Typically, you won't use this function. Instead use functions specific
1216 * to the type of source you are using.
1218 void
1219 g_source_set_callback (GSource *source,
1220 GSourceFunc func,
1221 gpointer data,
1222 GDestroyNotify notify)
1224 GSourceCallback *new_callback;
1226 g_return_if_fail (source != NULL);
1228 new_callback = g_new (GSourceCallback, 1);
1230 new_callback->ref_count = 1;
1231 new_callback->func = func;
1232 new_callback->data = data;
1233 new_callback->notify = notify;
1235 g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1240 * g_source_set_funcs:
1241 * @source: a #GSource
1242 * @funcs: the new #GSourceFuncs
1244 * Sets the source functions (can be used to override
1245 * default implementations) of an unattached source.
1247 * Since: 2.12
1249 void
1250 g_source_set_funcs (GSource *source,
1251 GSourceFuncs *funcs)
1253 g_return_if_fail (source != NULL);
1254 g_return_if_fail (source->context == NULL);
1255 g_return_if_fail (source->ref_count > 0);
1256 g_return_if_fail (funcs != NULL);
1258 source->source_funcs = funcs;
1262 * g_source_set_priority:
1263 * @source: a #GSource
1264 * @priority: the new priority.
1266 * Sets the priority of a source. While the main loop is being
1267 * run, a source will be dispatched if it is ready to be dispatched and no sources
1268 * at a higher (numerically smaller) priority are ready to be dispatched.
1270 void
1271 g_source_set_priority (GSource *source,
1272 gint priority)
1274 GSList *tmp_list;
1275 GMainContext *context;
1277 g_return_if_fail (source != NULL);
1279 context = source->context;
1281 if (context)
1282 LOCK_CONTEXT (context);
1284 source->priority = priority;
1286 if (context)
1288 /* Remove the source from the context's source and then
1289 * add it back so it is sorted in the correct plcae
1291 g_source_list_remove (source, source->context);
1292 g_source_list_add (source, source->context);
1294 if (!SOURCE_BLOCKED (source))
1296 tmp_list = source->poll_fds;
1297 while (tmp_list)
1299 g_main_context_remove_poll_unlocked (context, tmp_list->data);
1300 g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1302 tmp_list = tmp_list->next;
1306 UNLOCK_CONTEXT (source->context);
1311 * g_source_get_priority:
1312 * @source: a #GSource
1314 * Gets the priority of a source.
1316 * Return value: the priority of the source
1318 gint
1319 g_source_get_priority (GSource *source)
1321 g_return_val_if_fail (source != NULL, 0);
1323 return source->priority;
1327 * g_source_set_can_recurse:
1328 * @source: a #GSource
1329 * @can_recurse: whether recursion is allowed for this source
1331 * Sets whether a source can be called recursively. If @can_recurse is
1332 * %TRUE, then while the source is being dispatched then this source
1333 * will be processed normally. Otherwise, all processing of this
1334 * source is blocked until the dispatch function returns.
1336 void
1337 g_source_set_can_recurse (GSource *source,
1338 gboolean can_recurse)
1340 GMainContext *context;
1342 g_return_if_fail (source != NULL);
1344 context = source->context;
1346 if (context)
1347 LOCK_CONTEXT (context);
1349 if (can_recurse)
1350 source->flags |= G_SOURCE_CAN_RECURSE;
1351 else
1352 source->flags &= ~G_SOURCE_CAN_RECURSE;
1354 if (context)
1355 UNLOCK_CONTEXT (context);
1359 * g_source_get_can_recurse:
1360 * @source: a #GSource
1362 * Checks whether a source is allowed to be called recursively.
1363 * see g_source_set_can_recurse().
1365 * Return value: whether recursion is allowed.
1367 gboolean
1368 g_source_get_can_recurse (GSource *source)
1370 g_return_val_if_fail (source != NULL, FALSE);
1372 return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1376 * g_source_ref:
1377 * @source: a #GSource
1379 * Increases the reference count on a source by one.
1381 * Return value: @source
1383 GSource *
1384 g_source_ref (GSource *source)
1386 GMainContext *context;
1388 g_return_val_if_fail (source != NULL, NULL);
1390 context = source->context;
1392 if (context)
1393 LOCK_CONTEXT (context);
1395 source->ref_count++;
1397 if (context)
1398 UNLOCK_CONTEXT (context);
1400 return source;
1403 /* g_source_unref() but possible to call within context lock
1405 static void
1406 g_source_unref_internal (GSource *source,
1407 GMainContext *context,
1408 gboolean have_lock)
1410 gpointer old_cb_data = NULL;
1411 GSourceCallbackFuncs *old_cb_funcs = NULL;
1413 g_return_if_fail (source != NULL);
1415 if (!have_lock && context)
1416 LOCK_CONTEXT (context);
1418 source->ref_count--;
1419 if (source->ref_count == 0)
1421 old_cb_data = source->callback_data;
1422 old_cb_funcs = source->callback_funcs;
1424 source->callback_data = NULL;
1425 source->callback_funcs = NULL;
1427 if (context && !SOURCE_DESTROYED (source))
1429 g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1430 source->ref_count++;
1432 else if (context)
1433 g_source_list_remove (source, context);
1435 if (source->source_funcs->finalize)
1436 source->source_funcs->finalize (source);
1438 g_slist_free (source->poll_fds);
1439 source->poll_fds = NULL;
1440 g_free (source);
1443 if (!have_lock && context)
1444 UNLOCK_CONTEXT (context);
1446 if (old_cb_funcs)
1448 if (have_lock)
1449 UNLOCK_CONTEXT (context);
1451 old_cb_funcs->unref (old_cb_data);
1453 if (have_lock)
1454 LOCK_CONTEXT (context);
1459 * g_source_unref:
1460 * @source: a #GSource
1462 * Decreases the reference count of a source by one. If the
1463 * resulting reference count is zero the source and associated
1464 * memory will be destroyed.
1466 void
1467 g_source_unref (GSource *source)
1469 g_return_if_fail (source != NULL);
1471 g_source_unref_internal (source, source->context, FALSE);
1475 * g_main_context_find_source_by_id:
1476 * @context: a #GMainContext (if %NULL, the default context will be used)
1477 * @source_id: the source ID, as returned by g_source_get_id().
1479 * Finds a #GSource given a pair of context and ID.
1481 * Return value: the #GSource if found, otherwise, %NULL
1483 GSource *
1484 g_main_context_find_source_by_id (GMainContext *context,
1485 guint source_id)
1487 GSource *source;
1489 g_return_val_if_fail (source_id > 0, NULL);
1491 if (context == NULL)
1492 context = g_main_context_default ();
1494 LOCK_CONTEXT (context);
1496 source = context->source_list;
1497 while (source)
1499 if (!SOURCE_DESTROYED (source) &&
1500 source->source_id == source_id)
1501 break;
1502 source = source->next;
1505 UNLOCK_CONTEXT (context);
1507 return source;
1511 * g_main_context_find_source_by_funcs_user_data:
1512 * @context: a #GMainContext (if %NULL, the default context will be used).
1513 * @funcs: the @source_funcs passed to g_source_new().
1514 * @user_data: the user data from the callback.
1516 * Finds a source with the given source functions and user data. If
1517 * multiple sources exist with the same source function and user data,
1518 * the first one found will be returned.
1520 * Return value: the source, if one was found, otherwise %NULL
1522 GSource *
1523 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1524 GSourceFuncs *funcs,
1525 gpointer user_data)
1527 GSource *source;
1529 g_return_val_if_fail (funcs != NULL, NULL);
1531 if (context == NULL)
1532 context = g_main_context_default ();
1534 LOCK_CONTEXT (context);
1536 source = context->source_list;
1537 while (source)
1539 if (!SOURCE_DESTROYED (source) &&
1540 source->source_funcs == funcs &&
1541 source->callback_funcs)
1543 GSourceFunc callback;
1544 gpointer callback_data;
1546 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1548 if (callback_data == user_data)
1549 break;
1551 source = source->next;
1554 UNLOCK_CONTEXT (context);
1556 return source;
1560 * g_main_context_find_source_by_user_data:
1561 * @context: a #GMainContext
1562 * @user_data: the user_data for the callback.
1564 * Finds a source with the given user data for the callback. If
1565 * multiple sources exist with the same user data, the first
1566 * one found will be returned.
1568 * Return value: the source, if one was found, otherwise %NULL
1570 GSource *
1571 g_main_context_find_source_by_user_data (GMainContext *context,
1572 gpointer user_data)
1574 GSource *source;
1576 if (context == NULL)
1577 context = g_main_context_default ();
1579 LOCK_CONTEXT (context);
1581 source = context->source_list;
1582 while (source)
1584 if (!SOURCE_DESTROYED (source) &&
1585 source->callback_funcs)
1587 GSourceFunc callback;
1588 gpointer callback_data = NULL;
1590 source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1592 if (callback_data == user_data)
1593 break;
1595 source = source->next;
1598 UNLOCK_CONTEXT (context);
1600 return source;
1604 * g_source_remove:
1605 * @tag: the ID of the source to remove.
1607 * Removes the source with the given id from the default main context.
1608 * The id of
1609 * a #GSource is given by g_source_get_id(), or will be returned by the
1610 * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1611 * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1612 * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1614 * See also g_source_destroy().
1616 * Return value: %TRUE if the source was found and removed.
1618 gboolean
1619 g_source_remove (guint tag)
1621 GSource *source;
1623 g_return_val_if_fail (tag > 0, FALSE);
1625 source = g_main_context_find_source_by_id (NULL, tag);
1626 if (source)
1627 g_source_destroy (source);
1629 return source != NULL;
1633 * g_source_remove_by_user_data:
1634 * @user_data: the user_data for the callback.
1636 * Removes a source from the default main loop context given the user
1637 * data for the callback. If multiple sources exist with the same user
1638 * data, only one will be destroyed.
1640 * Return value: %TRUE if a source was found and removed.
1642 gboolean
1643 g_source_remove_by_user_data (gpointer user_data)
1645 GSource *source;
1647 source = g_main_context_find_source_by_user_data (NULL, user_data);
1648 if (source)
1650 g_source_destroy (source);
1651 return TRUE;
1653 else
1654 return FALSE;
1658 * g_source_remove_by_funcs_user_data:
1659 * @funcs: The @source_funcs passed to g_source_new()
1660 * @user_data: the user data for the callback
1662 * Removes a source from the default main loop context given the
1663 * source functions and user data. If multiple sources exist with the
1664 * same source functions and user data, only one will be destroyed.
1666 * Return value: %TRUE if a source was found and removed.
1668 gboolean
1669 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1670 gpointer user_data)
1672 GSource *source;
1674 g_return_val_if_fail (funcs != NULL, FALSE);
1676 source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1677 if (source)
1679 g_source_destroy (source);
1680 return TRUE;
1682 else
1683 return FALSE;
1687 * g_get_current_time:
1688 * @result: #GTimeVal structure in which to store current time.
1690 * Equivalent to the UNIX gettimeofday() function, but portable.
1692 void
1693 g_get_current_time (GTimeVal *result)
1695 #ifndef G_OS_WIN32
1696 struct timeval r;
1698 g_return_if_fail (result != NULL);
1700 /*this is required on alpha, there the timeval structs are int's
1701 not longs and a cast only would fail horribly*/
1702 gettimeofday (&r, NULL);
1703 result->tv_sec = r.tv_sec;
1704 result->tv_usec = r.tv_usec;
1705 #else
1706 FILETIME ft;
1707 guint64 *time64 = (guint64 *) &ft;
1709 GetSystemTimeAsFileTime (&ft);
1711 /* Convert from 100s of nanoseconds since 1601-01-01
1712 * to Unix epoch. Yes, this is Y2038 unsafe.
1714 *time64 -= G_GINT64_CONSTANT (116444736000000000);
1715 *time64 /= 10;
1717 result->tv_sec = *time64 / 1000000;
1718 result->tv_usec = *time64 % 1000000;
1719 #endif
1722 static void
1723 g_main_dispatch_free (gpointer dispatch)
1725 g_slice_free (GMainDispatch, dispatch);
1728 /* Running the main loop */
1730 static GMainDispatch *
1731 get_dispatch (void)
1733 static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
1734 GMainDispatch *dispatch = g_static_private_get (&depth_private);
1735 if (!dispatch)
1737 dispatch = g_slice_new0 (GMainDispatch);
1738 g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
1741 return dispatch;
1745 * g_main_depth:
1747 * Return value: The main loop recursion level in the current thread
1749 * Returns the depth of the stack of calls to
1750 * g_main_context_dispatch() on any #GMainContext in the current thread.
1751 * That is, when called from the toplevel, it gives 0. When
1752 * called from within a callback from g_main_context_iteration()
1753 * (or g_main_loop_run(), etc.) it returns 1. When called from within
1754 * a callback to a recursive call to g_main_context_iterate(),
1755 * it returns 2. And so forth.
1757 * This function is useful in a situation like the following:
1758 * Imagine an extremely simple "garbage collected" system.
1760 * <example>
1761 * static GList *free_list;
1763 * gpointer
1764 * allocate_memory (gsize size)
1765 * {
1766 * gpointer result = g_malloc (size);
1767 * free_list = g_list_prepend (free_list, result);
1768 * return result;
1771 * void
1772 * free_allocated_memory (void)
1774 * GList *l;
1775 * for (l = free_list; l; l = l->next);
1776 * g_free (l->data);
1777 * g_list_free (free_list);
1778 * free_list = NULL;
1781 * [...]
1783 * while (TRUE);
1785 * g_main_context_iteration (NULL, TRUE);
1786 * free_allocated_memory();
1788 * </example>
1790 * This works from an application, however, if you want to do the same
1791 * thing from a library, it gets more difficult, since you no longer
1792 * control the main loop. You might think you can simply use an idle
1793 * function to make the call to free_allocated_memory(), but that
1794 * doesn't work, since the idle function could be called from a
1795 * recursive callback. This can be fixed by using g_main_depth()
1797 * <example>
1798 * gpointer
1799 * allocate_memory (gsize size)
1800 * {
1801 * FreeListBlock *block = g_new (FreeListBlock, 1);\
1802 * block->mem = g_malloc (size);
1803 * block->depth = g_main_depth ();
1804 * free_list = g_list_prepend (free_list, block);
1805 * return block->mem;
1808 * void
1809 * free_allocated_memory (void)
1811 * GList *l;
1813 * int depth = g_main_depth ();
1814 * for (l = free_list; l; );
1816 * GList *next = l->next;
1817 * FreeListBlock *block = l->data;
1818 * if (block->depth > depth)
1820 * g_free (block->mem);
1821 * g_free (block);
1822 * free_list = g_list_delete_link (free_list, l);
1825 * l = next;
1828 * </example>
1830 * There is a temptation to use g_main_depth() to solve
1831 * problems with reentrancy. For instance, while waiting for data
1832 * to be received from the network in response to a menu item,
1833 * the menu item might be selected again. It might seem that
1834 * one could make the menu item's callback return immediately
1835 * and do nothing if g_main_depth() returns a value greater than 1.
1836 * However, this should be avoided since the user then sees selecting
1837 * the menu item do nothing. Furthermore, you'll find yourself adding
1838 * these checks all over your code, since there are doubtless many,
1839 * many things that the user could do. Instead, you can use the
1840 * following techniques:
1842 * <orderedlist>
1843 * <listitem>
1844 * <para>
1845 * Use gtk_widget_set_sensitive() or modal dialogs to prevent
1846 * the user from interacting with elements while the main
1847 * loop is recursing.
1848 * </para>
1849 * </listitem>
1850 * <listitem>
1851 * <para>
1852 * Avoid main loop recursion in situations where you can't handle
1853 * arbitrary callbacks. Instead, structure your code so that you
1854 * simply return to the main loop and then get called again when
1855 * there is more work to do.
1856 * </para>
1857 * </listitem>
1858 * </orderedlist>
1861 g_main_depth (void)
1863 GMainDispatch *dispatch = get_dispatch ();
1864 return dispatch->depth;
1868 * g_main_current_source:
1870 * Returns the currently firing source for this thread.
1872 * Return value: The currently firing source or %NULL.
1874 * Since: 2.12
1876 GSource *
1877 g_main_current_source (void)
1879 GMainDispatch *dispatch = get_dispatch ();
1880 return dispatch->source ? dispatch->source->data : NULL;
1884 * g_source_is_destroyed:
1885 * @source: a #GSource
1887 * Returns whether @source has been destroyed.
1889 * This is important when you operate upon your objects
1890 * from within idle handlers, but may have freed the object
1891 * before the dispatch of your idle handler.
1893 * <informalexample><programlisting>
1894 * static gboolean
1895 * idle_callback (gpointer data)
1897 * SomeWidget *self = data;
1899 * GDK_THREADS_ENTER (<!-- -->);
1900 * /<!-- -->* do stuff with self *<!-- -->/
1901 * self->idle_id = 0;
1902 * GDK_THREADS_LEAVE (<!-- -->);
1904 * return FALSE;
1907 * static void
1908 * some_widget_do_stuff_later (SomeWidget *self)
1910 * self->idle_id = g_idle_add (idle_callback, self);
1913 * static void
1914 * some_widget_finalize (GObject *object)
1916 * SomeWidget *self = SOME_WIDGET (object);
1918 * if (self->idle_id)
1919 * g_source_remove (self->idle_id);
1921 * G_OBJECT_CLASS (parent_class)->finalize (object);
1923 * </programlisting></informalexample>
1925 * This will fail in a multi-threaded application if the
1926 * widget is destroyed before the idle handler fires due
1927 * to the use after free in the callback. A solution, to
1928 * this particular problem, is to check to if the source
1929 * has already been destroy within the callback.
1931 * <informalexample><programlisting>
1932 * static gboolean
1933 * idle_callback (gpointer data)
1935 * SomeWidget *self = data;
1937 * GDK_THREADS_ENTER ();
1938 * if (!g_source_is_destroyed (g_main_current_source ()))
1940 * /<!-- -->* do stuff with self *<!-- -->/
1942 * GDK_THREADS_LEAVE ();
1944 * return FALSE;
1946 * </programlisting></informalexample>
1948 * Return value: %TRUE if the source has been destroyed
1950 gboolean
1951 g_source_is_destroyed (GSource *source)
1953 return SOURCE_DESTROYED (source);
1957 /* Temporarily remove all this source's file descriptors from the
1958 * poll(), so that if data comes available for one of the file descriptors
1959 * we don't continually spin in the poll()
1961 /* HOLDS: source->context's lock */
1962 static void
1963 block_source (GSource *source)
1965 GSList *tmp_list;
1967 g_return_if_fail (!SOURCE_BLOCKED (source));
1969 tmp_list = source->poll_fds;
1970 while (tmp_list)
1972 g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
1973 tmp_list = tmp_list->next;
1977 /* HOLDS: source->context's lock */
1978 static void
1979 unblock_source (GSource *source)
1981 GSList *tmp_list;
1983 g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
1984 g_return_if_fail (!SOURCE_DESTROYED (source));
1986 tmp_list = source->poll_fds;
1987 while (tmp_list)
1989 g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
1990 tmp_list = tmp_list->next;
1994 /* HOLDS: context's lock */
1995 static void
1996 g_main_dispatch (GMainContext *context)
1998 GMainDispatch *current = get_dispatch ();
1999 guint i;
2001 for (i = 0; i < context->pending_dispatches->len; i++)
2003 GSource *source = context->pending_dispatches->pdata[i];
2005 context->pending_dispatches->pdata[i] = NULL;
2006 g_assert (source);
2008 source->flags &= ~G_SOURCE_READY;
2010 if (!SOURCE_DESTROYED (source))
2012 gboolean was_in_call;
2013 gpointer user_data = NULL;
2014 GSourceFunc callback = NULL;
2015 GSourceCallbackFuncs *cb_funcs;
2016 gpointer cb_data;
2017 gboolean need_destroy;
2019 gboolean (*dispatch) (GSource *,
2020 GSourceFunc,
2021 gpointer);
2023 dispatch = source->source_funcs->dispatch;
2024 cb_funcs = source->callback_funcs;
2025 cb_data = source->callback_data;
2027 if (cb_funcs)
2028 cb_funcs->ref (cb_data);
2030 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2031 block_source (source);
2033 was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2034 source->flags |= G_HOOK_FLAG_IN_CALL;
2036 if (cb_funcs)
2037 cb_funcs->get (cb_data, source, &callback, &user_data);
2039 UNLOCK_CONTEXT (context);
2041 current->depth++;
2042 current->source = g_slist_prepend (current->source, source);
2043 need_destroy = ! dispatch (source,
2044 callback,
2045 user_data);
2046 current->source = g_slist_remove (current->source, source);
2047 current->depth--;
2049 if (cb_funcs)
2050 cb_funcs->unref (cb_data);
2052 LOCK_CONTEXT (context);
2054 if (!was_in_call)
2055 source->flags &= ~G_HOOK_FLAG_IN_CALL;
2057 if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2058 !SOURCE_DESTROYED (source))
2059 unblock_source (source);
2061 /* Note: this depends on the fact that we can't switch
2062 * sources from one main context to another
2064 if (need_destroy && !SOURCE_DESTROYED (source))
2066 g_assert (source->context == context);
2067 g_source_destroy_internal (source, context, TRUE);
2071 SOURCE_UNREF (source, context);
2074 g_ptr_array_set_size (context->pending_dispatches, 0);
2077 /* Holds context's lock */
2078 static inline GSource *
2079 next_valid_source (GMainContext *context,
2080 GSource *source)
2082 GSource *new_source = source ? source->next : context->source_list;
2084 while (new_source)
2086 if (!SOURCE_DESTROYED (new_source))
2088 new_source->ref_count++;
2089 break;
2092 new_source = new_source->next;
2095 if (source)
2096 SOURCE_UNREF (source, context);
2098 return new_source;
2102 * g_main_context_acquire:
2103 * @context: a #GMainContext
2105 * Tries to become the owner of the specified context.
2106 * If some other context is the owner of the context,
2107 * returns %FALSE immediately. Ownership is properly
2108 * recursive: the owner can require ownership again
2109 * and will release ownership when g_main_context_release()
2110 * is called as many times as g_main_context_acquire().
2112 * You must be the owner of a context before you
2113 * can call g_main_context_prepare(), g_main_context_query(),
2114 * g_main_context_check(), g_main_context_dispatch().
2116 * Return value: %TRUE if the operation succeeded, and
2117 * this thread is now the owner of @context.
2119 gboolean
2120 g_main_context_acquire (GMainContext *context)
2122 #ifdef G_THREADS_ENABLED
2123 gboolean result = FALSE;
2124 GThread *self = G_THREAD_SELF;
2126 if (context == NULL)
2127 context = g_main_context_default ();
2129 LOCK_CONTEXT (context);
2131 if (!context->owner)
2133 context->owner = self;
2134 g_assert (context->owner_count == 0);
2137 if (context->owner == self)
2139 context->owner_count++;
2140 result = TRUE;
2143 UNLOCK_CONTEXT (context);
2145 return result;
2146 #else /* !G_THREADS_ENABLED */
2147 return TRUE;
2148 #endif /* G_THREADS_ENABLED */
2152 * g_main_context_release:
2153 * @context: a #GMainContext
2155 * Releases ownership of a context previously acquired by this thread
2156 * with g_main_context_acquire(). If the context was acquired multiple
2157 * times, the only release ownership when g_main_context_release()
2158 * is called as many times as it was acquired.
2160 void
2161 g_main_context_release (GMainContext *context)
2163 #ifdef G_THREADS_ENABLED
2164 if (context == NULL)
2165 context = g_main_context_default ();
2167 LOCK_CONTEXT (context);
2169 context->owner_count--;
2170 if (context->owner_count == 0)
2172 context->owner = NULL;
2174 if (context->waiters)
2176 GMainWaiter *waiter = context->waiters->data;
2177 gboolean loop_internal_waiter =
2178 (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
2179 context->waiters = g_slist_delete_link (context->waiters,
2180 context->waiters);
2181 if (!loop_internal_waiter)
2182 g_mutex_lock (waiter->mutex);
2184 g_cond_signal (waiter->cond);
2186 if (!loop_internal_waiter)
2187 g_mutex_unlock (waiter->mutex);
2191 UNLOCK_CONTEXT (context);
2192 #endif /* G_THREADS_ENABLED */
2196 * g_main_context_wait:
2197 * @context: a #GMainContext
2198 * @cond: a condition variable
2199 * @mutex: a mutex, currently held
2201 * Tries to become the owner of the specified context,
2202 * as with g_main_context_acquire(). But if another thread
2203 * is the owner, atomically drop @mutex and wait on @cond until
2204 * that owner releases ownership or until @cond is signaled, then
2205 * try again (once) to become the owner.
2207 * Return value: %TRUE if the operation succeeded, and
2208 * this thread is now the owner of @context.
2210 gboolean
2211 g_main_context_wait (GMainContext *context,
2212 GCond *cond,
2213 GMutex *mutex)
2215 #ifdef G_THREADS_ENABLED
2216 gboolean result = FALSE;
2217 GThread *self = G_THREAD_SELF;
2218 gboolean loop_internal_waiter;
2220 if (context == NULL)
2221 context = g_main_context_default ();
2223 loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2225 if (!loop_internal_waiter)
2226 LOCK_CONTEXT (context);
2228 if (context->owner && context->owner != self)
2230 GMainWaiter waiter;
2232 waiter.cond = cond;
2233 waiter.mutex = mutex;
2235 context->waiters = g_slist_append (context->waiters, &waiter);
2237 if (!loop_internal_waiter)
2238 UNLOCK_CONTEXT (context);
2239 g_cond_wait (cond, mutex);
2240 if (!loop_internal_waiter)
2241 LOCK_CONTEXT (context);
2243 context->waiters = g_slist_remove (context->waiters, &waiter);
2246 if (!context->owner)
2248 context->owner = self;
2249 g_assert (context->owner_count == 0);
2252 if (context->owner == self)
2254 context->owner_count++;
2255 result = TRUE;
2258 if (!loop_internal_waiter)
2259 UNLOCK_CONTEXT (context);
2261 return result;
2262 #else /* !G_THREADS_ENABLED */
2263 return TRUE;
2264 #endif /* G_THREADS_ENABLED */
2268 * g_main_context_prepare:
2269 * @context: a #GMainContext
2270 * @priority: location to store priority of highest priority
2271 * source already ready.
2273 * Prepares to poll sources within a main loop. The resulting information
2274 * for polling is determined by calling g_main_context_query ().
2276 * Return value: %TRUE if some source is ready to be dispatched
2277 * prior to polling.
2279 gboolean
2280 g_main_context_prepare (GMainContext *context,
2281 gint *priority)
2283 gint i;
2284 gint n_ready = 0;
2285 gint current_priority = G_MAXINT;
2286 GSource *source;
2288 if (context == NULL)
2289 context = g_main_context_default ();
2291 LOCK_CONTEXT (context);
2293 context->time_is_current = FALSE;
2295 if (context->in_check_or_prepare)
2297 g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2298 "prepare() member.");
2299 UNLOCK_CONTEXT (context);
2300 return FALSE;
2303 #ifdef G_THREADS_ENABLED
2304 if (context->poll_waiting)
2306 g_warning("g_main_context_prepare(): main loop already active in another thread");
2307 UNLOCK_CONTEXT (context);
2308 return FALSE;
2311 context->poll_waiting = TRUE;
2312 #endif /* G_THREADS_ENABLED */
2314 #if 0
2315 /* If recursing, finish up current dispatch, before starting over */
2316 if (context->pending_dispatches)
2318 if (dispatch)
2319 g_main_dispatch (context, &current_time);
2321 UNLOCK_CONTEXT (context);
2322 return TRUE;
2324 #endif
2326 /* If recursing, clear list of pending dispatches */
2328 for (i = 0; i < context->pending_dispatches->len; i++)
2330 if (context->pending_dispatches->pdata[i])
2331 SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2333 g_ptr_array_set_size (context->pending_dispatches, 0);
2335 /* Prepare all sources */
2337 context->timeout = -1;
2339 source = next_valid_source (context, NULL);
2340 while (source)
2342 gint source_timeout = -1;
2344 if ((n_ready > 0) && (source->priority > current_priority))
2346 SOURCE_UNREF (source, context);
2347 break;
2349 if (SOURCE_BLOCKED (source))
2350 goto next;
2352 if (!(source->flags & G_SOURCE_READY))
2354 gboolean result;
2355 gboolean (*prepare) (GSource *source,
2356 gint *timeout);
2358 prepare = source->source_funcs->prepare;
2359 context->in_check_or_prepare++;
2360 UNLOCK_CONTEXT (context);
2362 result = (*prepare) (source, &source_timeout);
2364 LOCK_CONTEXT (context);
2365 context->in_check_or_prepare--;
2367 if (result)
2368 source->flags |= G_SOURCE_READY;
2371 if (source->flags & G_SOURCE_READY)
2373 n_ready++;
2374 current_priority = source->priority;
2375 context->timeout = 0;
2378 if (source_timeout >= 0)
2380 if (context->timeout < 0)
2381 context->timeout = source_timeout;
2382 else
2383 context->timeout = MIN (context->timeout, source_timeout);
2386 next:
2387 source = next_valid_source (context, source);
2390 UNLOCK_CONTEXT (context);
2392 if (priority)
2393 *priority = current_priority;
2395 return (n_ready > 0);
2399 * g_main_context_query:
2400 * @context: a #GMainContext
2401 * @max_priority: maximum priority source to check
2402 * @timeout_: location to store timeout to be used in polling
2403 * @fds: location to store #GPollFD records that need to be polled.
2404 * @n_fds: length of @fds.
2406 * Determines information necessary to poll this main loop.
2408 * Return value: the number of records actually stored in @fds,
2409 * or, if more than @n_fds records need to be stored, the number
2410 * of records that need to be stored.
2412 gint
2413 g_main_context_query (GMainContext *context,
2414 gint max_priority,
2415 gint *timeout,
2416 GPollFD *fds,
2417 gint n_fds)
2419 gint n_poll;
2420 GPollRec *pollrec;
2422 LOCK_CONTEXT (context);
2424 pollrec = context->poll_records;
2425 n_poll = 0;
2426 while (pollrec && max_priority >= pollrec->priority)
2428 if (pollrec->fd->events)
2430 if (n_poll < n_fds)
2432 fds[n_poll].fd = pollrec->fd->fd;
2433 /* In direct contradiction to the Unix98 spec, IRIX runs into
2434 * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2435 * flags in the events field of the pollfd while it should
2436 * just ignoring them. So we mask them out here.
2438 fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2439 fds[n_poll].revents = 0;
2441 n_poll++;
2444 pollrec = pollrec->next;
2447 #ifdef G_THREADS_ENABLED
2448 context->poll_changed = FALSE;
2449 #endif
2451 if (timeout)
2453 *timeout = context->timeout;
2454 if (*timeout != 0)
2455 context->time_is_current = FALSE;
2458 UNLOCK_CONTEXT (context);
2460 return n_poll;
2464 * g_main_context_check:
2465 * @context: a #GMainContext
2466 * @max_priority: the maximum numerical priority of sources to check
2467 * @fds: array of #GPollFD's that was passed to the last call to
2468 * g_main_context_query()
2469 * @n_fds: return value of g_main_context_query()
2471 * Passes the results of polling back to the main loop.
2473 * Return value: %TRUE if some sources are ready to be dispatched.
2475 gboolean
2476 g_main_context_check (GMainContext *context,
2477 gint max_priority,
2478 GPollFD *fds,
2479 gint n_fds)
2481 GSource *source;
2482 GPollRec *pollrec;
2483 gint n_ready = 0;
2484 gint i;
2486 LOCK_CONTEXT (context);
2488 if (context->in_check_or_prepare)
2490 g_warning ("g_main_context_check() called recursively from within a source's check() or "
2491 "prepare() member.");
2492 UNLOCK_CONTEXT (context);
2493 return FALSE;
2496 #ifdef G_THREADS_ENABLED
2497 if (!context->poll_waiting)
2499 #ifndef G_OS_WIN32
2500 gchar a;
2501 read (context->wake_up_pipe[0], &a, 1);
2502 #endif
2504 else
2505 context->poll_waiting = FALSE;
2507 /* If the set of poll file descriptors changed, bail out
2508 * and let the main loop rerun
2510 if (context->poll_changed)
2512 UNLOCK_CONTEXT (context);
2513 return 0;
2515 #endif /* G_THREADS_ENABLED */
2517 pollrec = context->poll_records;
2518 i = 0;
2519 while (i < n_fds)
2521 if (pollrec->fd->events)
2523 pollrec->fd->revents = fds[i].revents;
2524 i++;
2526 pollrec = pollrec->next;
2529 source = next_valid_source (context, NULL);
2530 while (source)
2532 if ((n_ready > 0) && (source->priority > max_priority))
2534 SOURCE_UNREF (source, context);
2535 break;
2537 if (SOURCE_BLOCKED (source))
2538 goto next;
2540 if (!(source->flags & G_SOURCE_READY))
2542 gboolean result;
2543 gboolean (*check) (GSource *source);
2545 check = source->source_funcs->check;
2547 context->in_check_or_prepare++;
2548 UNLOCK_CONTEXT (context);
2550 result = (*check) (source);
2552 LOCK_CONTEXT (context);
2553 context->in_check_or_prepare--;
2555 if (result)
2556 source->flags |= G_SOURCE_READY;
2559 if (source->flags & G_SOURCE_READY)
2561 source->ref_count++;
2562 g_ptr_array_add (context->pending_dispatches, source);
2564 n_ready++;
2566 /* never dispatch sources with less priority than the first
2567 * one we choose to dispatch
2569 max_priority = source->priority;
2572 next:
2573 source = next_valid_source (context, source);
2576 UNLOCK_CONTEXT (context);
2578 return n_ready > 0;
2582 * g_main_context_dispatch:
2583 * @context: a #GMainContext
2585 * Dispatches all pending sources.
2587 void
2588 g_main_context_dispatch (GMainContext *context)
2590 LOCK_CONTEXT (context);
2592 if (context->pending_dispatches->len > 0)
2594 g_main_dispatch (context);
2597 UNLOCK_CONTEXT (context);
2600 /* HOLDS context lock */
2601 static gboolean
2602 g_main_context_iterate (GMainContext *context,
2603 gboolean block,
2604 gboolean dispatch,
2605 GThread *self)
2607 gint max_priority;
2608 gint timeout;
2609 gboolean some_ready;
2610 gint nfds, allocated_nfds;
2611 GPollFD *fds = NULL;
2613 UNLOCK_CONTEXT (context);
2615 #ifdef G_THREADS_ENABLED
2616 if (!g_main_context_acquire (context))
2618 gboolean got_ownership;
2620 g_return_val_if_fail (g_thread_supported (), FALSE);
2622 if (!block)
2623 return FALSE;
2625 LOCK_CONTEXT (context);
2627 if (!context->cond)
2628 context->cond = g_cond_new ();
2630 got_ownership = g_main_context_wait (context,
2631 context->cond,
2632 g_static_mutex_get_mutex (&context->mutex));
2634 if (!got_ownership)
2636 UNLOCK_CONTEXT (context);
2637 return FALSE;
2640 else
2641 LOCK_CONTEXT (context);
2642 #endif /* G_THREADS_ENABLED */
2644 if (!context->cached_poll_array)
2646 context->cached_poll_array_size = context->n_poll_records;
2647 context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2650 allocated_nfds = context->cached_poll_array_size;
2651 fds = context->cached_poll_array;
2653 UNLOCK_CONTEXT (context);
2655 g_main_context_prepare (context, &max_priority);
2657 while ((nfds = g_main_context_query (context, max_priority, &timeout, fds,
2658 allocated_nfds)) > allocated_nfds)
2660 LOCK_CONTEXT (context);
2661 g_free (fds);
2662 context->cached_poll_array_size = allocated_nfds = nfds;
2663 context->cached_poll_array = fds = g_new (GPollFD, nfds);
2664 UNLOCK_CONTEXT (context);
2667 if (!block)
2668 timeout = 0;
2670 g_main_context_poll (context, timeout, max_priority, fds, nfds);
2672 some_ready = g_main_context_check (context, max_priority, fds, nfds);
2674 if (dispatch)
2675 g_main_context_dispatch (context);
2677 #ifdef G_THREADS_ENABLED
2678 g_main_context_release (context);
2679 #endif /* G_THREADS_ENABLED */
2681 LOCK_CONTEXT (context);
2683 return some_ready;
2687 * g_main_context_pending:
2688 * @context: a #GMainContext (if %NULL, the default context will be used)
2690 * Checks if any sources have pending events for the given context.
2692 * Return value: %TRUE if events are pending.
2694 gboolean
2695 g_main_context_pending (GMainContext *context)
2697 gboolean retval;
2699 if (!context)
2700 context = g_main_context_default();
2702 LOCK_CONTEXT (context);
2703 retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
2704 UNLOCK_CONTEXT (context);
2706 return retval;
2710 * g_main_context_iteration:
2711 * @context: a #GMainContext (if %NULL, the default context will be used)
2712 * @may_block: whether the call may block.
2714 * Runs a single iteration for the given main loop. This involves
2715 * checking to see if any event sources are ready to be processed,
2716 * then if no events sources are ready and @may_block is %TRUE, waiting
2717 * for a source to become ready, then dispatching the highest priority
2718 * events sources that are ready. Note that even when @may_block is %TRUE,
2719 * it is still possible for g_main_context_iteration() to return
2720 * %FALSE, since the the wait may be interrupted for other
2721 * reasons than an event source becoming ready.
2723 * Return value: %TRUE if events were dispatched.
2725 gboolean
2726 g_main_context_iteration (GMainContext *context, gboolean may_block)
2728 gboolean retval;
2730 if (!context)
2731 context = g_main_context_default();
2733 LOCK_CONTEXT (context);
2734 retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
2735 UNLOCK_CONTEXT (context);
2737 return retval;
2741 * g_main_loop_new:
2742 * @context: a #GMainContext (if %NULL, the default context will be used).
2743 * @is_running: set to %TRUE to indicate that the loop is running. This
2744 * is not very important since calling g_main_loop_run() will set this to
2745 * %TRUE anyway.
2747 * Creates a new #GMainLoop structure.
2749 * Return value: a new #GMainLoop.
2751 GMainLoop *
2752 g_main_loop_new (GMainContext *context,
2753 gboolean is_running)
2755 GMainLoop *loop;
2757 if (!context)
2758 context = g_main_context_default();
2760 g_main_context_ref (context);
2762 loop = g_new0 (GMainLoop, 1);
2763 loop->context = context;
2764 loop->is_running = is_running != FALSE;
2765 loop->ref_count = 1;
2767 return loop;
2771 * g_main_loop_ref:
2772 * @loop: a #GMainLoop
2774 * Increases the reference count on a #GMainLoop object by one.
2776 * Return value: @loop
2778 GMainLoop *
2779 g_main_loop_ref (GMainLoop *loop)
2781 g_return_val_if_fail (loop != NULL, NULL);
2782 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2784 g_atomic_int_inc (&loop->ref_count);
2786 return loop;
2790 * g_main_loop_unref:
2791 * @loop: a #GMainLoop
2793 * Decreases the reference count on a #GMainLoop object by one. If
2794 * the result is zero, free the loop and free all associated memory.
2796 void
2797 g_main_loop_unref (GMainLoop *loop)
2799 g_return_if_fail (loop != NULL);
2800 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2802 if (!g_atomic_int_dec_and_test (&loop->ref_count))
2803 return;
2805 g_main_context_unref (loop->context);
2806 g_free (loop);
2810 * g_main_loop_run:
2811 * @loop: a #GMainLoop
2813 * Runs a main loop until g_main_loop_quit() is called on the loop.
2814 * If this is called for the thread of the loop's #GMainContext,
2815 * it will process events from the loop, otherwise it will
2816 * simply wait.
2818 void
2819 g_main_loop_run (GMainLoop *loop)
2821 GThread *self = G_THREAD_SELF;
2823 g_return_if_fail (loop != NULL);
2824 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2826 #ifdef G_THREADS_ENABLED
2827 if (!g_main_context_acquire (loop->context))
2829 gboolean got_ownership = FALSE;
2831 /* Another thread owns this context */
2832 if (!g_thread_supported ())
2834 g_warning ("g_main_loop_run() was called from second thread but "
2835 "g_thread_init() was never called.");
2836 return;
2839 LOCK_CONTEXT (loop->context);
2841 g_atomic_int_inc (&loop->ref_count);
2843 if (!loop->is_running)
2844 loop->is_running = TRUE;
2846 if (!loop->context->cond)
2847 loop->context->cond = g_cond_new ();
2849 while (loop->is_running && !got_ownership)
2850 got_ownership = g_main_context_wait (loop->context,
2851 loop->context->cond,
2852 g_static_mutex_get_mutex (&loop->context->mutex));
2854 if (!loop->is_running)
2856 UNLOCK_CONTEXT (loop->context);
2857 if (got_ownership)
2858 g_main_context_release (loop->context);
2859 g_main_loop_unref (loop);
2860 return;
2863 g_assert (got_ownership);
2865 else
2866 LOCK_CONTEXT (loop->context);
2867 #endif /* G_THREADS_ENABLED */
2869 if (loop->context->in_check_or_prepare)
2871 g_warning ("g_main_loop_run(): called recursively from within a source's "
2872 "check() or prepare() member, iteration not possible.");
2873 return;
2876 g_atomic_int_inc (&loop->ref_count);
2877 loop->is_running = TRUE;
2878 while (loop->is_running)
2879 g_main_context_iterate (loop->context, TRUE, TRUE, self);
2881 UNLOCK_CONTEXT (loop->context);
2883 #ifdef G_THREADS_ENABLED
2884 g_main_context_release (loop->context);
2885 #endif /* G_THREADS_ENABLED */
2887 g_main_loop_unref (loop);
2891 * g_main_loop_quit:
2892 * @loop: a #GMainLoop
2894 * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
2895 * for the loop will return.
2897 void
2898 g_main_loop_quit (GMainLoop *loop)
2900 g_return_if_fail (loop != NULL);
2901 g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2903 LOCK_CONTEXT (loop->context);
2904 loop->is_running = FALSE;
2905 g_main_context_wakeup_unlocked (loop->context);
2907 #ifdef G_THREADS_ENABLED
2908 if (loop->context->cond)
2909 g_cond_broadcast (loop->context->cond);
2910 #endif /* G_THREADS_ENABLED */
2912 UNLOCK_CONTEXT (loop->context);
2916 * g_main_loop_is_running:
2917 * @loop: a #GMainLoop.
2919 * Checks to see if the main loop is currently being run via g_main_loop_run().
2921 * Return value: %TRUE if the mainloop is currently being run.
2923 gboolean
2924 g_main_loop_is_running (GMainLoop *loop)
2926 g_return_val_if_fail (loop != NULL, FALSE);
2927 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
2929 return loop->is_running;
2933 * g_main_loop_get_context:
2934 * @loop: a #GMainLoop.
2936 * Returns the #GMainContext of @loop.
2938 * Return value: the #GMainContext of @loop
2940 GMainContext *
2941 g_main_loop_get_context (GMainLoop *loop)
2943 g_return_val_if_fail (loop != NULL, NULL);
2944 g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2946 return loop->context;
2949 /* HOLDS: context's lock */
2950 static void
2951 g_main_context_poll (GMainContext *context,
2952 gint timeout,
2953 gint priority,
2954 GPollFD *fds,
2955 gint n_fds)
2957 #ifdef G_MAIN_POLL_DEBUG
2958 GTimer *poll_timer;
2959 GPollRec *pollrec;
2960 gint i;
2961 #endif
2963 GPollFunc poll_func;
2965 if (n_fds || timeout != 0)
2967 #ifdef G_MAIN_POLL_DEBUG
2968 g_print ("g_main_poll(%d) timeout: %d\n", n_fds, timeout);
2969 poll_timer = g_timer_new ();
2970 #endif
2972 LOCK_CONTEXT (context);
2974 poll_func = context->poll_func;
2976 UNLOCK_CONTEXT (context);
2977 if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
2979 #ifndef G_OS_WIN32
2980 g_warning ("poll(2) failed due to: %s.",
2981 g_strerror (errno));
2982 #else
2983 /* If g_poll () returns -1, it has already called g_warning() */
2984 #endif
2987 #ifdef G_MAIN_POLL_DEBUG
2988 LOCK_CONTEXT (context);
2990 g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
2991 n_fds,
2992 timeout,
2993 g_timer_elapsed (poll_timer, NULL));
2994 g_timer_destroy (poll_timer);
2995 pollrec = context->poll_records;
2996 i = 0;
2997 while (i < n_fds)
2999 if (pollrec->fd->events)
3001 if (fds[i].revents)
3003 g_print (" [%d:", fds[i].fd);
3004 if (fds[i].revents & G_IO_IN)
3005 g_print ("i");
3006 if (fds[i].revents & G_IO_OUT)
3007 g_print ("o");
3008 if (fds[i].revents & G_IO_PRI)
3009 g_print ("p");
3010 if (fds[i].revents & G_IO_ERR)
3011 g_print ("e");
3012 if (fds[i].revents & G_IO_HUP)
3013 g_print ("h");
3014 if (fds[i].revents & G_IO_NVAL)
3015 g_print ("n");
3016 g_print ("]");
3018 i++;
3020 pollrec = pollrec->next;
3022 g_print ("\n");
3024 UNLOCK_CONTEXT (context);
3025 #endif
3026 } /* if (n_fds || timeout != 0) */
3030 * g_main_context_add_poll:
3031 * @context: a #GMainContext (or %NULL for the default context)
3032 * @fd: a #GPollFD structure holding information about a file
3033 * descriptor to watch.
3034 * @priority: the priority for this file descriptor which should be
3035 * the same as the priority used for g_source_attach() to ensure that the
3036 * file descriptor is polled whenever the results may be needed.
3038 * Adds a file descriptor to the set of file descriptors polled for
3039 * this context. This will very seldomly be used directly. Instead
3040 * a typical event source will use g_source_add_poll() instead.
3042 void
3043 g_main_context_add_poll (GMainContext *context,
3044 GPollFD *fd,
3045 gint priority)
3047 if (!context)
3048 context = g_main_context_default ();
3050 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3051 g_return_if_fail (fd);
3053 LOCK_CONTEXT (context);
3054 g_main_context_add_poll_unlocked (context, priority, fd);
3055 UNLOCK_CONTEXT (context);
3058 /* HOLDS: main_loop_lock */
3059 static void
3060 g_main_context_add_poll_unlocked (GMainContext *context,
3061 gint priority,
3062 GPollFD *fd)
3064 GPollRec *lastrec, *pollrec;
3065 GPollRec *newrec = g_slice_new (GPollRec);
3067 /* This file descriptor may be checked before we ever poll */
3068 fd->revents = 0;
3069 newrec->fd = fd;
3070 newrec->priority = priority;
3072 lastrec = NULL;
3073 pollrec = context->poll_records;
3074 while (pollrec && priority >= pollrec->priority)
3076 lastrec = pollrec;
3077 pollrec = pollrec->next;
3080 if (lastrec)
3081 lastrec->next = newrec;
3082 else
3083 context->poll_records = newrec;
3085 newrec->next = pollrec;
3087 context->n_poll_records++;
3089 #ifdef G_THREADS_ENABLED
3090 context->poll_changed = TRUE;
3092 /* Now wake up the main loop if it is waiting in the poll() */
3093 g_main_context_wakeup_unlocked (context);
3094 #endif
3098 * g_main_context_remove_poll:
3099 * @context:a #GMainContext
3100 * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3102 * Removes file descriptor from the set of file descriptors to be
3103 * polled for a particular context.
3105 void
3106 g_main_context_remove_poll (GMainContext *context,
3107 GPollFD *fd)
3109 if (!context)
3110 context = g_main_context_default ();
3112 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3113 g_return_if_fail (fd);
3115 LOCK_CONTEXT (context);
3116 g_main_context_remove_poll_unlocked (context, fd);
3117 UNLOCK_CONTEXT (context);
3120 static void
3121 g_main_context_remove_poll_unlocked (GMainContext *context,
3122 GPollFD *fd)
3124 GPollRec *pollrec, *lastrec;
3126 lastrec = NULL;
3127 pollrec = context->poll_records;
3129 while (pollrec)
3131 if (pollrec->fd == fd)
3133 if (lastrec != NULL)
3134 lastrec->next = pollrec->next;
3135 else
3136 context->poll_records = pollrec->next;
3138 g_slice_free (GPollRec, pollrec);
3140 context->n_poll_records--;
3141 break;
3143 lastrec = pollrec;
3144 pollrec = pollrec->next;
3147 #ifdef G_THREADS_ENABLED
3148 context->poll_changed = TRUE;
3150 /* Now wake up the main loop if it is waiting in the poll() */
3151 g_main_context_wakeup_unlocked (context);
3152 #endif
3156 * g_source_get_current_time:
3157 * @source: a #GSource
3158 * @timeval: #GTimeVal structure in which to store current time.
3160 * Gets the "current time" to be used when checking
3161 * this source. The advantage of calling this function over
3162 * calling g_get_current_time() directly is that when
3163 * checking multiple sources, GLib can cache a single value
3164 * instead of having to repeatedly get the system time.
3166 void
3167 g_source_get_current_time (GSource *source,
3168 GTimeVal *timeval)
3170 GMainContext *context;
3172 g_return_if_fail (source->context != NULL);
3174 context = source->context;
3176 LOCK_CONTEXT (context);
3178 if (!context->time_is_current)
3180 g_get_current_time (&context->current_time);
3181 context->time_is_current = TRUE;
3184 *timeval = context->current_time;
3186 UNLOCK_CONTEXT (context);
3190 * g_main_context_set_poll_func:
3191 * @context: a #GMainContext
3192 * @func: the function to call to poll all file descriptors
3194 * Sets the function to use to handle polling of file descriptors. It
3195 * will be used instead of the poll() system call
3196 * (or GLib's replacement function, which is used where
3197 * poll() isn't available).
3199 * This function could possibly be used to integrate the GLib event
3200 * loop with an external event loop.
3202 void
3203 g_main_context_set_poll_func (GMainContext *context,
3204 GPollFunc func)
3206 if (!context)
3207 context = g_main_context_default ();
3209 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3211 LOCK_CONTEXT (context);
3213 if (func)
3214 context->poll_func = func;
3215 else
3217 #ifdef HAVE_POLL
3218 context->poll_func = (GPollFunc) poll;
3219 #else
3220 context->poll_func = (GPollFunc) g_poll;
3221 #endif
3224 UNLOCK_CONTEXT (context);
3228 * g_main_context_get_poll_func:
3229 * @context: a #GMainContext
3231 * Gets the poll function set by g_main_context_set_poll_func().
3233 * Return value: the poll function
3235 GPollFunc
3236 g_main_context_get_poll_func (GMainContext *context)
3238 GPollFunc result;
3240 if (!context)
3241 context = g_main_context_default ();
3243 g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3245 LOCK_CONTEXT (context);
3246 result = context->poll_func;
3247 UNLOCK_CONTEXT (context);
3249 return result;
3252 /* HOLDS: context's lock */
3253 /* Wake the main loop up from a poll() */
3254 static void
3255 g_main_context_wakeup_unlocked (GMainContext *context)
3257 #ifdef G_THREADS_ENABLED
3258 if (g_thread_supported() && context->poll_waiting)
3260 context->poll_waiting = FALSE;
3261 #ifndef G_OS_WIN32
3262 write (context->wake_up_pipe[1], "A", 1);
3263 #else
3264 ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
3265 #endif
3267 #endif
3271 * g_main_context_wakeup:
3272 * @context: a #GMainContext
3274 * If @context is currently waiting in a poll(), interrupt
3275 * the poll(), and continue the iteration process.
3277 void
3278 g_main_context_wakeup (GMainContext *context)
3280 if (!context)
3281 context = g_main_context_default ();
3283 g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3285 LOCK_CONTEXT (context);
3286 g_main_context_wakeup_unlocked (context);
3287 UNLOCK_CONTEXT (context);
3291 * g_main_context_is_owner:
3292 * @context: a #GMainContext
3294 * Determines whether this thread holds the (recursive)
3295 * ownership of this #GMaincontext. This is useful to
3296 * know before waiting on another thread that may be
3297 * blocking to get ownership of @context.
3299 * Returns: %TRUE if current thread is owner of @context.
3301 * Since: 2.10
3303 gboolean
3304 g_main_context_is_owner (GMainContext *context)
3306 gboolean is_owner;
3308 if (!context)
3309 context = g_main_context_default ();
3311 #ifdef G_THREADS_ENABLED
3312 LOCK_CONTEXT (context);
3313 is_owner = context->owner == G_THREAD_SELF;
3314 UNLOCK_CONTEXT (context);
3315 #else
3316 is_owner = TRUE;
3317 #endif
3319 return is_owner;
3322 /* Timeouts */
3324 static void
3325 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3326 GTimeVal *current_time)
3328 guint seconds = timeout_source->interval / 1000;
3329 guint msecs = timeout_source->interval - seconds * 1000;
3331 timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
3332 timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
3333 if (timeout_source->expiration.tv_usec >= 1000000)
3335 timeout_source->expiration.tv_usec -= 1000000;
3336 timeout_source->expiration.tv_sec++;
3340 static gboolean
3341 g_timeout_prepare (GSource *source,
3342 gint *timeout)
3344 glong sec;
3345 glong msec;
3346 GTimeVal current_time;
3348 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3350 g_source_get_current_time (source, &current_time);
3352 sec = timeout_source->expiration.tv_sec - current_time.tv_sec;
3353 msec = (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000;
3355 /* We do the following in a rather convoluted fashion to deal with
3356 * the fact that we don't have an integral type big enough to hold
3357 * the difference of two timevals in millseconds.
3359 if (sec < 0 || (sec == 0 && msec < 0))
3360 msec = 0;
3361 else
3363 glong interval_sec = timeout_source->interval / 1000;
3364 glong interval_msec = timeout_source->interval % 1000;
3366 if (msec < 0)
3368 msec += 1000;
3369 sec -= 1;
3372 if (sec > interval_sec ||
3373 (sec == interval_sec && msec > interval_msec))
3375 /* The system time has been set backwards, so we
3376 * reset the expiration time to now + timeout_source->interval;
3377 * this at least avoids hanging for long periods of time.
3379 g_timeout_set_expiration (timeout_source, &current_time);
3380 msec = MIN (G_MAXINT, timeout_source->interval);
3382 else
3384 msec = MIN (G_MAXINT, (guint)msec + 1000 * (guint)sec);
3388 *timeout = (gint)msec;
3390 return msec == 0;
3393 static gboolean
3394 g_timeout_check (GSource *source)
3396 GTimeVal current_time;
3397 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3399 g_source_get_current_time (source, &current_time);
3401 return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
3402 ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
3403 (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
3406 static gboolean
3407 g_timeout_dispatch (GSource *source,
3408 GSourceFunc callback,
3409 gpointer user_data)
3411 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3413 if (!callback)
3415 g_warning ("Timeout source dispatched without callback\n"
3416 "You must call g_source_set_callback().");
3417 return FALSE;
3420 if (callback (user_data))
3422 GTimeVal current_time;
3424 g_source_get_current_time (source, &current_time);
3425 g_timeout_set_expiration (timeout_source, &current_time);
3427 return TRUE;
3429 else
3430 return FALSE;
3434 * g_timeout_source_new:
3435 * @interval: the timeout interval in milliseconds.
3437 * Creates a new timeout source.
3439 * The source will not initially be associated with any #GMainContext
3440 * and must be added to one with g_source_attach() before it will be
3441 * executed.
3443 * Return value: the newly-created timeout source
3445 GSource *
3446 g_timeout_source_new (guint interval)
3448 GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3449 GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3450 GTimeVal current_time;
3452 timeout_source->interval = interval;
3454 g_get_current_time (&current_time);
3455 g_timeout_set_expiration (timeout_source, &current_time);
3457 return source;
3461 * g_timeout_add_full:
3462 * @priority: the priority of the idle source. Typically this will be in the
3463 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3464 * @interval: the time between calls to the function, in milliseconds
3465 * (1/1000ths of a second)
3466 * @function: function to call
3467 * @data: data to pass to @function
3468 * @notify: function to call when the idle is removed, or %NULL
3470 * Sets a function to be called at regular intervals, with the given
3471 * priority. The function is called repeatedly until it returns
3472 * %FALSE, at which point the timeout is automatically destroyed and
3473 * the function will not be called again. The @notify function is
3474 * called when the timeout is destroyed. The first call to the
3475 * function will be at the end of the first @interval.
3477 * Note that timeout functions may be delayed, due to the processing of other
3478 * event sources. Thus they should not be relied on for precise timing.
3479 * After each call to the timeout function, the time of the next
3480 * timeout is recalculated based on the current time and the given interval
3481 * (it does not try to 'catch up' time lost in delays).
3483 * Return value: the ID (greater than 0) of the event source.
3485 guint
3486 g_timeout_add_full (gint priority,
3487 guint interval,
3488 GSourceFunc function,
3489 gpointer data,
3490 GDestroyNotify notify)
3492 GSource *source;
3493 guint id;
3495 g_return_val_if_fail (function != NULL, 0);
3497 source = g_timeout_source_new (interval);
3499 if (priority != G_PRIORITY_DEFAULT)
3500 g_source_set_priority (source, priority);
3502 g_source_set_callback (source, function, data, notify);
3503 id = g_source_attach (source, NULL);
3504 g_source_unref (source);
3506 return id;
3510 * g_timeout_add:
3511 * @interval: the time between calls to the function, in milliseconds
3512 * (1/1000ths of a second)
3513 * @function: function to call
3514 * @data: data to pass to @function
3516 * Sets a function to be called at regular intervals, with the default
3517 * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly
3518 * until it returns %FALSE, at which point the timeout is automatically
3519 * destroyed and the function will not be called again. The first call
3520 * to the function will be at the end of the first @interval.
3522 * Note that timeout functions may be delayed, due to the processing of other
3523 * event sources. Thus they should not be relied on for precise timing.
3524 * After each call to the timeout function, the time of the next
3525 * timeout is recalculated based on the current time and the given interval
3526 * (it does not try to 'catch up' time lost in delays).
3528 * Return value: the ID (greater than 0) of the event source.
3530 guint
3531 g_timeout_add (guint32 interval,
3532 GSourceFunc function,
3533 gpointer data)
3535 return g_timeout_add_full (G_PRIORITY_DEFAULT,
3536 interval, function, data, NULL);
3539 /* Child watch functions */
3541 #ifdef G_OS_WIN32
3543 static gboolean
3544 g_child_watch_prepare (GSource *source,
3545 gint *timeout)
3547 *timeout = -1;
3548 return FALSE;
3552 static gboolean
3553 g_child_watch_check (GSource *source)
3555 GChildWatchSource *child_watch_source;
3556 gboolean child_exited;
3558 child_watch_source = (GChildWatchSource *) source;
3560 child_exited = child_watch_source->poll.revents & G_IO_IN;
3562 if (child_exited)
3564 DWORD child_status;
3567 * Note: We do _not_ check for the special value of STILL_ACTIVE
3568 * since we know that the process has exited and doing so runs into
3569 * problems if the child process "happens to return STILL_ACTIVE(259)"
3570 * as Microsoft's Platform SDK puts it.
3572 if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
3574 gchar *emsg = g_win32_error_message (GetLastError ());
3575 g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
3576 g_free (emsg);
3578 child_watch_source->child_status = -1;
3580 else
3581 child_watch_source->child_status = child_status;
3584 return child_exited;
3587 #else /* G_OS_WIN32 */
3589 static gboolean
3590 check_for_child_exited (GSource *source)
3592 GChildWatchSource *child_watch_source;
3593 gint count;
3595 /* protect against another SIGCHLD in the middle of this call */
3596 count = child_watch_count;
3598 child_watch_source = (GChildWatchSource *) source;
3600 if (child_watch_source->child_exited)
3601 return TRUE;
3603 if (child_watch_source->count < count)
3605 gint child_status;
3607 if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
3609 child_watch_source->child_status = child_status;
3610 child_watch_source->child_exited = TRUE;
3612 child_watch_source->count = count;
3615 return child_watch_source->child_exited;
3618 static gboolean
3619 g_child_watch_prepare (GSource *source,
3620 gint *timeout)
3622 *timeout = -1;
3624 return check_for_child_exited (source);
3628 static gboolean
3629 g_child_watch_check (GSource *source)
3631 return check_for_child_exited (source);
3634 #endif /* G_OS_WIN32 */
3636 static gboolean
3637 g_child_watch_dispatch (GSource *source,
3638 GSourceFunc callback,
3639 gpointer user_data)
3641 GChildWatchSource *child_watch_source;
3642 GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
3644 child_watch_source = (GChildWatchSource *) source;
3646 if (!callback)
3648 g_warning ("Child watch source dispatched without callback\n"
3649 "You must call g_source_set_callback().");
3650 return FALSE;
3653 (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
3655 /* We never keep a child watch source around as the child is gone */
3656 return FALSE;
3659 #ifndef G_OS_WIN32
3661 static void
3662 g_child_watch_signal_handler (int signum)
3664 child_watch_count ++;
3666 if (child_watch_init_state == CHILD_WATCH_INITIALIZED_THREADED)
3668 write (child_watch_wake_up_pipe[1], "B", 1);
3670 else
3672 /* We count on the signal interrupting the poll in the same thread.
3677 static void
3678 g_child_watch_source_init_single (void)
3680 struct sigaction action;
3682 g_assert (! g_thread_supported());
3683 g_assert (child_watch_init_state == CHILD_WATCH_UNINITIALIZED);
3685 child_watch_init_state = CHILD_WATCH_INITIALIZED_SINGLE;
3687 action.sa_handler = g_child_watch_signal_handler;
3688 sigemptyset (&action.sa_mask);
3689 action.sa_flags = SA_NOCLDSTOP;
3690 sigaction (SIGCHLD, &action, NULL);
3693 static gpointer
3694 child_watch_helper_thread (gpointer data)
3696 while (1)
3698 gchar b[20];
3699 GSList *list;
3701 read (child_watch_wake_up_pipe[0], b, 20);
3703 /* We were woken up. Wake up all other contexts in all other threads */
3704 G_LOCK (main_context_list);
3705 for (list = main_context_list; list; list = list->next)
3707 GMainContext *context;
3709 context = list->data;
3710 if (g_atomic_int_get (&context->ref_count) > 0)
3711 /* Due to racing conditions we can find ref_count == 0, in
3712 * that case, however, the context is still not destroyed
3713 * and no poll can be active, otherwise the ref_count
3714 * wouldn't be 0 */
3715 g_main_context_wakeup (context);
3717 G_UNLOCK (main_context_list);
3721 static void
3722 g_child_watch_source_init_multi_threaded (void)
3724 GError *error = NULL;
3725 struct sigaction action;
3727 g_assert (g_thread_supported());
3729 if (pipe (child_watch_wake_up_pipe) < 0)
3730 g_error ("Cannot create wake up pipe: %s\n", g_strerror (errno));
3731 fcntl (child_watch_wake_up_pipe[1], F_SETFL, O_NONBLOCK | fcntl (child_watch_wake_up_pipe[1], F_GETFL));
3733 /* We create a helper thread that polls on the wakeup pipe indefinitely */
3734 /* FIXME: Think this through for races */
3735 if (g_thread_create (child_watch_helper_thread, NULL, FALSE, &error) == NULL)
3736 g_error ("Cannot create a thread to monitor child exit status: %s\n", error->message);
3737 child_watch_init_state = CHILD_WATCH_INITIALIZED_THREADED;
3739 action.sa_handler = g_child_watch_signal_handler;
3740 sigemptyset (&action.sa_mask);
3741 action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
3742 sigaction (SIGCHLD, &action, NULL);
3745 static void
3746 g_child_watch_source_init_promote_single_to_threaded (void)
3748 g_child_watch_source_init_multi_threaded ();
3751 static void
3752 g_child_watch_source_init (void)
3754 if (g_thread_supported())
3756 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
3757 g_child_watch_source_init_multi_threaded ();
3758 else if (child_watch_init_state == CHILD_WATCH_INITIALIZED_SINGLE)
3759 g_child_watch_source_init_promote_single_to_threaded ();
3761 else
3763 if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
3764 g_child_watch_source_init_single ();
3768 #endif /* !G_OS_WIN32 */
3771 * g_child_watch_source_new:
3772 * @pid: process id of a child process to watch. On Windows, a HANDLE
3773 * for the process to watch (which actually doesn't have to be a child).
3775 * Creates a new child_watch source.
3777 * The source will not initially be associated with any #GMainContext
3778 * and must be added to one with g_source_attach() before it will be
3779 * executed.
3781 * Note that child watch sources can only be used in conjunction with
3782 * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
3783 * flag is used.
3785 * Note that on platforms where #GPid must be explicitely closed
3786 * (see g_spawn_close_pid()) @pid must not be closed while the
3787 * source is still active. Typically, you will want to call
3788 * g_spawn_close_pid() in the callback function for the source.
3790 * Note further that using g_child_watch_source_new() is not
3791 * compatible with calling <literal>waitpid(-1)</literal> in
3792 * the application. Calling waitpid() for individual pids will
3793 * still work fine.
3795 * Return value: the newly-created child watch source
3797 * Since: 2.4
3799 GSource *
3800 g_child_watch_source_new (GPid pid)
3802 GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
3803 GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
3805 #ifdef G_OS_WIN32
3806 child_watch_source->poll.fd = (int)pid;
3807 child_watch_source->poll.events = G_IO_IN;
3809 g_source_add_poll (source, &child_watch_source->poll);
3810 #else /* G_OS_WIN32 */
3811 g_child_watch_source_init ();
3812 #endif /* G_OS_WIN32 */
3814 child_watch_source->pid = pid;
3816 return source;
3820 * g_child_watch_add_full:
3821 * @priority: the priority of the idle source. Typically this will be in the
3822 * range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3823 * @pid: process id of a child process to watch
3824 * @function: function to call
3825 * @data: data to pass to @function
3826 * @notify: function to call when the idle is removed, or %NULL
3828 * Sets a function to be called when the child indicated by @pid exits, at a
3829 * default priority, #G_PRIORITY_DEFAULT.
3831 * Note that on platforms where #GPid must be explicitely closed
3832 * (see g_spawn_close_pid()) @pid must not be closed while the
3833 * source is still active. Typically, you will want to call
3834 * g_spawn_close_pid() in the callback function for the source.
3836 * GLib supports only a single callback per process id.
3838 * Return value: the ID (greater than 0) of the event source.
3840 * Since: 2.4
3842 guint
3843 g_child_watch_add_full (gint priority,
3844 GPid pid,
3845 GChildWatchFunc function,
3846 gpointer data,
3847 GDestroyNotify notify)
3849 GSource *source;
3850 guint id;
3852 g_return_val_if_fail (function != NULL, 0);
3854 source = g_child_watch_source_new (pid);
3856 if (priority != G_PRIORITY_DEFAULT)
3857 g_source_set_priority (source, priority);
3859 g_source_set_callback (source, (GSourceFunc) function, data, notify);
3860 id = g_source_attach (source, NULL);
3861 g_source_unref (source);
3863 return id;
3867 * g_child_watch_add:
3868 * @pid: process id of a child process to watch
3869 * @function: function to call
3870 * @data: data to pass to @function
3872 * Sets a function to be called when the child indicated by @pid exits, at a
3873 * default priority, #G_PRIORITY_DEFAULT.
3875 * Note that on platforms where #GPid must be explicitely closed
3876 * (see g_spawn_close_pid()) @pid must not be closed while the
3877 * source is still active. Typically, you will want to call
3878 * g_spawn_close_pid() in the callback function for the source.
3880 * GLib supports only a single callback per process id.
3882 * Return value: the ID (greater than 0) of the event source.
3884 * Since: 2.4
3886 guint
3887 g_child_watch_add (GPid pid,
3888 GChildWatchFunc function,
3889 gpointer data)
3891 return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
3895 /* Idle functions */
3897 static gboolean
3898 g_idle_prepare (GSource *source,
3899 gint *timeout)
3901 *timeout = 0;
3903 return TRUE;
3906 static gboolean
3907 g_idle_check (GSource *source)
3909 return TRUE;
3912 static gboolean
3913 g_idle_dispatch (GSource *source,
3914 GSourceFunc callback,
3915 gpointer user_data)
3917 if (!callback)
3919 g_warning ("Idle source dispatched without callback\n"
3920 "You must call g_source_set_callback().");
3921 return FALSE;
3924 return callback (user_data);
3928 * g_idle_source_new:
3930 * Creates a new idle source.
3932 * The source will not initially be associated with any #GMainContext
3933 * and must be added to one with g_source_attach() before it will be
3934 * executed. Note that the default priority for idle sources is
3935 * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
3936 * have a default priority of %G_PRIORITY_DEFAULT.
3938 * Return value: the newly-created idle source
3940 GSource *
3941 g_idle_source_new (void)
3943 GSource *source;
3945 source = g_source_new (&g_idle_funcs, sizeof (GSource));
3946 g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
3948 return source;
3952 * g_idle_add_full:
3953 * @priority: the priority of the idle source. Typically this will be in the
3954 * range btweeen #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3955 * @function: function to call
3956 * @data: data to pass to @function
3957 * @notify: function to call when the idle is removed, or %NULL
3959 * Adds a function to be called whenever there are no higher priority
3960 * events pending. If the function returns %FALSE it is automatically
3961 * removed from the list of event sources and will not be called again.
3963 * Return value: the ID (greater than 0) of the event source.
3965 guint
3966 g_idle_add_full (gint priority,
3967 GSourceFunc function,
3968 gpointer data,
3969 GDestroyNotify notify)
3971 GSource *source;
3972 guint id;
3974 g_return_val_if_fail (function != NULL, 0);
3976 source = g_idle_source_new ();
3978 if (priority != G_PRIORITY_DEFAULT_IDLE)
3979 g_source_set_priority (source, priority);
3981 g_source_set_callback (source, function, data, notify);
3982 id = g_source_attach (source, NULL);
3983 g_source_unref (source);
3985 return id;
3989 * g_idle_add:
3990 * @function: function to call
3991 * @data: data to pass to @function.
3993 * Adds a function to be called whenever there are no higher priority
3994 * events pending to the default main loop. The function is given the
3995 * default idle priority, #G_PRIORITY_DEFAULT_IDLE. If the function
3996 * returns %FALSE it is automatically removed from the list of event
3997 * sources and will not be called again.
3999 * Return value: the ID (greater than 0) of the event source.
4001 guint
4002 g_idle_add (GSourceFunc function,
4003 gpointer data)
4005 return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4009 * g_idle_remove_by_data:
4010 * @data: the data for the idle source's callback.
4012 * Removes the idle function with the given data.
4014 * Return value: %TRUE if an idle source was found and removed.
4016 gboolean
4017 g_idle_remove_by_data (gpointer data)
4019 return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4022 #define __G_MAIN_C__
4023 #include "galiasdef.c"