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, 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
47 guint cancelled_running : 1;
48 guint cancelled_running_waiting : 1;
54 static guint signals[LAST_SIGNAL] = { 0 };
56 G_DEFINE_TYPE_WITH_PRIVATE (GCancellable, g_cancellable, G_TYPE_OBJECT)
58 static GPrivate current_cancellable;
59 static GMutex cancellable_mutex;
60 static GCond cancellable_cond;
63 g_cancellable_finalize (GObject *object)
65 GCancellable *cancellable = G_CANCELLABLE (object);
67 if (cancellable->priv->wakeup)
68 GLIB_PRIVATE_CALL (g_wakeup_free) (cancellable->priv->wakeup);
70 G_OBJECT_CLASS (g_cancellable_parent_class)->finalize (object);
74 g_cancellable_class_init (GCancellableClass *klass)
76 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
78 gobject_class->finalize = g_cancellable_finalize;
81 * GCancellable::cancelled:
82 * @cancellable: a #GCancellable.
84 * Emitted when the operation has been cancelled.
86 * Can be used by implementations of cancellable operations. If the
87 * operation is cancelled from another thread, the signal will be
88 * emitted in the thread that cancelled the operation, not the
89 * thread that is running the operation.
91 * Note that disconnecting from this signal (or any signal) in a
92 * multi-threaded program is prone to race conditions. For instance
93 * it is possible that a signal handler may be invoked even
94 * <emphasis>after</emphasis> a call to
95 * g_signal_handler_disconnect() for that handler has already
98 * There is also a problem when cancellation happen
99 * right before connecting to the signal. If this happens the
100 * signal will unexpectedly not be emitted, and checking before
101 * connecting to the signal leaves a race condition where this is
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:
111 * /<!-- -->* Make sure we don't do any 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
116 * * handle cancellation 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
130 * * is now safe 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),
144 g_cclosure_marshal_VOID__VOID,
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: (transfer none): a #GCancellable from the top of the stack, or %NULL
227 * 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.
251 g_cancellable_reset (GCancellable *cancellable)
253 GCancellablePrivate *priv;
255 g_return_if_fail (G_IS_CANCELLABLE (cancellable));
257 g_mutex_lock (&cancellable_mutex);
259 priv = cancellable->priv;
261 while (priv->cancelled_running)
263 priv->cancelled_running_waiting = TRUE;
264 g_cond_wait (&cancellable_cond, &cancellable_mutex);
270 GLIB_PRIVATE_CALL (g_wakeup_acknowledge) (priv->wakeup);
272 priv->cancelled = FALSE;
275 g_mutex_unlock (&cancellable_mutex);
279 * g_cancellable_is_cancelled:
280 * @cancellable: (allow-none): a #GCancellable or %NULL
282 * Checks if a cancellable job has been cancelled.
284 * Returns: %TRUE if @cancellable is cancelled,
285 * FALSE if called with %NULL or if item is not cancelled.
288 g_cancellable_is_cancelled (GCancellable *cancellable)
290 return cancellable != NULL && cancellable->priv->cancelled;
294 * g_cancellable_set_error_if_cancelled:
295 * @cancellable: (allow-none): a #GCancellable or %NULL
296 * @error: #GError to append error state to
298 * If the @cancellable is cancelled, sets the error to notify
299 * that the operation was cancelled.
301 * Returns: %TRUE if @cancellable was cancelled, %FALSE if it was not
304 g_cancellable_set_error_if_cancelled (GCancellable *cancellable,
307 if (g_cancellable_is_cancelled (cancellable))
309 g_set_error_literal (error,
311 G_IO_ERROR_CANCELLED,
312 _("Operation was cancelled"));
320 * g_cancellable_get_fd:
321 * @cancellable: a #GCancellable.
323 * Gets the file descriptor for a cancellable job. This can be used to
324 * implement cancellable operations on Unix systems. The returned fd will
325 * turn readable when @cancellable is cancelled.
327 * You are not supposed to read from the fd yourself, just check for
328 * readable status. Reading to unset the readable status is done
329 * with g_cancellable_reset().
331 * After a successful return from this function, you should use
332 * g_cancellable_release_fd() to free up resources allocated for
333 * the returned file descriptor.
335 * See also g_cancellable_make_pollfd().
337 * Returns: A valid file descriptor. %-1 if the file descriptor
338 * is not supported, or on errors.
341 g_cancellable_get_fd (GCancellable *cancellable)
345 if (cancellable == NULL)
351 g_cancellable_make_pollfd (cancellable, &pollfd);
358 * g_cancellable_make_pollfd:
359 * @cancellable: (allow-none): a #GCancellable or %NULL
360 * @pollfd: a pointer to a #GPollFD
362 * Creates a #GPollFD corresponding to @cancellable; this can be passed
363 * to g_poll() and used to poll for cancellation. This is useful both
364 * for unix systems without a native poll and for portability to
367 * When this function returns %TRUE, you should use
368 * g_cancellable_release_fd() to free up resources allocated for the
369 * @pollfd. After a %FALSE return, do not call g_cancellable_release_fd().
371 * If this function returns %FALSE, either no @cancellable was given or
372 * resource limits prevent this function from allocating the necessary
373 * structures for polling. (On Linux, you will likely have reached
374 * the maximum number of file descriptors.) The suggested way to handle
375 * these cases is to ignore the @cancellable.
377 * You are not supposed to read from the fd yourself, just check for
378 * readable status. Reading to unset the readable status is done
379 * with g_cancellable_reset().
381 * Returns: %TRUE if @pollfd was successfully initialized, %FALSE on
382 * failure to prepare the cancellable.
387 g_cancellable_make_pollfd (GCancellable *cancellable, GPollFD *pollfd)
389 g_return_val_if_fail (pollfd != NULL, FALSE);
390 if (cancellable == NULL)
392 g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), FALSE);
394 g_mutex_lock (&cancellable_mutex);
396 cancellable->priv->fd_refcount++;
398 if (cancellable->priv->wakeup == NULL)
400 cancellable->priv->wakeup = GLIB_PRIVATE_CALL (g_wakeup_new) ();
402 if (cancellable->priv->cancelled)
403 GLIB_PRIVATE_CALL (g_wakeup_signal) (cancellable->priv->wakeup);
406 GLIB_PRIVATE_CALL (g_wakeup_get_pollfd) (cancellable->priv->wakeup, pollfd);
408 g_mutex_unlock (&cancellable_mutex);
414 * g_cancellable_release_fd:
415 * @cancellable: a #GCancellable
417 * Releases a resources previously allocated by g_cancellable_get_fd()
418 * or g_cancellable_make_pollfd().
420 * For compatibility reasons with older releases, calling this function
421 * is not strictly required, the resources will be automatically freed
422 * when the @cancellable is finalized. However, the @cancellable will
423 * block scarce file descriptors until it is finalized if this function
424 * is not called. This can cause the application to run out of file
425 * descriptors when many #GCancellables are used at the same time.
430 g_cancellable_release_fd (GCancellable *cancellable)
432 GCancellablePrivate *priv;
434 if (cancellable == NULL)
437 g_return_if_fail (G_IS_CANCELLABLE (cancellable));
438 g_return_if_fail (cancellable->priv->fd_refcount > 0);
440 priv = cancellable->priv;
442 g_mutex_lock (&cancellable_mutex);
445 if (priv->fd_refcount == 0)
447 GLIB_PRIVATE_CALL (g_wakeup_free) (priv->wakeup);
451 g_mutex_unlock (&cancellable_mutex);
455 * g_cancellable_cancel:
456 * @cancellable: a #GCancellable object.
458 * Will set @cancellable to cancelled, and will emit the
459 * #GCancellable::cancelled signal. (However, see the warning about
460 * race conditions in the documentation for that signal if you are
461 * planning to connect to it.)
463 * This function is thread-safe. In other words, you can safely call
464 * it from a thread other than the one running the operation that was
465 * passed the @cancellable.
467 * The convention within gio is that cancelling an asynchronous
468 * operation causes it to complete asynchronously. That is, if you
469 * cancel the operation from the same thread in which it is running,
470 * then the operation's #GAsyncReadyCallback will not be invoked until
471 * the application returns to the main loop.
474 g_cancellable_cancel (GCancellable *cancellable)
476 GCancellablePrivate *priv;
478 if (cancellable == NULL ||
479 cancellable->priv->cancelled)
482 priv = cancellable->priv;
484 g_mutex_lock (&cancellable_mutex);
488 g_mutex_unlock (&cancellable_mutex);
492 priv->cancelled = TRUE;
493 priv->cancelled_running = TRUE;
496 GLIB_PRIVATE_CALL (g_wakeup_signal) (priv->wakeup);
498 g_mutex_unlock (&cancellable_mutex);
500 g_object_ref (cancellable);
501 g_signal_emit (cancellable, signals[CANCELLED], 0);
503 g_mutex_lock (&cancellable_mutex);
505 priv->cancelled_running = FALSE;
506 if (priv->cancelled_running_waiting)
507 g_cond_broadcast (&cancellable_cond);
508 priv->cancelled_running_waiting = FALSE;
510 g_mutex_unlock (&cancellable_mutex);
512 g_object_unref (cancellable);
516 * g_cancellable_connect:
517 * @cancellable: A #GCancellable.
518 * @callback: The #GCallback to connect.
519 * @data: Data to pass to @callback.
520 * @data_destroy_func: (allow-none): Free function for @data or %NULL.
522 * Convenience function to connect to the #GCancellable::cancelled
523 * signal. Also handles the race condition that may happen
524 * if the cancellable is cancelled right before connecting.
526 * @callback is called at most once, either directly at the
527 * time of the connect if @cancellable is already cancelled,
528 * or when @cancellable is cancelled in some thread.
530 * @data_destroy_func will be called when the handler is
531 * disconnected, or immediately if the cancellable is already
534 * See #GCancellable::cancelled for details on how to use this.
536 * Since GLib 2.40, the lock protecting @cancellable is not held when
537 * @callback is invoked. This lifts a restriction in place for
538 * earlier GLib versions which now makes it easier to write cleanup
539 * code that unconditionally invokes e.g. g_cancellable_cancel().
541 * Returns: The id of the signal handler or 0 if @cancellable has already
547 g_cancellable_connect (GCancellable *cancellable,
550 GDestroyNotify data_destroy_func)
554 g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), 0);
556 g_mutex_lock (&cancellable_mutex);
558 if (cancellable->priv->cancelled)
560 void (*_callback) (GCancellable *cancellable,
563 g_mutex_unlock (&cancellable_mutex);
565 _callback = (void *)callback;
568 _callback (cancellable, data);
570 if (data_destroy_func)
571 data_destroy_func (data);
575 id = g_signal_connect_data (cancellable, "cancelled",
577 (GClosureNotify) data_destroy_func,
580 g_mutex_unlock (&cancellable_mutex);
588 * g_cancellable_disconnect:
589 * @cancellable: (allow-none): A #GCancellable or %NULL.
590 * @handler_id: Handler id of the handler to be disconnected, or %0.
592 * Disconnects a handler from a cancellable instance similar to
593 * g_signal_handler_disconnect(). Additionally, in the event that a
594 * signal handler is currently running, this call will block until the
595 * handler has finished. Calling this function from a
596 * #GCancellable::cancelled signal handler will therefore result in a
599 * This avoids a race condition where a thread cancels at the
600 * same time as the cancellable operation is finished and the
601 * signal handler is removed. See #GCancellable::cancelled for
602 * details on how to use this.
604 * If @cancellable is %NULL or @handler_id is %0 this function does
610 g_cancellable_disconnect (GCancellable *cancellable,
613 GCancellablePrivate *priv;
615 if (handler_id == 0 || cancellable == NULL)
618 g_mutex_lock (&cancellable_mutex);
620 priv = cancellable->priv;
622 while (priv->cancelled_running)
624 priv->cancelled_running_waiting = TRUE;
625 g_cond_wait (&cancellable_cond, &cancellable_mutex);
628 g_signal_handler_disconnect (cancellable, handler_id);
630 g_mutex_unlock (&cancellable_mutex);
636 GCancellable *cancellable;
637 guint cancelled_handler;
638 } GCancellableSource;
641 cancellable_source_cancelled (GCancellable *cancellable,
644 GSource *source = user_data;
646 if (!g_source_is_destroyed (source))
647 g_source_set_ready_time (source, 0);
651 cancellable_source_dispatch (GSource *source,
652 GSourceFunc callback,
655 GCancellableSourceFunc func = (GCancellableSourceFunc)callback;
656 GCancellableSource *cancellable_source = (GCancellableSource *)source;
658 g_source_set_ready_time (source, -1);
659 return (*func) (cancellable_source->cancellable, user_data);
663 cancellable_source_finalize (GSource *source)
665 GCancellableSource *cancellable_source = (GCancellableSource *)source;
667 if (cancellable_source->cancellable)
669 g_cancellable_disconnect (cancellable_source->cancellable,
670 cancellable_source->cancelled_handler);
671 g_object_unref (cancellable_source->cancellable);
676 cancellable_source_closure_callback (GCancellable *cancellable,
679 GClosure *closure = data;
681 GValue params = G_VALUE_INIT;
682 GValue result_value = G_VALUE_INIT;
685 g_value_init (&result_value, G_TYPE_BOOLEAN);
687 g_value_init (¶ms, G_TYPE_CANCELLABLE);
688 g_value_set_object (¶ms, cancellable);
690 g_closure_invoke (closure, &result_value, 1, ¶ms, NULL);
692 result = g_value_get_boolean (&result_value);
693 g_value_unset (&result_value);
694 g_value_unset (¶ms);
699 static GSourceFuncs cancellable_source_funcs =
703 cancellable_source_dispatch,
704 cancellable_source_finalize,
705 (GSourceFunc)cancellable_source_closure_callback,
709 * g_cancellable_source_new: (skip)
710 * @cancellable: (allow-none): a #GCancellable, or %NULL
712 * Creates a source that triggers if @cancellable is cancelled and
713 * calls its callback of type #GCancellableSourceFunc. This is
714 * primarily useful for attaching to another (non-cancellable) source
715 * with g_source_add_child_source() to add cancellability to it.
717 * For convenience, you can call this with a %NULL #GCancellable,
718 * in which case the source will never trigger.
720 * Return value: (transfer full): the new #GSource.
725 g_cancellable_source_new (GCancellable *cancellable)
728 GCancellableSource *cancellable_source;
730 source = g_source_new (&cancellable_source_funcs, sizeof (GCancellableSource));
731 g_source_set_name (source, "GCancellable");
732 cancellable_source = (GCancellableSource *)source;
736 cancellable_source->cancellable = g_object_ref (cancellable);
738 /* We intentionally don't use g_cancellable_connect() here,
739 * because we don't want the "at most once" behavior.
741 cancellable_source->cancelled_handler =
742 g_signal_connect (cancellable, "cancelled",
743 G_CALLBACK (cancellable_source_cancelled),
745 if (g_cancellable_is_cancelled (cancellable))
746 g_source_set_ready_time (source, 0);