1 /* GIO - GLib Input, Output and Streaming Library
3 * Copyright (C) 2006-2007 Red Hat, Inc.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General
16 * Public License along with this library; if not, write to the
17 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18 * Boston, MA 02111-1307, USA.
20 * Author: Alexander Larsson <alexl@redhat.com>
26 #include "glib-unix.h"
28 #include <sys/eventfd.h>
37 #include "gcancellable.h"
42 * SECTION:gcancellable
43 * @short_description: Thread-safe Operation Cancellation Stack
46 * GCancellable is a thread-safe operation cancellation stack used
47 * throughout GIO to allow for cancellation of synchronous and
48 * asynchronous operations.
56 struct _GCancellablePrivate
59 guint cancelled_running : 1;
60 guint cancelled_running_waiting : 1;
63 /* If cancel_pipe[0] is != -1 and cancel_pipe[1] is -1, it is an eventfd */
71 static guint signals[LAST_SIGNAL] = { 0 };
73 G_DEFINE_TYPE (GCancellable, g_cancellable, G_TYPE_OBJECT);
75 static GStaticPrivate current_cancellable = G_STATIC_PRIVATE_INIT;
76 G_LOCK_DEFINE_STATIC(cancellable);
77 static GCond *cancellable_cond = NULL;
80 g_cancellable_close_pipe (GCancellable *cancellable)
82 GCancellablePrivate *priv;
84 priv = cancellable->priv;
86 if (priv->cancel_pipe[0] != -1)
88 close (priv->cancel_pipe[0]);
89 priv->cancel_pipe[0] = -1;
92 if (priv->cancel_pipe[1] != -1)
94 close (priv->cancel_pipe[1]);
95 priv->cancel_pipe[1] = -1;
101 CloseHandle (priv->event);
108 g_cancellable_finalize (GObject *object)
110 GCancellable *cancellable = G_CANCELLABLE (object);
112 g_cancellable_close_pipe (cancellable);
114 G_OBJECT_CLASS (g_cancellable_parent_class)->finalize (object);
118 g_cancellable_class_init (GCancellableClass *klass)
120 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
122 g_type_class_add_private (klass, sizeof (GCancellablePrivate));
124 if (cancellable_cond == NULL && g_thread_supported ())
125 cancellable_cond = g_cond_new ();
127 gobject_class->finalize = g_cancellable_finalize;
130 * GCancellable::cancelled:
131 * @cancellable: a #GCancellable.
133 * Emitted when the operation has been cancelled.
135 * Can be used by implementations of cancellable operations. If the
136 * operation is cancelled from another thread, the signal will be
137 * emitted in the thread that cancelled the operation, not the
138 * thread that is running the operation.
140 * Note that disconnecting from this signal (or any signal) in a
141 * multi-threaded program is prone to race conditions. For instance
142 * it is possible that a signal handler may be invoked even
143 * <emphasis>after</emphasis> a call to
144 * g_signal_handler_disconnect() for that handler has already
147 * There is also a problem when cancellation happen
148 * right before connecting to the signal. If this happens the
149 * signal will unexpectedly not be emitted, and checking before
150 * connecting to the signal leaves a race condition where this is
153 * In order to make it safe and easy to connect handlers there
154 * are two helper functions: g_cancellable_connect() and
155 * g_cancellable_disconnect() which protect against problems
158 * An example of how to us this:
160 * /<!-- -->* Make sure we don't do any unnecessary work if already cancelled *<!-- -->/
161 * if (g_cancellable_set_error_if_cancelled (cancellable))
164 * /<!-- -->* Set up all the data needed to be able to
165 * * handle cancellation of the operation *<!-- -->/
166 * my_data = my_data_new (...);
170 * id = g_cancellable_connect (cancellable,
171 * G_CALLBACK (cancelled_handler)
174 * /<!-- -->* cancellable operation here... *<!-- -->/
176 * g_cancellable_disconnect (cancellable, id);
178 * /<!-- -->* cancelled_handler is never called after this, it
179 * * is now safe to free the data *<!-- -->/
180 * my_data_free (my_data);
183 * Note that the cancelled signal is emitted in the thread that
184 * the user cancelled from, which may be the main thread. So, the
185 * cancellable signal should not do something that can block.
188 g_signal_new (I_("cancelled"),
189 G_TYPE_FROM_CLASS (gobject_class),
191 G_STRUCT_OFFSET (GCancellableClass, cancelled),
193 g_cclosure_marshal_VOID__VOID,
199 g_cancellable_write_cancelled (GCancellable *cancellable)
203 SetEvent (priv->event);
206 GCancellablePrivate *priv;
209 priv = cancellable->priv;
212 if (priv->cancel_pipe[0] == -1)
215 g_assert (cancellable->priv->cancelled);
218 if (priv->cancel_pipe[1] == -1)
223 c = write (priv->cancel_pipe[0], &buf, sizeof (buf));
224 while (c == -1 && errno == EINTR);
231 c = write (priv->cancel_pipe[1], &ch, 1);
232 while (c == -1 && errno == EINTR);
239 g_cancellable_open_pipe (GCancellable *cancellable)
241 GCancellablePrivate *priv;
243 priv = cancellable->priv;
245 priv->cancel_pipe[0] = eventfd (0, EFD_CLOEXEC | EFD_NONBLOCK);
246 if (priv->cancel_pipe[0] >= 0)
249 g_cancellable_write_cancelled (cancellable);
252 else if (errno != ENOSYS)
254 /* Fall through on ENOSYS */
256 if (g_unix_open_pipe (priv->cancel_pipe, FD_CLOEXEC, NULL))
258 /* Make them nonblocking, just to be sure we don't block
259 * on errors and stuff
261 g_unix_set_fd_nonblocking (priv->cancel_pipe[0], TRUE, NULL);
262 g_unix_set_fd_nonblocking (priv->cancel_pipe[1], TRUE, NULL);
265 g_cancellable_write_cancelled (cancellable);
271 g_cancellable_init (GCancellable *cancellable)
273 cancellable->priv = G_TYPE_INSTANCE_GET_PRIVATE (cancellable,
275 GCancellablePrivate);
276 cancellable->priv->cancel_pipe[0] = -1;
277 cancellable->priv->cancel_pipe[1] = -1;
283 * Creates a new #GCancellable object.
285 * Applications that want to start one or more operations
286 * that should be cancellable should create a #GCancellable
287 * and pass it to the operations.
289 * One #GCancellable can be used in multiple consecutive
290 * operations, but not in multiple concurrent operations.
292 * Returns: a #GCancellable.
295 g_cancellable_new (void)
297 return g_object_new (G_TYPE_CANCELLABLE, NULL);
301 * g_cancellable_push_current:
302 * @cancellable: a #GCancellable object
304 * Pushes @cancellable onto the cancellable stack. The current
305 * cancellable can then be recieved using g_cancellable_get_current().
307 * This is useful when implementing cancellable operations in
308 * code that does not allow you to pass down the cancellable object.
310 * This is typically called automatically by e.g. #GFile operations,
311 * so you rarely have to call this yourself.
314 g_cancellable_push_current (GCancellable *cancellable)
318 g_return_if_fail (cancellable != NULL);
320 l = g_static_private_get (¤t_cancellable);
321 l = g_slist_prepend (l, cancellable);
322 g_static_private_set (¤t_cancellable, l, NULL);
326 * g_cancellable_pop_current:
327 * @cancellable: a #GCancellable object
329 * Pops @cancellable off the cancellable stack (verifying that @cancellable
330 * is on the top of the stack).
333 g_cancellable_pop_current (GCancellable *cancellable)
337 l = g_static_private_get (¤t_cancellable);
339 g_return_if_fail (l != NULL);
340 g_return_if_fail (l->data == cancellable);
342 l = g_slist_delete_link (l, l);
343 g_static_private_set (¤t_cancellable, l, NULL);
347 * g_cancellable_get_current:
349 * Gets the top cancellable from the stack.
351 * Returns: (transfer none): a #GCancellable from the top of the stack, or %NULL
352 * if the stack is empty.
355 g_cancellable_get_current (void)
359 l = g_static_private_get (¤t_cancellable);
363 return G_CANCELLABLE (l->data);
367 * g_cancellable_reset:
368 * @cancellable: a #GCancellable object.
370 * Resets @cancellable to its uncancelled state.
373 g_cancellable_reset (GCancellable *cancellable)
375 GCancellablePrivate *priv;
377 g_return_if_fail (G_IS_CANCELLABLE (cancellable));
381 priv = cancellable->priv;
383 while (priv->cancelled_running)
385 priv->cancelled_running_waiting = TRUE;
386 g_cond_wait (cancellable_cond,
387 g_static_mutex_get_mutex (& G_LOCK_NAME (cancellable)));
392 /* Make sure we're not leaving old cancel state around */
396 ResetEvent (priv->event);
398 if (priv->cancel_pipe[0] != -1)
402 if (priv->cancel_pipe[1] == -1)
407 c = read (priv->cancel_pipe[0], &buf, sizeof(buf));
408 while (c == -1 && errno == EINTR);
416 c = read (priv->cancel_pipe[0], &ch, 1);
417 while (c == -1 && errno == EINTR);
421 priv->cancelled = FALSE;
423 G_UNLOCK(cancellable);
427 * g_cancellable_is_cancelled:
428 * @cancellable: a #GCancellable or NULL.
430 * Checks if a cancellable job has been cancelled.
432 * Returns: %TRUE if @cancellable is cancelled,
433 * FALSE if called with %NULL or if item is not cancelled.
436 g_cancellable_is_cancelled (GCancellable *cancellable)
438 return cancellable != NULL && cancellable->priv->cancelled;
442 * g_cancellable_set_error_if_cancelled:
443 * @cancellable: a #GCancellable object.
444 * @error: #GError to append error state to.
446 * If the @cancellable is cancelled, sets the error to notify
447 * that the operation was cancelled.
449 * Returns: %TRUE if @cancellable was cancelled, %FALSE if it was not.
452 g_cancellable_set_error_if_cancelled (GCancellable *cancellable,
455 if (g_cancellable_is_cancelled (cancellable))
457 g_set_error_literal (error,
459 G_IO_ERROR_CANCELLED,
460 _("Operation was cancelled"));
468 * g_cancellable_get_fd:
469 * @cancellable: a #GCancellable.
471 * Gets the file descriptor for a cancellable job. This can be used to
472 * implement cancellable operations on Unix systems. The returned fd will
473 * turn readable when @cancellable is cancelled.
475 * You are not supposed to read from the fd yourself, just check for
476 * readable status. Reading to unset the readable status is done
477 * with g_cancellable_reset().
479 * After a successful return from this function, you should use
480 * g_cancellable_release_fd() to free up resources allocated for
481 * the returned file descriptor.
483 * See also g_cancellable_make_pollfd().
485 * Returns: A valid file descriptor. %-1 if the file descriptor
486 * is not supported, or on errors.
489 g_cancellable_get_fd (GCancellable *cancellable)
491 GCancellablePrivate *priv;
494 if (cancellable == NULL)
497 priv = cancellable->priv;
503 if (priv->cancel_pipe[0] == -1)
504 g_cancellable_open_pipe (cancellable);
505 fd = priv->cancel_pipe[0];
508 G_UNLOCK(cancellable);
515 * g_cancellable_make_pollfd:
516 * @cancellable: a #GCancellable or %NULL
517 * @pollfd: a pointer to a #GPollFD
519 * Creates a #GPollFD corresponding to @cancellable; this can be passed
520 * to g_poll() and used to poll for cancellation. This is useful both
521 * for unix systems without a native poll and for portability to
524 * When this function returns %TRUE, you should use
525 * g_cancellable_release_fd() to free up resources allocated for the
526 * @pollfd. After a %FALSE return, do not call g_cancellable_release_fd().
528 * If this function returns %FALSE, either no @cancellable was given or
529 * resource limits prevent this function from allocating the necessary
530 * structures for polling. (On Linux, you will likely have reached
531 * the maximum number of file descriptors.) The suggested way to handle
532 * these cases is to ignore the @cancellable.
534 * You are not supposed to read from the fd yourself, just check for
535 * readable status. Reading to unset the readable status is done
536 * with g_cancellable_reset().
538 * Returns: %TRUE if @pollfd was successfully initialized, %FALSE on
539 * failure to prepare the cancellable.
544 g_cancellable_make_pollfd (GCancellable *cancellable, GPollFD *pollfd)
546 g_return_val_if_fail (pollfd != NULL, FALSE);
547 if (cancellable == NULL)
549 g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), FALSE);
553 GCancellablePrivate *priv;
555 priv = cancellable->priv;
557 if (priv->event == NULL)
559 /* A manual reset anonymous event, starting unset */
560 priv->event = CreateEvent (NULL, TRUE, FALSE, NULL);
561 if (priv->event == NULL)
563 G_UNLOCK(cancellable);
567 SetEvent(priv->event);
570 G_UNLOCK(cancellable);
572 pollfd->fd = (gintptr)priv->event;
573 #else /* !G_OS_WIN32 */
574 int fd = g_cancellable_get_fd (cancellable);
579 #endif /* G_OS_WIN32 */
582 pollfd->events = G_IO_IN;
589 * g_cancellable_release_fd:
590 * @cancellable: a #GCancellable
592 * Releases a resources previously allocated by g_cancellable_get_fd()
593 * or g_cancellable_make_pollfd().
595 * For compatibility reasons with older releases, calling this function
596 * is not strictly required, the resources will be automatically freed
597 * when the @cancellable is finalized. However, the @cancellable will
598 * block scarce file descriptors until it is finalized if this function
599 * is not called. This can cause the application to run out of file
600 * descriptors when many #GCancellables are used at the same time.
605 g_cancellable_release_fd (GCancellable *cancellable)
607 GCancellablePrivate *priv;
609 if (cancellable == NULL)
612 g_return_if_fail (G_IS_CANCELLABLE (cancellable));
613 g_return_if_fail (cancellable->priv->fd_refcount > 0);
615 priv = cancellable->priv;
617 G_LOCK (cancellable);
619 if (priv->fd_refcount == 0)
620 g_cancellable_close_pipe (cancellable);
621 G_UNLOCK (cancellable);
625 * g_cancellable_cancel:
626 * @cancellable: a #GCancellable object.
628 * Will set @cancellable to cancelled, and will emit the
629 * #GCancellable::cancelled signal. (However, see the warning about
630 * race conditions in the documentation for that signal if you are
631 * planning to connect to it.)
633 * This function is thread-safe. In other words, you can safely call
634 * it from a thread other than the one running the operation that was
635 * passed the @cancellable.
637 * The convention within gio is that cancelling an asynchronous
638 * operation causes it to complete asynchronously. That is, if you
639 * cancel the operation from the same thread in which it is running,
640 * then the operation's #GAsyncReadyCallback will not be invoked until
641 * the application returns to the main loop.
644 g_cancellable_cancel (GCancellable *cancellable)
646 GCancellablePrivate *priv;
648 if (cancellable == NULL ||
649 cancellable->priv->cancelled)
652 priv = cancellable->priv;
657 G_UNLOCK (cancellable);
661 priv->cancelled = TRUE;
662 priv->cancelled_running = TRUE;
664 g_cancellable_write_cancelled (cancellable);
666 G_UNLOCK(cancellable);
668 g_object_ref (cancellable);
669 g_signal_emit (cancellable, signals[CANCELLED], 0);
673 priv->cancelled_running = FALSE;
674 if (priv->cancelled_running_waiting)
675 g_cond_broadcast (cancellable_cond);
676 priv->cancelled_running_waiting = FALSE;
678 G_UNLOCK(cancellable);
680 g_object_unref (cancellable);
684 * g_cancellable_connect:
685 * @cancellable: A #GCancellable.
686 * @callback: The #GCallback to connect.
687 * @data: Data to pass to @callback.
688 * @data_destroy_func: Free function for @data or %NULL.
690 * Convenience function to connect to the #GCancellable::cancelled
691 * signal. Also handles the race condition that may happen
692 * if the cancellable is cancelled right before connecting.
694 * @callback is called at most once, either directly at the
695 * time of the connect if @cancellable is already cancelled,
696 * or when @cancellable is cancelled in some thread.
698 * @data_destroy_func will be called when the handler is
699 * disconnected, or immediately if the cancellable is already
702 * See #GCancellable::cancelled for details on how to use this.
704 * Returns: The id of the signal handler or 0 if @cancellable has already
710 g_cancellable_connect (GCancellable *cancellable,
713 GDestroyNotify data_destroy_func)
717 g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), 0);
719 G_LOCK (cancellable);
721 if (cancellable->priv->cancelled)
723 void (*_callback) (GCancellable *cancellable,
726 _callback = (void *)callback;
729 _callback (cancellable, data);
731 if (data_destroy_func)
732 data_destroy_func (data);
736 id = g_signal_connect_data (cancellable, "cancelled",
738 (GClosureNotify) data_destroy_func,
741 G_UNLOCK (cancellable);
747 * g_cancellable_disconnect:
748 * @cancellable: A #GCancellable or %NULL.
749 * @handler_id: Handler id of the handler to be disconnected, or %0.
751 * Disconnects a handler from a cancellable instance similar to
752 * g_signal_handler_disconnect(). Additionally, in the event that a
753 * signal handler is currently running, this call will block until the
754 * handler has finished. Calling this function from a
755 * #GCancellable::cancelled signal handler will therefore result in a
758 * This avoids a race condition where a thread cancels at the
759 * same time as the cancellable operation is finished and the
760 * signal handler is removed. See #GCancellable::cancelled for
761 * details on how to use this.
763 * If @cancellable is %NULL or @handler_id is %0 this function does
769 g_cancellable_disconnect (GCancellable *cancellable,
772 GCancellablePrivate *priv;
774 if (handler_id == 0 || cancellable == NULL)
777 G_LOCK (cancellable);
779 priv = cancellable->priv;
781 while (priv->cancelled_running)
783 priv->cancelled_running_waiting = TRUE;
784 g_cond_wait (cancellable_cond,
785 g_static_mutex_get_mutex (& G_LOCK_NAME (cancellable)));
788 g_signal_handler_disconnect (cancellable, handler_id);
789 G_UNLOCK (cancellable);
795 GCancellable *cancellable;
797 } GCancellableSource;
800 cancellable_source_prepare (GSource *source,
803 GCancellableSource *cancellable_source = (GCancellableSource *)source;
806 return g_cancellable_is_cancelled (cancellable_source->cancellable);
810 cancellable_source_check (GSource *source)
812 GCancellableSource *cancellable_source = (GCancellableSource *)source;
814 return g_cancellable_is_cancelled (cancellable_source->cancellable);
818 cancellable_source_dispatch (GSource *source,
819 GSourceFunc callback,
822 GCancellableSourceFunc func = (GCancellableSourceFunc)callback;
823 GCancellableSource *cancellable_source = (GCancellableSource *)source;
825 return (*func) (cancellable_source->cancellable, user_data);
829 cancellable_source_finalize (GSource *source)
831 GCancellableSource *cancellable_source = (GCancellableSource *)source;
833 if (cancellable_source->cancellable)
834 g_object_unref (cancellable_source->cancellable);
838 cancellable_source_closure_callback (GCancellable *cancellable,
841 GClosure *closure = data;
843 GValue params = { 0, };
844 GValue result_value = { 0, };
847 g_value_init (&result_value, G_TYPE_BOOLEAN);
849 g_value_init (¶ms, G_TYPE_CANCELLABLE);
850 g_value_set_object (¶ms, cancellable);
852 g_closure_invoke (closure, &result_value, 1, ¶ms, NULL);
854 result = g_value_get_boolean (&result_value);
855 g_value_unset (&result_value);
856 g_value_unset (¶ms);
861 static GSourceFuncs cancellable_source_funcs =
863 cancellable_source_prepare,
864 cancellable_source_check,
865 cancellable_source_dispatch,
866 cancellable_source_finalize,
867 (GSourceFunc)cancellable_source_closure_callback,
868 (GSourceDummyMarshal)g_cclosure_marshal_generic,
872 * g_cancellable_source_new: (skip)
873 * @cancellable: a #GCancellable, or %NULL
875 * Creates a source that triggers if @cancellable is cancelled and
876 * calls its callback of type #GCancellableSourceFunc. This is
877 * primarily useful for attaching to another (non-cancellable) source
878 * with g_source_add_child_source() to add cancellability to it.
880 * For convenience, you can call this with a %NULL #GCancellable,
881 * in which case the source will never trigger.
883 * Return value: (transfer full): the new #GSource.
888 g_cancellable_source_new (GCancellable *cancellable)
891 GCancellableSource *cancellable_source;
893 source = g_source_new (&cancellable_source_funcs, sizeof (GCancellableSource));
894 g_source_set_name (source, "GCancellable");
895 cancellable_source = (GCancellableSource *)source;
897 if (g_cancellable_make_pollfd (cancellable,
898 &cancellable_source->pollfd))
900 cancellable_source->cancellable = g_object_ref (cancellable);
901 g_source_add_poll (source, &cancellable_source->pollfd);