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.1 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, see <http://www.gnu.org/licenses/>.
18 * Author: Alexander Larsson <alexl@redhat.com>
24 #include "glib-private.h"
25 #include "gcancellable.h"
30 * SECTION:gcancellable
31 * @short_description: Thread-safe Operation Cancellation Stack
34 * GCancellable is a thread-safe operation cancellation stack used
35 * throughout GIO to allow for cancellation of synchronous and
36 * asynchronous operations.
44 struct _GCancellablePrivate
46 /* Atomic so that g_cancellable_is_cancelled does not require holding the mutex. */
48 /* Access to fields below is protected by cancellable_mutex. */
49 guint cancelled_running : 1;
50 guint cancelled_running_waiting : 1;
56 static guint signals[LAST_SIGNAL] = { 0 };
58 G_DEFINE_TYPE_WITH_PRIVATE (GCancellable, g_cancellable, G_TYPE_OBJECT)
60 static GPrivate current_cancellable;
61 static GMutex cancellable_mutex;
62 static GCond cancellable_cond;
65 g_cancellable_finalize (GObject *object)
67 GCancellable *cancellable = G_CANCELLABLE (object);
69 if (cancellable->priv->wakeup)
70 GLIB_PRIVATE_CALL (g_wakeup_free) (cancellable->priv->wakeup);
72 G_OBJECT_CLASS (g_cancellable_parent_class)->finalize (object);
76 g_cancellable_class_init (GCancellableClass *klass)
78 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
80 gobject_class->finalize = g_cancellable_finalize;
83 * GCancellable::cancelled:
84 * @cancellable: a #GCancellable.
86 * Emitted when the operation has been cancelled.
88 * Can be used by implementations of cancellable operations. If the
89 * operation is cancelled from another thread, the signal will be
90 * emitted in the thread that cancelled the operation, not the
91 * thread that is running the operation.
93 * Note that disconnecting from this signal (or any signal) in a
94 * multi-threaded program is prone to race conditions. For instance
95 * it is possible that a signal handler may be invoked even after
96 * a call to g_signal_handler_disconnect() for that handler has
99 * There is also a problem when cancellation happens right before
100 * connecting to the signal. If this happens the signal will
101 * unexpectedly not be emitted, and checking before connecting to
102 * the signal leaves a race condition where this is still happening.
104 * In order to make it safe and easy to connect handlers there
105 * are two helper functions: g_cancellable_connect() and
106 * g_cancellable_disconnect() which protect against problems
109 * An example of how to us this:
110 * |[<!-- language="C" -->
111 * // Make sure we don't do unnecessary work if already cancelled
112 * if (g_cancellable_set_error_if_cancelled (cancellable, error))
115 * // Set up all the data needed to be able to handle cancellation
116 * // of the operation
117 * my_data = my_data_new (...);
121 * id = g_cancellable_connect (cancellable,
122 * G_CALLBACK (cancelled_handler)
125 * // cancellable operation here...
127 * g_cancellable_disconnect (cancellable, id);
129 * // cancelled_handler is never called after this, it is now safe
130 * // to free the data
131 * my_data_free (my_data);
134 * Note that the cancelled signal is emitted in the thread that
135 * the user cancelled from, which may be the main thread. So, the
136 * cancellable signal should not do something that can block.
139 g_signal_new (I_("cancelled"),
140 G_TYPE_FROM_CLASS (gobject_class),
142 G_STRUCT_OFFSET (GCancellableClass, cancelled),
150 g_cancellable_init (GCancellable *cancellable)
152 cancellable->priv = g_cancellable_get_instance_private (cancellable);
158 * Creates a new #GCancellable object.
160 * Applications that want to start one or more operations
161 * that should be cancellable should create a #GCancellable
162 * and pass it to the operations.
164 * One #GCancellable can be used in multiple consecutive
165 * operations or in multiple concurrent operations.
167 * Returns: a #GCancellable.
170 g_cancellable_new (void)
172 return g_object_new (G_TYPE_CANCELLABLE, NULL);
176 * g_cancellable_push_current:
177 * @cancellable: a #GCancellable object
179 * Pushes @cancellable onto the cancellable stack. The current
180 * cancellable can then be received using g_cancellable_get_current().
182 * This is useful when implementing cancellable operations in
183 * code that does not allow you to pass down the cancellable object.
185 * This is typically called automatically by e.g. #GFile operations,
186 * so you rarely have to call this yourself.
189 g_cancellable_push_current (GCancellable *cancellable)
193 g_return_if_fail (cancellable != NULL);
195 l = g_private_get (¤t_cancellable);
196 l = g_slist_prepend (l, cancellable);
197 g_private_set (¤t_cancellable, l);
201 * g_cancellable_pop_current:
202 * @cancellable: a #GCancellable object
204 * Pops @cancellable off the cancellable stack (verifying that @cancellable
205 * is on the top of the stack).
208 g_cancellable_pop_current (GCancellable *cancellable)
212 l = g_private_get (¤t_cancellable);
214 g_return_if_fail (l != NULL);
215 g_return_if_fail (l->data == cancellable);
217 l = g_slist_delete_link (l, l);
218 g_private_set (¤t_cancellable, l);
222 * g_cancellable_get_current:
224 * Gets the top cancellable from the stack.
226 * Returns: (nullable) (transfer none): a #GCancellable from the top
227 * of the stack, or %NULL if the stack is empty.
230 g_cancellable_get_current (void)
234 l = g_private_get (¤t_cancellable);
238 return G_CANCELLABLE (l->data);
242 * g_cancellable_reset:
243 * @cancellable: a #GCancellable object.
245 * Resets @cancellable to its uncancelled state.
247 * If cancellable is currently in use by any cancellable operation
248 * then the behavior of this function is undefined.
250 * Note that it is generally not a good idea to reuse an existing
251 * cancellable for more operations after it has been cancelled once,
252 * as this function might tempt you to do. The recommended practice
253 * is to drop the reference to a cancellable after cancelling it,
254 * and let it die with the outstanding async operations. You should
255 * create a fresh cancellable for further async operations.
258 g_cancellable_reset (GCancellable *cancellable)
260 GCancellablePrivate *priv;
262 g_return_if_fail (G_IS_CANCELLABLE (cancellable));
264 g_mutex_lock (&cancellable_mutex);
266 priv = cancellable->priv;
268 while (priv->cancelled_running)
270 priv->cancelled_running_waiting = TRUE;
271 g_cond_wait (&cancellable_cond, &cancellable_mutex);
274 if (g_atomic_int_get (&priv->cancelled))
277 GLIB_PRIVATE_CALL (g_wakeup_acknowledge) (priv->wakeup);
279 g_atomic_int_set (&priv->cancelled, FALSE);
282 g_mutex_unlock (&cancellable_mutex);
286 * g_cancellable_is_cancelled:
287 * @cancellable: (nullable): a #GCancellable or %NULL
289 * Checks if a cancellable job has been cancelled.
291 * Returns: %TRUE if @cancellable is cancelled,
292 * FALSE if called with %NULL or if item is not cancelled.
295 g_cancellable_is_cancelled (GCancellable *cancellable)
297 return cancellable != NULL && g_atomic_int_get (&cancellable->priv->cancelled);
301 * g_cancellable_set_error_if_cancelled:
302 * @cancellable: (nullable): a #GCancellable or %NULL
303 * @error: #GError to append error state to
305 * If the @cancellable is cancelled, sets the error to notify
306 * that the operation was cancelled.
308 * Returns: %TRUE if @cancellable was cancelled, %FALSE if it was not
311 g_cancellable_set_error_if_cancelled (GCancellable *cancellable,
314 if (g_cancellable_is_cancelled (cancellable))
316 g_set_error_literal (error,
318 G_IO_ERROR_CANCELLED,
319 _("Operation was cancelled"));
327 * g_cancellable_get_fd:
328 * @cancellable: a #GCancellable.
330 * Gets the file descriptor for a cancellable job. This can be used to
331 * implement cancellable operations on Unix systems. The returned fd will
332 * turn readable when @cancellable is cancelled.
334 * You are not supposed to read from the fd yourself, just check for
335 * readable status. Reading to unset the readable status is done
336 * with g_cancellable_reset().
338 * After a successful return from this function, you should use
339 * g_cancellable_release_fd() to free up resources allocated for
340 * the returned file descriptor.
342 * See also g_cancellable_make_pollfd().
344 * Returns: A valid file descriptor. `-1` if the file descriptor
345 * is not supported, or on errors.
348 g_cancellable_get_fd (GCancellable *cancellable)
352 if (cancellable == NULL)
358 g_cancellable_make_pollfd (cancellable, &pollfd);
365 * g_cancellable_make_pollfd:
366 * @cancellable: (nullable): a #GCancellable or %NULL
367 * @pollfd: a pointer to a #GPollFD
369 * Creates a #GPollFD corresponding to @cancellable; this can be passed
370 * to g_poll() and used to poll for cancellation. This is useful both
371 * for unix systems without a native poll and for portability to
374 * When this function returns %TRUE, you should use
375 * g_cancellable_release_fd() to free up resources allocated for the
376 * @pollfd. After a %FALSE return, do not call g_cancellable_release_fd().
378 * If this function returns %FALSE, either no @cancellable was given or
379 * resource limits prevent this function from allocating the necessary
380 * structures for polling. (On Linux, you will likely have reached
381 * the maximum number of file descriptors.) The suggested way to handle
382 * these cases is to ignore the @cancellable.
384 * You are not supposed to read from the fd yourself, just check for
385 * readable status. Reading to unset the readable status is done
386 * with g_cancellable_reset().
388 * Returns: %TRUE if @pollfd was successfully initialized, %FALSE on
389 * failure to prepare the cancellable.
394 g_cancellable_make_pollfd (GCancellable *cancellable, GPollFD *pollfd)
396 g_return_val_if_fail (pollfd != NULL, FALSE);
397 if (cancellable == NULL)
399 g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), FALSE);
401 g_mutex_lock (&cancellable_mutex);
403 cancellable->priv->fd_refcount++;
405 if (cancellable->priv->wakeup == NULL)
407 cancellable->priv->wakeup = GLIB_PRIVATE_CALL (g_wakeup_new) ();
409 if (g_atomic_int_get (&cancellable->priv->cancelled))
410 GLIB_PRIVATE_CALL (g_wakeup_signal) (cancellable->priv->wakeup);
413 GLIB_PRIVATE_CALL (g_wakeup_get_pollfd) (cancellable->priv->wakeup, pollfd);
415 g_mutex_unlock (&cancellable_mutex);
421 * g_cancellable_release_fd:
422 * @cancellable: a #GCancellable
424 * Releases a resources previously allocated by g_cancellable_get_fd()
425 * or g_cancellable_make_pollfd().
427 * For compatibility reasons with older releases, calling this function
428 * is not strictly required, the resources will be automatically freed
429 * when the @cancellable is finalized. However, the @cancellable will
430 * block scarce file descriptors until it is finalized if this function
431 * is not called. This can cause the application to run out of file
432 * descriptors when many #GCancellables are used at the same time.
437 g_cancellable_release_fd (GCancellable *cancellable)
439 GCancellablePrivate *priv;
441 if (cancellable == NULL)
444 g_return_if_fail (G_IS_CANCELLABLE (cancellable));
446 priv = cancellable->priv;
448 g_mutex_lock (&cancellable_mutex);
449 g_assert (priv->fd_refcount > 0);
452 if (priv->fd_refcount == 0)
454 GLIB_PRIVATE_CALL (g_wakeup_free) (priv->wakeup);
458 g_mutex_unlock (&cancellable_mutex);
462 * g_cancellable_cancel:
463 * @cancellable: (nullable): a #GCancellable object.
465 * Will set @cancellable to cancelled, and will emit the
466 * #GCancellable::cancelled signal. (However, see the warning about
467 * race conditions in the documentation for that signal if you are
468 * planning to connect to it.)
470 * This function is thread-safe. In other words, you can safely call
471 * it from a thread other than the one running the operation that was
472 * passed the @cancellable.
474 * If @cancellable is %NULL, this function returns immediately for convenience.
476 * The convention within GIO is that cancelling an asynchronous
477 * operation causes it to complete asynchronously. That is, if you
478 * cancel the operation from the same thread in which it is running,
479 * then the operation's #GAsyncReadyCallback will not be invoked until
480 * the application returns to the main loop.
483 g_cancellable_cancel (GCancellable *cancellable)
485 GCancellablePrivate *priv;
487 if (cancellable == NULL || g_cancellable_is_cancelled (cancellable))
490 priv = cancellable->priv;
492 g_mutex_lock (&cancellable_mutex);
494 if (g_atomic_int_get (&priv->cancelled))
496 g_mutex_unlock (&cancellable_mutex);
500 g_atomic_int_set (&priv->cancelled, TRUE);
501 priv->cancelled_running = TRUE;
504 GLIB_PRIVATE_CALL (g_wakeup_signal) (priv->wakeup);
506 g_mutex_unlock (&cancellable_mutex);
508 g_object_ref (cancellable);
509 g_signal_emit (cancellable, signals[CANCELLED], 0);
511 g_mutex_lock (&cancellable_mutex);
513 priv->cancelled_running = FALSE;
514 if (priv->cancelled_running_waiting)
515 g_cond_broadcast (&cancellable_cond);
516 priv->cancelled_running_waiting = FALSE;
518 g_mutex_unlock (&cancellable_mutex);
520 g_object_unref (cancellable);
524 * g_cancellable_connect:
525 * @cancellable: A #GCancellable.
526 * @callback: The #GCallback to connect.
527 * @data: Data to pass to @callback.
528 * @data_destroy_func: (nullable): Free function for @data or %NULL.
530 * Convenience function to connect to the #GCancellable::cancelled
531 * signal. Also handles the race condition that may happen
532 * if the cancellable is cancelled right before connecting.
534 * @callback is called at most once, either directly at the
535 * time of the connect if @cancellable is already cancelled,
536 * or when @cancellable is cancelled in some thread.
538 * @data_destroy_func will be called when the handler is
539 * disconnected, or immediately if the cancellable is already
542 * See #GCancellable::cancelled for details on how to use this.
544 * Since GLib 2.40, the lock protecting @cancellable is not held when
545 * @callback is invoked. This lifts a restriction in place for
546 * earlier GLib versions which now makes it easier to write cleanup
547 * code that unconditionally invokes e.g. g_cancellable_cancel().
549 * Returns: The id of the signal handler or 0 if @cancellable has already
555 g_cancellable_connect (GCancellable *cancellable,
558 GDestroyNotify data_destroy_func)
562 g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), 0);
564 g_mutex_lock (&cancellable_mutex);
566 if (g_atomic_int_get (&cancellable->priv->cancelled))
568 void (*_callback) (GCancellable *cancellable,
571 g_mutex_unlock (&cancellable_mutex);
573 _callback = (void *)callback;
576 _callback (cancellable, data);
578 if (data_destroy_func)
579 data_destroy_func (data);
583 id = g_signal_connect_data (cancellable, "cancelled",
585 (GClosureNotify) data_destroy_func,
588 g_mutex_unlock (&cancellable_mutex);
596 * g_cancellable_disconnect:
597 * @cancellable: (nullable): A #GCancellable or %NULL.
598 * @handler_id: Handler id of the handler to be disconnected, or `0`.
600 * Disconnects a handler from a cancellable instance similar to
601 * g_signal_handler_disconnect(). Additionally, in the event that a
602 * signal handler is currently running, this call will block until the
603 * handler has finished. Calling this function from a
604 * #GCancellable::cancelled signal handler will therefore result in a
607 * This avoids a race condition where a thread cancels at the
608 * same time as the cancellable operation is finished and the
609 * signal handler is removed. See #GCancellable::cancelled for
610 * details on how to use this.
612 * If @cancellable is %NULL or @handler_id is `0` this function does
618 g_cancellable_disconnect (GCancellable *cancellable,
621 GCancellablePrivate *priv;
623 if (handler_id == 0 || cancellable == NULL)
626 g_mutex_lock (&cancellable_mutex);
628 priv = cancellable->priv;
630 while (priv->cancelled_running)
632 priv->cancelled_running_waiting = TRUE;
633 g_cond_wait (&cancellable_cond, &cancellable_mutex);
636 g_signal_handler_disconnect (cancellable, handler_id);
638 g_mutex_unlock (&cancellable_mutex);
644 GCancellable *cancellable;
645 guint cancelled_handler;
646 } GCancellableSource;
649 * We can't guarantee that the source still has references, so we are
650 * relying on the fact that g_source_set_ready_time() no longer makes
651 * assertions about the reference count - the source might be in the
652 * window between last-unref and finalize, during which its refcount
653 * is officially 0. However, we *can* guarantee that it's OK to
654 * dereference it in a limited way, because we know we haven't yet reached
655 * cancellable_source_finalize() - if we had, then we would have waited
656 * for signal emission to finish, then disconnected the signal handler
658 * See https://bugzilla.gnome.org/show_bug.cgi?id=791754
661 cancellable_source_cancelled (GCancellable *cancellable,
664 GSource *source = user_data;
666 g_source_set_ready_time (source, 0);
670 cancellable_source_dispatch (GSource *source,
671 GSourceFunc callback,
674 GCancellableSourceFunc func = (GCancellableSourceFunc)callback;
675 GCancellableSource *cancellable_source = (GCancellableSource *)source;
677 g_source_set_ready_time (source, -1);
678 return (*func) (cancellable_source->cancellable, user_data);
682 cancellable_source_finalize (GSource *source)
684 GCancellableSource *cancellable_source = (GCancellableSource *)source;
686 if (cancellable_source->cancellable)
688 g_cancellable_disconnect (cancellable_source->cancellable,
689 cancellable_source->cancelled_handler);
690 g_object_unref (cancellable_source->cancellable);
695 cancellable_source_closure_callback (GCancellable *cancellable,
698 GClosure *closure = data;
700 GValue params = G_VALUE_INIT;
701 GValue result_value = G_VALUE_INIT;
704 g_value_init (&result_value, G_TYPE_BOOLEAN);
706 g_value_init (¶ms, G_TYPE_CANCELLABLE);
707 g_value_set_object (¶ms, cancellable);
709 g_closure_invoke (closure, &result_value, 1, ¶ms, NULL);
711 result = g_value_get_boolean (&result_value);
712 g_value_unset (&result_value);
713 g_value_unset (¶ms);
718 static GSourceFuncs cancellable_source_funcs =
722 cancellable_source_dispatch,
723 cancellable_source_finalize,
724 (GSourceFunc)cancellable_source_closure_callback,
728 * g_cancellable_source_new: (skip)
729 * @cancellable: (nullable): a #GCancellable, or %NULL
731 * Creates a source that triggers if @cancellable is cancelled and
732 * calls its callback of type #GCancellableSourceFunc. This is
733 * primarily useful for attaching to another (non-cancellable) source
734 * with g_source_add_child_source() to add cancellability to it.
736 * For convenience, you can call this with a %NULL #GCancellable,
737 * in which case the source will never trigger.
739 * The new #GSource will hold a reference to the #GCancellable.
741 * Returns: (transfer full): the new #GSource.
746 g_cancellable_source_new (GCancellable *cancellable)
749 GCancellableSource *cancellable_source;
751 source = g_source_new (&cancellable_source_funcs, sizeof (GCancellableSource));
752 g_source_set_name (source, "GCancellable");
753 cancellable_source = (GCancellableSource *)source;
757 cancellable_source->cancellable = g_object_ref (cancellable);
759 /* We intentionally don't use g_cancellable_connect() here,
760 * because we don't want the "at most once" behavior.
762 cancellable_source->cancelled_handler =
763 g_signal_connect (cancellable, "cancelled",
764 G_CALLBACK (cancellable_source_cancelled),
766 if (g_cancellable_is_cancelled (cancellable))
767 g_source_set_ready_time (source, 0);