1 /* GIO - GLib Input, Output and Streaming Library
3 * Copyright (C) 2006-2007 Red Hat, Inc.
5 * SPDX-License-Identifier: LGPL-2.1-or-later
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.1 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
18 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
20 * Author: Alexander Larsson <alexl@redhat.com>
26 #include "glib-private.h"
27 #include "gcancellable.h"
34 * `GCancellable` allows operations to be cancelled.
36 * `GCancellable` is a thread-safe operation cancellation stack used
37 * throughout GIO to allow for cancellation of synchronous and
38 * asynchronous operations.
46 struct _GCancellablePrivate
48 /* Atomic so that g_cancellable_is_cancelled does not require holding the mutex. */
50 /* Access to fields below is protected by cancellable_mutex. */
51 guint cancelled_running : 1;
52 guint cancelled_running_waiting : 1;
53 unsigned cancelled_emissions;
54 unsigned cancelled_emissions_waiting : 1;
60 static guint signals[LAST_SIGNAL] = { 0 };
62 G_DEFINE_TYPE_WITH_PRIVATE (GCancellable, g_cancellable, G_TYPE_OBJECT)
64 static GPrivate current_cancellable;
65 static GMutex cancellable_mutex;
66 static GCond cancellable_cond;
69 g_cancellable_finalize (GObject *object)
71 GCancellable *cancellable = G_CANCELLABLE (object);
73 if (cancellable->priv->wakeup)
74 GLIB_PRIVATE_CALL (g_wakeup_free) (cancellable->priv->wakeup);
76 G_OBJECT_CLASS (g_cancellable_parent_class)->finalize (object);
80 g_cancellable_class_init (GCancellableClass *klass)
82 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
84 gobject_class->finalize = g_cancellable_finalize;
87 * GCancellable::cancelled:
88 * @cancellable: a #GCancellable.
90 * Emitted when the operation has been cancelled.
92 * Can be used by implementations of cancellable operations. If the
93 * operation is cancelled from another thread, the signal will be
94 * emitted in the thread that cancelled the operation, not the
95 * thread that is running the operation.
97 * Note that disconnecting from this signal (or any signal) in a
98 * multi-threaded program is prone to race conditions. For instance
99 * it is possible that a signal handler may be invoked even after
100 * a call to g_signal_handler_disconnect() for that handler has
103 * There is also a problem when cancellation happens right before
104 * connecting to the signal. If this happens the signal will
105 * unexpectedly not be emitted, and checking before connecting to
106 * the signal leaves a race condition where this is still happening.
108 * In order to make it safe and easy to connect handlers there
109 * are two helper functions: g_cancellable_connect() and
110 * g_cancellable_disconnect() which protect against problems
113 * An example of how to us this:
114 * |[<!-- language="C" -->
115 * // Make sure we don't do unnecessary work if already cancelled
116 * if (g_cancellable_set_error_if_cancelled (cancellable, error))
119 * // Set up all the data needed to be able to handle cancellation
120 * // of the operation
121 * my_data = my_data_new (...);
125 * id = g_cancellable_connect (cancellable,
126 * G_CALLBACK (cancelled_handler)
129 * // cancellable operation here...
131 * g_cancellable_disconnect (cancellable, id);
133 * // cancelled_handler is never called after this, it is now safe
134 * // to free the data
135 * my_data_free (my_data);
138 * Note that the cancelled signal is emitted in the thread that
139 * the user cancelled from, which may be the main thread. So, the
140 * cancellable signal should not do something that can block.
143 g_signal_new (I_("cancelled"),
144 G_TYPE_FROM_CLASS (gobject_class),
146 G_STRUCT_OFFSET (GCancellableClass, cancelled),
154 g_cancellable_init (GCancellable *cancellable)
156 cancellable->priv = g_cancellable_get_instance_private (cancellable);
162 * Creates a new #GCancellable object.
164 * Applications that want to start one or more operations
165 * that should be cancellable should create a #GCancellable
166 * and pass it to the operations.
168 * One #GCancellable can be used in multiple consecutive
169 * operations or in multiple concurrent operations.
171 * Returns: a #GCancellable.
174 g_cancellable_new (void)
176 return g_object_new (G_TYPE_CANCELLABLE, NULL);
180 * g_cancellable_push_current:
181 * @cancellable: a #GCancellable object
183 * Pushes @cancellable onto the cancellable stack. The current
184 * cancellable can then be received using g_cancellable_get_current().
186 * This is useful when implementing cancellable operations in
187 * code that does not allow you to pass down the cancellable object.
189 * This is typically called automatically by e.g. #GFile operations,
190 * so you rarely have to call this yourself.
193 g_cancellable_push_current (GCancellable *cancellable)
197 g_return_if_fail (cancellable != NULL);
199 l = g_private_get (¤t_cancellable);
200 l = g_slist_prepend (l, cancellable);
201 g_private_set (¤t_cancellable, l);
205 * g_cancellable_pop_current:
206 * @cancellable: a #GCancellable object
208 * Pops @cancellable off the cancellable stack (verifying that @cancellable
209 * is on the top of the stack).
212 g_cancellable_pop_current (GCancellable *cancellable)
216 l = g_private_get (¤t_cancellable);
218 g_return_if_fail (l != NULL);
219 g_return_if_fail (l->data == cancellable);
221 l = g_slist_delete_link (l, l);
222 g_private_set (¤t_cancellable, l);
226 * g_cancellable_get_current:
228 * Gets the top cancellable from the stack.
230 * Returns: (nullable) (transfer none): a #GCancellable from the top
231 * of the stack, or %NULL if the stack is empty.
234 g_cancellable_get_current (void)
238 l = g_private_get (¤t_cancellable);
242 return G_CANCELLABLE (l->data);
246 * g_cancellable_reset:
247 * @cancellable: a #GCancellable object.
249 * Resets @cancellable to its uncancelled state.
251 * If cancellable is currently in use by any cancellable operation
252 * then the behavior of this function is undefined.
254 * Note that it is generally not a good idea to reuse an existing
255 * cancellable for more operations after it has been cancelled once,
256 * as this function might tempt you to do. The recommended practice
257 * is to drop the reference to a cancellable after cancelling it,
258 * and let it die with the outstanding async operations. You should
259 * create a fresh cancellable for further async operations.
262 g_cancellable_reset (GCancellable *cancellable)
264 GCancellablePrivate *priv;
266 g_return_if_fail (G_IS_CANCELLABLE (cancellable));
268 g_mutex_lock (&cancellable_mutex);
270 priv = cancellable->priv;
272 while (priv->cancelled_running || priv->cancelled_emissions > 0)
274 if (priv->cancelled_running)
275 priv->cancelled_running_waiting = TRUE;
277 if (priv->cancelled_emissions > 0)
278 priv->cancelled_emissions_waiting = TRUE;
280 g_cond_wait (&cancellable_cond, &cancellable_mutex);
283 if (g_atomic_int_exchange (&priv->cancelled, FALSE))
286 GLIB_PRIVATE_CALL (g_wakeup_acknowledge) (priv->wakeup);
289 g_mutex_unlock (&cancellable_mutex);
293 * g_cancellable_is_cancelled:
294 * @cancellable: (nullable): a #GCancellable or %NULL
296 * Checks if a cancellable job has been cancelled.
298 * Returns: %TRUE if @cancellable is cancelled,
299 * FALSE if called with %NULL or if item is not cancelled.
302 g_cancellable_is_cancelled (GCancellable *cancellable)
304 return cancellable != NULL && g_atomic_int_get (&cancellable->priv->cancelled);
308 * g_cancellable_set_error_if_cancelled:
309 * @cancellable: (nullable): a #GCancellable or %NULL
310 * @error: #GError to append error state to
312 * If the @cancellable is cancelled, sets the error to notify
313 * that the operation was cancelled.
315 * Returns: %TRUE if @cancellable was cancelled, %FALSE if it was not
318 g_cancellable_set_error_if_cancelled (GCancellable *cancellable,
321 if (g_cancellable_is_cancelled (cancellable))
323 g_set_error_literal (error,
325 G_IO_ERROR_CANCELLED,
326 _("Operation was cancelled"));
334 * g_cancellable_get_fd:
335 * @cancellable: a #GCancellable.
337 * Gets the file descriptor for a cancellable job. This can be used to
338 * implement cancellable operations on Unix systems. The returned fd will
339 * turn readable when @cancellable is cancelled.
341 * You are not supposed to read from the fd yourself, just check for
342 * readable status. Reading to unset the readable status is done
343 * with g_cancellable_reset().
345 * After a successful return from this function, you should use
346 * g_cancellable_release_fd() to free up resources allocated for
347 * the returned file descriptor.
349 * See also g_cancellable_make_pollfd().
351 * Returns: A valid file descriptor. `-1` if the file descriptor
352 * is not supported, or on errors.
355 g_cancellable_get_fd (GCancellable *cancellable)
359 gboolean retval G_GNUC_UNUSED /* when compiling with G_DISABLE_ASSERT */;
362 if (cancellable == NULL)
368 retval = g_cancellable_make_pollfd (cancellable, &pollfd);
376 * g_cancellable_make_pollfd:
377 * @cancellable: (nullable): a #GCancellable or %NULL
378 * @pollfd: a pointer to a #GPollFD
380 * Creates a #GPollFD corresponding to @cancellable; this can be passed
381 * to g_poll() and used to poll for cancellation. This is useful both
382 * for unix systems without a native poll and for portability to
385 * When this function returns %TRUE, you should use
386 * g_cancellable_release_fd() to free up resources allocated for the
387 * @pollfd. After a %FALSE return, do not call g_cancellable_release_fd().
389 * If this function returns %FALSE, either no @cancellable was given or
390 * resource limits prevent this function from allocating the necessary
391 * structures for polling. (On Linux, you will likely have reached
392 * the maximum number of file descriptors.) The suggested way to handle
393 * these cases is to ignore the @cancellable.
395 * You are not supposed to read from the fd yourself, just check for
396 * readable status. Reading to unset the readable status is done
397 * with g_cancellable_reset().
399 * Returns: %TRUE if @pollfd was successfully initialized, %FALSE on
400 * failure to prepare the cancellable.
405 g_cancellable_make_pollfd (GCancellable *cancellable, GPollFD *pollfd)
407 g_return_val_if_fail (pollfd != NULL, FALSE);
408 if (cancellable == NULL)
410 g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), FALSE);
412 g_mutex_lock (&cancellable_mutex);
414 cancellable->priv->fd_refcount++;
416 if (cancellable->priv->wakeup == NULL)
418 cancellable->priv->wakeup = GLIB_PRIVATE_CALL (g_wakeup_new) ();
420 if (g_atomic_int_get (&cancellable->priv->cancelled))
421 GLIB_PRIVATE_CALL (g_wakeup_signal) (cancellable->priv->wakeup);
424 GLIB_PRIVATE_CALL (g_wakeup_get_pollfd) (cancellable->priv->wakeup, pollfd);
426 g_mutex_unlock (&cancellable_mutex);
432 * g_cancellable_release_fd:
433 * @cancellable: a #GCancellable
435 * Releases a resources previously allocated by g_cancellable_get_fd()
436 * or g_cancellable_make_pollfd().
438 * For compatibility reasons with older releases, calling this function
439 * is not strictly required, the resources will be automatically freed
440 * when the @cancellable is finalized. However, the @cancellable will
441 * block scarce file descriptors until it is finalized if this function
442 * is not called. This can cause the application to run out of file
443 * descriptors when many #GCancellables are used at the same time.
448 g_cancellable_release_fd (GCancellable *cancellable)
450 GCancellablePrivate *priv;
452 if (cancellable == NULL)
455 g_return_if_fail (G_IS_CANCELLABLE (cancellable));
457 priv = cancellable->priv;
459 g_mutex_lock (&cancellable_mutex);
460 g_assert (priv->fd_refcount > 0);
463 if (priv->fd_refcount == 0)
465 GLIB_PRIVATE_CALL (g_wakeup_free) (priv->wakeup);
469 g_mutex_unlock (&cancellable_mutex);
473 * g_cancellable_cancel:
474 * @cancellable: (nullable): a #GCancellable object.
476 * Will set @cancellable to cancelled, and will emit the
477 * #GCancellable::cancelled signal. (However, see the warning about
478 * race conditions in the documentation for that signal if you are
479 * planning to connect to it.)
481 * This function is thread-safe. In other words, you can safely call
482 * it from a thread other than the one running the operation that was
483 * passed the @cancellable.
485 * If @cancellable is %NULL, this function returns immediately for convenience.
487 * The convention within GIO is that cancelling an asynchronous
488 * operation causes it to complete asynchronously. That is, if you
489 * cancel the operation from the same thread in which it is running,
490 * then the operation's #GAsyncReadyCallback will not be invoked until
491 * the application returns to the main loop.
494 g_cancellable_cancel (GCancellable *cancellable)
496 GCancellablePrivate *priv;
498 if (cancellable == NULL || g_cancellable_is_cancelled (cancellable))
501 priv = cancellable->priv;
503 g_mutex_lock (&cancellable_mutex);
505 if (g_atomic_int_exchange (&priv->cancelled, TRUE))
507 g_mutex_unlock (&cancellable_mutex);
511 priv->cancelled_running = TRUE;
514 GLIB_PRIVATE_CALL (g_wakeup_signal) (priv->wakeup);
516 g_mutex_unlock (&cancellable_mutex);
518 g_object_ref (cancellable);
519 g_signal_emit (cancellable, signals[CANCELLED], 0);
521 g_mutex_lock (&cancellable_mutex);
523 priv->cancelled_running = FALSE;
524 if (priv->cancelled_running_waiting)
525 g_cond_broadcast (&cancellable_cond);
526 priv->cancelled_running_waiting = FALSE;
528 g_mutex_unlock (&cancellable_mutex);
530 g_object_unref (cancellable);
534 * g_cancellable_connect:
535 * @cancellable: A #GCancellable.
536 * @callback: The #GCallback to connect.
537 * @data: Data to pass to @callback.
538 * @data_destroy_func: (nullable): Free function for @data or %NULL.
540 * Convenience function to connect to the #GCancellable::cancelled
541 * signal. Also handles the race condition that may happen
542 * if the cancellable is cancelled right before connecting.
544 * @callback is called at most once, either directly at the
545 * time of the connect if @cancellable is already cancelled,
546 * or when @cancellable is cancelled in some thread.
548 * @data_destroy_func will be called when the handler is
549 * disconnected, or immediately if the cancellable is already
552 * See #GCancellable::cancelled for details on how to use this.
554 * Since GLib 2.40, the lock protecting @cancellable is not held when
555 * @callback is invoked. This lifts a restriction in place for
556 * earlier GLib versions which now makes it easier to write cleanup
557 * code that unconditionally invokes e.g. g_cancellable_cancel().
559 * Returns: The id of the signal handler or 0 if @cancellable has already
565 g_cancellable_connect (GCancellable *cancellable,
568 GDestroyNotify data_destroy_func)
572 g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), 0);
574 g_mutex_lock (&cancellable_mutex);
576 if (g_atomic_int_get (&cancellable->priv->cancelled))
578 void (*_callback) (GCancellable *cancellable,
581 _callback = (void *)callback;
584 cancellable->priv->cancelled_emissions++;
586 g_mutex_unlock (&cancellable_mutex);
588 _callback (cancellable, data);
590 if (data_destroy_func)
591 data_destroy_func (data);
593 g_mutex_lock (&cancellable_mutex);
595 if (cancellable->priv->cancelled_emissions_waiting)
596 g_cond_broadcast (&cancellable_cond);
598 cancellable->priv->cancelled_emissions--;
600 g_mutex_unlock (&cancellable_mutex);
604 id = g_signal_connect_data (cancellable, "cancelled",
606 (GClosureNotify) data_destroy_func,
609 g_mutex_unlock (&cancellable_mutex);
617 * g_cancellable_disconnect:
618 * @cancellable: (nullable): A #GCancellable or %NULL.
619 * @handler_id: Handler id of the handler to be disconnected, or `0`.
621 * Disconnects a handler from a cancellable instance similar to
622 * g_signal_handler_disconnect(). Additionally, in the event that a
623 * signal handler is currently running, this call will block until the
624 * handler has finished. Calling this function from a
625 * #GCancellable::cancelled signal handler will therefore result in a
628 * This avoids a race condition where a thread cancels at the
629 * same time as the cancellable operation is finished and the
630 * signal handler is removed. See #GCancellable::cancelled for
631 * details on how to use this.
633 * If @cancellable is %NULL or @handler_id is `0` this function does
639 g_cancellable_disconnect (GCancellable *cancellable,
642 GCancellablePrivate *priv;
644 if (handler_id == 0 || cancellable == NULL)
647 g_mutex_lock (&cancellable_mutex);
649 priv = cancellable->priv;
651 while (priv->cancelled_running || priv->cancelled_emissions)
653 if (priv->cancelled_running)
654 priv->cancelled_running_waiting = TRUE;
656 if (priv->cancelled_emissions)
657 priv->cancelled_emissions_waiting = TRUE;
659 g_cond_wait (&cancellable_cond, &cancellable_mutex);
662 g_signal_handler_disconnect (cancellable, handler_id);
664 g_mutex_unlock (&cancellable_mutex);
670 GCancellable *cancellable;
671 gulong cancelled_handler;
672 /* Protected by cancellable_mutex: */
673 gboolean resurrected_during_cancellation;
674 } GCancellableSource;
677 * The reference count of the GSource might be 0 at this point but it is not
678 * finalized yet and its dispose function did not run yet, or otherwise we
679 * would have disconnected the signal handler already and due to the signal
680 * emission lock it would be impossible to call the signal handler at that
681 * point. That is: at this point we either have a fully valid GSource, or
682 * it's not disposed or finalized yet and we can still resurrect it as needed.
684 * As such we first ensure that we have a strong reference to the GSource in
685 * here before calling any other GSource API.
688 cancellable_source_cancelled (GCancellable *cancellable,
691 GSource *source = user_data;
692 GCancellableSource *cancellable_source = (GCancellableSource *) source;
694 g_mutex_lock (&cancellable_mutex);
696 /* Drop the reference added in cancellable_source_dispose(); see the comment there.
697 * The reference must be dropped after unlocking @cancellable_mutex since
698 * it could be the final reference, and the dispose function takes
699 * @cancellable_mutex. */
700 if (cancellable_source->resurrected_during_cancellation)
702 cancellable_source->resurrected_during_cancellation = FALSE;
703 g_mutex_unlock (&cancellable_mutex);
704 g_source_unref (source);
708 g_source_ref (source);
709 g_mutex_unlock (&cancellable_mutex);
710 g_source_set_ready_time (source, 0);
711 g_source_unref (source);
715 cancellable_source_dispatch (GSource *source,
716 GSourceFunc callback,
719 GCancellableSourceFunc func = (GCancellableSourceFunc)callback;
720 GCancellableSource *cancellable_source = (GCancellableSource *)source;
722 g_source_set_ready_time (source, -1);
723 return (*func) (cancellable_source->cancellable, user_data);
727 cancellable_source_dispose (GSource *source)
729 GCancellableSource *cancellable_source = (GCancellableSource *)source;
731 g_mutex_lock (&cancellable_mutex);
733 if (cancellable_source->cancellable)
735 if (cancellable_source->cancellable->priv->cancelled_running)
737 /* There can be a race here: if thread A has called
738 * g_cancellable_cancel() and has got as far as committing to call
739 * cancellable_source_cancelled(), then thread B drops the final
740 * ref on the GCancellableSource before g_source_ref() is called in
741 * cancellable_source_cancelled(), then cancellable_source_dispose()
742 * will run through and the GCancellableSource will be finalised
743 * before cancellable_source_cancelled() gets to g_source_ref(). It
744 * will then be left in a state where it’s committed to using a
745 * dangling GCancellableSource pointer.
747 * Eliminate that race by resurrecting the #GSource temporarily, and
748 * then dropping that reference in cancellable_source_cancelled(),
749 * which should be guaranteed to fire because we’re inside a
750 * @cancelled_running block.
752 g_source_ref (source);
753 cancellable_source->resurrected_during_cancellation = TRUE;
756 g_clear_signal_handler (&cancellable_source->cancelled_handler,
757 cancellable_source->cancellable);
758 g_clear_object (&cancellable_source->cancellable);
761 g_mutex_unlock (&cancellable_mutex);
765 cancellable_source_closure_callback (GCancellable *cancellable,
768 GClosure *closure = data;
770 GValue params = G_VALUE_INIT;
771 GValue result_value = G_VALUE_INIT;
774 g_value_init (&result_value, G_TYPE_BOOLEAN);
776 g_value_init (¶ms, G_TYPE_CANCELLABLE);
777 g_value_set_object (¶ms, cancellable);
779 g_closure_invoke (closure, &result_value, 1, ¶ms, NULL);
781 result = g_value_get_boolean (&result_value);
782 g_value_unset (&result_value);
783 g_value_unset (¶ms);
788 static GSourceFuncs cancellable_source_funcs =
792 cancellable_source_dispatch,
794 (GSourceFunc)cancellable_source_closure_callback,
799 * g_cancellable_source_new:
800 * @cancellable: (nullable): a #GCancellable, or %NULL
802 * Creates a source that triggers if @cancellable is cancelled and
803 * calls its callback of type #GCancellableSourceFunc. This is
804 * primarily useful for attaching to another (non-cancellable) source
805 * with g_source_add_child_source() to add cancellability to it.
807 * For convenience, you can call this with a %NULL #GCancellable,
808 * in which case the source will never trigger.
810 * The new #GSource will hold a reference to the #GCancellable.
812 * Returns: (transfer full): the new #GSource.
817 g_cancellable_source_new (GCancellable *cancellable)
820 GCancellableSource *cancellable_source;
822 source = g_source_new (&cancellable_source_funcs, sizeof (GCancellableSource));
823 g_source_set_static_name (source, "GCancellable");
824 g_source_set_dispose_function (source, cancellable_source_dispose);
825 cancellable_source = (GCancellableSource *)source;
829 cancellable_source->cancellable = g_object_ref (cancellable);
831 /* We intentionally don't use g_cancellable_connect() here,
832 * because we don't want the "at most once" behavior.
834 cancellable_source->cancelled_handler =
835 g_signal_connect (cancellable, "cancelled",
836 G_CALLBACK (cancellable_source_cancelled),
838 if (g_cancellable_is_cancelled (cancellable))
839 g_source_set_ready_time (source, 0);