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)
202 GCancellablePrivate *priv;
205 priv = cancellable->priv;
209 SetEvent (priv->event);
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);
228 #endif /* HAVE_EVENTFD */
231 c = write (priv->cancel_pipe[1], &ch, 1);
232 while (c == -1 && errno == EINTR);
233 #endif /* G_OS_WIN32 */
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 || errno == EINVAL))
256 /* Fall through on ENOSYS or EINVAL */
258 if (g_unix_open_pipe (priv->cancel_pipe, FD_CLOEXEC, NULL))
260 /* Make them nonblocking, just to be sure we don't block
261 * on errors and stuff
263 g_unix_set_fd_nonblocking (priv->cancel_pipe[0], TRUE, NULL);
264 g_unix_set_fd_nonblocking (priv->cancel_pipe[1], TRUE, NULL);
267 g_cancellable_write_cancelled (cancellable);
273 g_cancellable_init (GCancellable *cancellable)
275 cancellable->priv = G_TYPE_INSTANCE_GET_PRIVATE (cancellable,
277 GCancellablePrivate);
278 cancellable->priv->cancel_pipe[0] = -1;
279 cancellable->priv->cancel_pipe[1] = -1;
285 * Creates a new #GCancellable object.
287 * Applications that want to start one or more operations
288 * that should be cancellable should create a #GCancellable
289 * and pass it to the operations.
291 * One #GCancellable can be used in multiple consecutive
292 * operations, but not in multiple concurrent operations.
294 * Returns: a #GCancellable.
297 g_cancellable_new (void)
299 return g_object_new (G_TYPE_CANCELLABLE, NULL);
303 * g_cancellable_push_current:
304 * @cancellable: a #GCancellable object
306 * Pushes @cancellable onto the cancellable stack. The current
307 * cancellable can then be recieved using g_cancellable_get_current().
309 * This is useful when implementing cancellable operations in
310 * code that does not allow you to pass down the cancellable object.
312 * This is typically called automatically by e.g. #GFile operations,
313 * so you rarely have to call this yourself.
316 g_cancellable_push_current (GCancellable *cancellable)
320 g_return_if_fail (cancellable != NULL);
322 l = g_static_private_get (¤t_cancellable);
323 l = g_slist_prepend (l, cancellable);
324 g_static_private_set (¤t_cancellable, l, NULL);
328 * g_cancellable_pop_current:
329 * @cancellable: a #GCancellable object
331 * Pops @cancellable off the cancellable stack (verifying that @cancellable
332 * is on the top of the stack).
335 g_cancellable_pop_current (GCancellable *cancellable)
339 l = g_static_private_get (¤t_cancellable);
341 g_return_if_fail (l != NULL);
342 g_return_if_fail (l->data == cancellable);
344 l = g_slist_delete_link (l, l);
345 g_static_private_set (¤t_cancellable, l, NULL);
349 * g_cancellable_get_current:
351 * Gets the top cancellable from the stack.
353 * Returns: (transfer none): a #GCancellable from the top of the stack, or %NULL
354 * if the stack is empty.
357 g_cancellable_get_current (void)
361 l = g_static_private_get (¤t_cancellable);
365 return G_CANCELLABLE (l->data);
369 * g_cancellable_reset:
370 * @cancellable: a #GCancellable object.
372 * Resets @cancellable to its uncancelled state.
375 g_cancellable_reset (GCancellable *cancellable)
377 GCancellablePrivate *priv;
379 g_return_if_fail (G_IS_CANCELLABLE (cancellable));
383 priv = cancellable->priv;
385 while (priv->cancelled_running)
387 priv->cancelled_running_waiting = TRUE;
388 g_cond_wait (cancellable_cond,
389 g_static_mutex_get_mutex (& G_LOCK_NAME (cancellable)));
394 /* Make sure we're not leaving old cancel state around */
398 ResetEvent (priv->event);
400 if (priv->cancel_pipe[0] != -1)
404 if (priv->cancel_pipe[1] == -1)
409 c = read (priv->cancel_pipe[0], &buf, sizeof(buf));
410 while (c == -1 && errno == EINTR);
418 c = read (priv->cancel_pipe[0], &ch, 1);
419 while (c == -1 && errno == EINTR);
423 priv->cancelled = FALSE;
425 G_UNLOCK(cancellable);
429 * g_cancellable_is_cancelled:
430 * @cancellable: a #GCancellable or NULL.
432 * Checks if a cancellable job has been cancelled.
434 * Returns: %TRUE if @cancellable is cancelled,
435 * FALSE if called with %NULL or if item is not cancelled.
438 g_cancellable_is_cancelled (GCancellable *cancellable)
440 return cancellable != NULL && cancellable->priv->cancelled;
444 * g_cancellable_set_error_if_cancelled:
445 * @cancellable: a #GCancellable object.
446 * @error: #GError to append error state to.
448 * If the @cancellable is cancelled, sets the error to notify
449 * that the operation was cancelled.
451 * Returns: %TRUE if @cancellable was cancelled, %FALSE if it was not.
454 g_cancellable_set_error_if_cancelled (GCancellable *cancellable,
457 if (g_cancellable_is_cancelled (cancellable))
459 g_set_error_literal (error,
461 G_IO_ERROR_CANCELLED,
462 _("Operation was cancelled"));
470 * g_cancellable_get_fd:
471 * @cancellable: a #GCancellable.
473 * Gets the file descriptor for a cancellable job. This can be used to
474 * implement cancellable operations on Unix systems. The returned fd will
475 * turn readable when @cancellable is cancelled.
477 * You are not supposed to read from the fd yourself, just check for
478 * readable status. Reading to unset the readable status is done
479 * with g_cancellable_reset().
481 * After a successful return from this function, you should use
482 * g_cancellable_release_fd() to free up resources allocated for
483 * the returned file descriptor.
485 * See also g_cancellable_make_pollfd().
487 * Returns: A valid file descriptor. %-1 if the file descriptor
488 * is not supported, or on errors.
491 g_cancellable_get_fd (GCancellable *cancellable)
493 GCancellablePrivate *priv;
496 if (cancellable == NULL)
499 priv = cancellable->priv;
505 if (priv->cancel_pipe[0] == -1)
506 g_cancellable_open_pipe (cancellable);
507 fd = priv->cancel_pipe[0];
510 G_UNLOCK(cancellable);
517 * g_cancellable_make_pollfd:
518 * @cancellable: a #GCancellable or %NULL
519 * @pollfd: a pointer to a #GPollFD
521 * Creates a #GPollFD corresponding to @cancellable; this can be passed
522 * to g_poll() and used to poll for cancellation. This is useful both
523 * for unix systems without a native poll and for portability to
526 * When this function returns %TRUE, you should use
527 * g_cancellable_release_fd() to free up resources allocated for the
528 * @pollfd. After a %FALSE return, do not call g_cancellable_release_fd().
530 * If this function returns %FALSE, either no @cancellable was given or
531 * resource limits prevent this function from allocating the necessary
532 * structures for polling. (On Linux, you will likely have reached
533 * the maximum number of file descriptors.) The suggested way to handle
534 * these cases is to ignore the @cancellable.
536 * You are not supposed to read from the fd yourself, just check for
537 * readable status. Reading to unset the readable status is done
538 * with g_cancellable_reset().
540 * Returns: %TRUE if @pollfd was successfully initialized, %FALSE on
541 * failure to prepare the cancellable.
546 g_cancellable_make_pollfd (GCancellable *cancellable, GPollFD *pollfd)
548 g_return_val_if_fail (pollfd != NULL, FALSE);
549 if (cancellable == NULL)
551 g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), FALSE);
555 GCancellablePrivate *priv;
557 priv = cancellable->priv;
559 if (priv->event == NULL)
561 /* A manual reset anonymous event, starting unset */
562 priv->event = CreateEvent (NULL, TRUE, FALSE, NULL);
563 if (priv->event == NULL)
565 G_UNLOCK(cancellable);
569 SetEvent(priv->event);
572 G_UNLOCK(cancellable);
574 pollfd->fd = (gintptr)priv->event;
575 #else /* !G_OS_WIN32 */
576 int fd = g_cancellable_get_fd (cancellable);
581 #endif /* G_OS_WIN32 */
584 pollfd->events = G_IO_IN;
591 * g_cancellable_release_fd:
592 * @cancellable: a #GCancellable
594 * Releases a resources previously allocated by g_cancellable_get_fd()
595 * or g_cancellable_make_pollfd().
597 * For compatibility reasons with older releases, calling this function
598 * is not strictly required, the resources will be automatically freed
599 * when the @cancellable is finalized. However, the @cancellable will
600 * block scarce file descriptors until it is finalized if this function
601 * is not called. This can cause the application to run out of file
602 * descriptors when many #GCancellables are used at the same time.
607 g_cancellable_release_fd (GCancellable *cancellable)
609 GCancellablePrivate *priv;
611 if (cancellable == NULL)
614 g_return_if_fail (G_IS_CANCELLABLE (cancellable));
615 g_return_if_fail (cancellable->priv->fd_refcount > 0);
617 priv = cancellable->priv;
619 G_LOCK (cancellable);
621 if (priv->fd_refcount == 0)
622 g_cancellable_close_pipe (cancellable);
623 G_UNLOCK (cancellable);
627 * g_cancellable_cancel:
628 * @cancellable: a #GCancellable object.
630 * Will set @cancellable to cancelled, and will emit the
631 * #GCancellable::cancelled signal. (However, see the warning about
632 * race conditions in the documentation for that signal if you are
633 * planning to connect to it.)
635 * This function is thread-safe. In other words, you can safely call
636 * it from a thread other than the one running the operation that was
637 * passed the @cancellable.
639 * The convention within gio is that cancelling an asynchronous
640 * operation causes it to complete asynchronously. That is, if you
641 * cancel the operation from the same thread in which it is running,
642 * then the operation's #GAsyncReadyCallback will not be invoked until
643 * the application returns to the main loop.
646 g_cancellable_cancel (GCancellable *cancellable)
648 GCancellablePrivate *priv;
650 if (cancellable == NULL ||
651 cancellable->priv->cancelled)
654 priv = cancellable->priv;
659 G_UNLOCK (cancellable);
663 priv->cancelled = TRUE;
664 priv->cancelled_running = TRUE;
666 g_cancellable_write_cancelled (cancellable);
668 G_UNLOCK(cancellable);
670 g_object_ref (cancellable);
671 g_signal_emit (cancellable, signals[CANCELLED], 0);
675 priv->cancelled_running = FALSE;
676 if (priv->cancelled_running_waiting)
677 g_cond_broadcast (cancellable_cond);
678 priv->cancelled_running_waiting = FALSE;
680 G_UNLOCK(cancellable);
682 g_object_unref (cancellable);
686 * g_cancellable_connect:
687 * @cancellable: A #GCancellable.
688 * @callback: The #GCallback to connect.
689 * @data: Data to pass to @callback.
690 * @data_destroy_func: Free function for @data or %NULL.
692 * Convenience function to connect to the #GCancellable::cancelled
693 * signal. Also handles the race condition that may happen
694 * if the cancellable is cancelled right before connecting.
696 * @callback is called at most once, either directly at the
697 * time of the connect if @cancellable is already cancelled,
698 * or when @cancellable is cancelled in some thread.
700 * @data_destroy_func will be called when the handler is
701 * disconnected, or immediately if the cancellable is already
704 * See #GCancellable::cancelled for details on how to use this.
706 * Returns: The id of the signal handler or 0 if @cancellable has already
712 g_cancellable_connect (GCancellable *cancellable,
715 GDestroyNotify data_destroy_func)
719 g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), 0);
721 G_LOCK (cancellable);
723 if (cancellable->priv->cancelled)
725 void (*_callback) (GCancellable *cancellable,
728 _callback = (void *)callback;
731 _callback (cancellable, data);
733 if (data_destroy_func)
734 data_destroy_func (data);
738 id = g_signal_connect_data (cancellable, "cancelled",
740 (GClosureNotify) data_destroy_func,
743 G_UNLOCK (cancellable);
749 * g_cancellable_disconnect:
750 * @cancellable: A #GCancellable or %NULL.
751 * @handler_id: Handler id of the handler to be disconnected, or %0.
753 * Disconnects a handler from a cancellable instance similar to
754 * g_signal_handler_disconnect(). Additionally, in the event that a
755 * signal handler is currently running, this call will block until the
756 * handler has finished. Calling this function from a
757 * #GCancellable::cancelled signal handler will therefore result in a
760 * This avoids a race condition where a thread cancels at the
761 * same time as the cancellable operation is finished and the
762 * signal handler is removed. See #GCancellable::cancelled for
763 * details on how to use this.
765 * If @cancellable is %NULL or @handler_id is %0 this function does
771 g_cancellable_disconnect (GCancellable *cancellable,
774 GCancellablePrivate *priv;
776 if (handler_id == 0 || cancellable == NULL)
779 G_LOCK (cancellable);
781 priv = cancellable->priv;
783 while (priv->cancelled_running)
785 priv->cancelled_running_waiting = TRUE;
786 g_cond_wait (cancellable_cond,
787 g_static_mutex_get_mutex (& G_LOCK_NAME (cancellable)));
790 g_signal_handler_disconnect (cancellable, handler_id);
791 G_UNLOCK (cancellable);
797 GCancellable *cancellable;
799 } GCancellableSource;
802 cancellable_source_prepare (GSource *source,
805 GCancellableSource *cancellable_source = (GCancellableSource *)source;
808 return g_cancellable_is_cancelled (cancellable_source->cancellable);
812 cancellable_source_check (GSource *source)
814 GCancellableSource *cancellable_source = (GCancellableSource *)source;
816 return g_cancellable_is_cancelled (cancellable_source->cancellable);
820 cancellable_source_dispatch (GSource *source,
821 GSourceFunc callback,
824 GCancellableSourceFunc func = (GCancellableSourceFunc)callback;
825 GCancellableSource *cancellable_source = (GCancellableSource *)source;
827 return (*func) (cancellable_source->cancellable, user_data);
831 cancellable_source_finalize (GSource *source)
833 GCancellableSource *cancellable_source = (GCancellableSource *)source;
835 if (cancellable_source->cancellable)
836 g_object_unref (cancellable_source->cancellable);
840 cancellable_source_closure_callback (GCancellable *cancellable,
843 GClosure *closure = data;
845 GValue params = { 0, };
846 GValue result_value = { 0, };
849 g_value_init (&result_value, G_TYPE_BOOLEAN);
851 g_value_init (¶ms, G_TYPE_CANCELLABLE);
852 g_value_set_object (¶ms, cancellable);
854 g_closure_invoke (closure, &result_value, 1, ¶ms, NULL);
856 result = g_value_get_boolean (&result_value);
857 g_value_unset (&result_value);
858 g_value_unset (¶ms);
863 static GSourceFuncs cancellable_source_funcs =
865 cancellable_source_prepare,
866 cancellable_source_check,
867 cancellable_source_dispatch,
868 cancellable_source_finalize,
869 (GSourceFunc)cancellable_source_closure_callback,
870 (GSourceDummyMarshal)g_cclosure_marshal_generic,
874 * g_cancellable_source_new: (skip)
875 * @cancellable: a #GCancellable, or %NULL
877 * Creates a source that triggers if @cancellable is cancelled and
878 * calls its callback of type #GCancellableSourceFunc. This is
879 * primarily useful for attaching to another (non-cancellable) source
880 * with g_source_add_child_source() to add cancellability to it.
882 * For convenience, you can call this with a %NULL #GCancellable,
883 * in which case the source will never trigger.
885 * Return value: (transfer full): the new #GSource.
890 g_cancellable_source_new (GCancellable *cancellable)
893 GCancellableSource *cancellable_source;
895 source = g_source_new (&cancellable_source_funcs, sizeof (GCancellableSource));
896 g_source_set_name (source, "GCancellable");
897 cancellable_source = (GCancellableSource *)source;
899 if (g_cancellable_make_pollfd (cancellable,
900 &cancellable_source->pollfd))
902 cancellable_source->cancellable = g_object_ref (cancellable);
903 g_source_add_poll (source, &cancellable_source->pollfd);