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-private.h"
27 #include "gcancellable.h"
32 * SECTION:gcancellable
33 * @short_description: Thread-safe Operation Cancellation Stack
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
49 guint cancelled_running : 1;
50 guint cancelled_running_waiting : 1;
56 static guint signals[LAST_SIGNAL] = { 0 };
58 G_DEFINE_TYPE (GCancellable, g_cancellable, G_TYPE_OBJECT);
60 static GStaticPrivate current_cancellable = G_STATIC_PRIVATE_INIT;
61 G_LOCK_DEFINE_STATIC(cancellable);
62 static GCond *cancellable_cond = NULL;
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 g_type_class_add_private (klass, sizeof (GCancellablePrivate));
82 if (cancellable_cond == NULL)
83 cancellable_cond = g_cond_new ();
85 gobject_class->finalize = g_cancellable_finalize;
88 * GCancellable::cancelled:
89 * @cancellable: a #GCancellable.
91 * Emitted when the operation has been cancelled.
93 * Can be used by implementations of cancellable operations. If the
94 * operation is cancelled from another thread, the signal will be
95 * emitted in the thread that cancelled the operation, not the
96 * thread that is running the operation.
98 * Note that disconnecting from this signal (or any signal) in a
99 * multi-threaded program is prone to race conditions. For instance
100 * it is possible that a signal handler may be invoked even
101 * <emphasis>after</emphasis> a call to
102 * g_signal_handler_disconnect() for that handler has already
105 * There is also a problem when cancellation happen
106 * right before connecting to the signal. If this happens the
107 * signal will unexpectedly not be emitted, and checking before
108 * connecting to the signal leaves a race condition where this is
111 * In order to make it safe and easy to connect handlers there
112 * are two helper functions: g_cancellable_connect() and
113 * g_cancellable_disconnect() which protect against problems
116 * An example of how to us this:
118 * /<!-- -->* Make sure we don't do any unnecessary work if already cancelled *<!-- -->/
119 * if (g_cancellable_set_error_if_cancelled (cancellable))
122 * /<!-- -->* Set up all the data needed to be able to
123 * * handle cancellation of the operation *<!-- -->/
124 * my_data = my_data_new (...);
128 * id = g_cancellable_connect (cancellable,
129 * G_CALLBACK (cancelled_handler)
132 * /<!-- -->* cancellable operation here... *<!-- -->/
134 * g_cancellable_disconnect (cancellable, id);
136 * /<!-- -->* cancelled_handler is never called after this, it
137 * * is now safe to free the data *<!-- -->/
138 * my_data_free (my_data);
141 * Note that the cancelled signal is emitted in the thread that
142 * the user cancelled from, which may be the main thread. So, the
143 * cancellable signal should not do something that can block.
146 g_signal_new (I_("cancelled"),
147 G_TYPE_FROM_CLASS (gobject_class),
149 G_STRUCT_OFFSET (GCancellableClass, cancelled),
151 g_cclosure_marshal_VOID__VOID,
157 g_cancellable_init (GCancellable *cancellable)
159 cancellable->priv = G_TYPE_INSTANCE_GET_PRIVATE (cancellable,
161 GCancellablePrivate);
167 * Creates a new #GCancellable object.
169 * Applications that want to start one or more operations
170 * that should be cancellable should create a #GCancellable
171 * and pass it to the operations.
173 * One #GCancellable can be used in multiple consecutive
174 * operations or in multiple concurrent operations.
176 * Returns: a #GCancellable.
179 g_cancellable_new (void)
181 return g_object_new (G_TYPE_CANCELLABLE, NULL);
185 * g_cancellable_push_current:
186 * @cancellable: a #GCancellable object
188 * Pushes @cancellable onto the cancellable stack. The current
189 * cancellable can then be received using g_cancellable_get_current().
191 * This is useful when implementing cancellable operations in
192 * code that does not allow you to pass down the cancellable object.
194 * This is typically called automatically by e.g. #GFile operations,
195 * so you rarely have to call this yourself.
198 g_cancellable_push_current (GCancellable *cancellable)
202 g_return_if_fail (cancellable != NULL);
204 l = g_static_private_get (¤t_cancellable);
205 l = g_slist_prepend (l, cancellable);
206 g_static_private_set (¤t_cancellable, l, NULL);
210 * g_cancellable_pop_current:
211 * @cancellable: a #GCancellable object
213 * Pops @cancellable off the cancellable stack (verifying that @cancellable
214 * is on the top of the stack).
217 g_cancellable_pop_current (GCancellable *cancellable)
221 l = g_static_private_get (¤t_cancellable);
223 g_return_if_fail (l != NULL);
224 g_return_if_fail (l->data == cancellable);
226 l = g_slist_delete_link (l, l);
227 g_static_private_set (¤t_cancellable, l, NULL);
231 * g_cancellable_get_current:
233 * Gets the top cancellable from the stack.
235 * Returns: (transfer none): a #GCancellable from the top of the stack, or %NULL
236 * if the stack is empty.
239 g_cancellable_get_current (void)
243 l = g_static_private_get (¤t_cancellable);
247 return G_CANCELLABLE (l->data);
251 * g_cancellable_reset:
252 * @cancellable: a #GCancellable object.
254 * Resets @cancellable to its uncancelled state.
256 * If cancellable is currently in use by any cancellable operation
257 * then the behavior of this function is undefined.
260 g_cancellable_reset (GCancellable *cancellable)
262 GCancellablePrivate *priv;
264 g_return_if_fail (G_IS_CANCELLABLE (cancellable));
268 priv = cancellable->priv;
270 while (priv->cancelled_running)
272 priv->cancelled_running_waiting = TRUE;
273 g_cond_wait (cancellable_cond,
274 g_static_mutex_get_mutex (& G_LOCK_NAME (cancellable)));
280 GLIB_PRIVATE_CALL (g_wakeup_acknowledge) (priv->wakeup);
282 priv->cancelled = FALSE;
284 G_UNLOCK(cancellable);
288 * g_cancellable_is_cancelled:
289 * @cancellable: (allow-none): a #GCancellable or %NULL
291 * Checks if a cancellable job has been cancelled.
293 * Returns: %TRUE if @cancellable is cancelled,
294 * FALSE if called with %NULL or if item is not cancelled.
297 g_cancellable_is_cancelled (GCancellable *cancellable)
299 return cancellable != NULL && cancellable->priv->cancelled;
303 * g_cancellable_set_error_if_cancelled:
304 * @cancellable: (allow-none): a #GCancellable or %NULL
305 * @error: #GError to append error state to
307 * If the @cancellable is cancelled, sets the error to notify
308 * that the operation was cancelled.
310 * Returns: %TRUE if @cancellable was cancelled, %FALSE if it was not
313 g_cancellable_set_error_if_cancelled (GCancellable *cancellable,
316 if (g_cancellable_is_cancelled (cancellable))
318 g_set_error_literal (error,
320 G_IO_ERROR_CANCELLED,
321 _("Operation was cancelled"));
329 * g_cancellable_get_fd:
330 * @cancellable: a #GCancellable.
332 * Gets the file descriptor for a cancellable job. This can be used to
333 * implement cancellable operations on Unix systems. The returned fd will
334 * turn readable when @cancellable is cancelled.
336 * You are not supposed to read from the fd yourself, just check for
337 * readable status. Reading to unset the readable status is done
338 * with g_cancellable_reset().
340 * After a successful return from this function, you should use
341 * g_cancellable_release_fd() to free up resources allocated for
342 * the returned file descriptor.
344 * See also g_cancellable_make_pollfd().
346 * Returns: A valid file descriptor. %-1 if the file descriptor
347 * is not supported, or on errors.
350 g_cancellable_get_fd (GCancellable *cancellable)
354 if (cancellable == NULL)
360 g_cancellable_make_pollfd (cancellable, &pollfd);
367 * g_cancellable_make_pollfd:
368 * @cancellable: a #GCancellable or %NULL
369 * @pollfd: a pointer to a #GPollFD
371 * Creates a #GPollFD corresponding to @cancellable; this can be passed
372 * to g_poll() and used to poll for cancellation. This is useful both
373 * for unix systems without a native poll and for portability to
376 * When this function returns %TRUE, you should use
377 * g_cancellable_release_fd() to free up resources allocated for the
378 * @pollfd. After a %FALSE return, do not call g_cancellable_release_fd().
380 * If this function returns %FALSE, either no @cancellable was given or
381 * resource limits prevent this function from allocating the necessary
382 * structures for polling. (On Linux, you will likely have reached
383 * the maximum number of file descriptors.) The suggested way to handle
384 * these cases is to ignore the @cancellable.
386 * You are not supposed to read from the fd yourself, just check for
387 * readable status. Reading to unset the readable status is done
388 * with g_cancellable_reset().
390 * Returns: %TRUE if @pollfd was successfully initialized, %FALSE on
391 * failure to prepare the cancellable.
396 g_cancellable_make_pollfd (GCancellable *cancellable, GPollFD *pollfd)
398 g_return_val_if_fail (pollfd != NULL, FALSE);
399 if (cancellable == NULL)
401 g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), FALSE);
405 cancellable->priv->fd_refcount++;
407 if (cancellable->priv->wakeup == NULL)
409 cancellable->priv->wakeup = GLIB_PRIVATE_CALL (g_wakeup_new) ();
411 if (cancellable->priv->cancelled)
412 GLIB_PRIVATE_CALL (g_wakeup_signal) (cancellable->priv->wakeup);
415 GLIB_PRIVATE_CALL (g_wakeup_get_pollfd) (cancellable->priv->wakeup, pollfd);
417 G_UNLOCK(cancellable);
423 * g_cancellable_release_fd:
424 * @cancellable: a #GCancellable
426 * Releases a resources previously allocated by g_cancellable_get_fd()
427 * or g_cancellable_make_pollfd().
429 * For compatibility reasons with older releases, calling this function
430 * is not strictly required, the resources will be automatically freed
431 * when the @cancellable is finalized. However, the @cancellable will
432 * block scarce file descriptors until it is finalized if this function
433 * is not called. This can cause the application to run out of file
434 * descriptors when many #GCancellables are used at the same time.
439 g_cancellable_release_fd (GCancellable *cancellable)
441 GCancellablePrivate *priv;
443 if (cancellable == NULL)
446 g_return_if_fail (G_IS_CANCELLABLE (cancellable));
447 g_return_if_fail (cancellable->priv->fd_refcount > 0);
449 priv = cancellable->priv;
451 G_LOCK (cancellable);
453 if (priv->fd_refcount == 0)
455 GLIB_PRIVATE_CALL (g_wakeup_free) (priv->wakeup);
458 G_UNLOCK (cancellable);
462 * g_cancellable_cancel:
463 * @cancellable: 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 * The convention within gio is that cancelling an asynchronous
475 * operation causes it to complete asynchronously. That is, if you
476 * cancel the operation from the same thread in which it is running,
477 * then the operation's #GAsyncReadyCallback will not be invoked until
478 * the application returns to the main loop.
481 g_cancellable_cancel (GCancellable *cancellable)
483 GCancellablePrivate *priv;
485 if (cancellable == NULL ||
486 cancellable->priv->cancelled)
489 priv = cancellable->priv;
494 G_UNLOCK (cancellable);
498 priv->cancelled = TRUE;
499 priv->cancelled_running = TRUE;
502 GLIB_PRIVATE_CALL (g_wakeup_signal) (priv->wakeup);
504 G_UNLOCK(cancellable);
506 g_object_ref (cancellable);
507 g_signal_emit (cancellable, signals[CANCELLED], 0);
511 priv->cancelled_running = FALSE;
512 if (priv->cancelled_running_waiting)
513 g_cond_broadcast (cancellable_cond);
514 priv->cancelled_running_waiting = FALSE;
516 G_UNLOCK(cancellable);
518 g_object_unref (cancellable);
522 * g_cancellable_connect:
523 * @cancellable: A #GCancellable.
524 * @callback: The #GCallback to connect.
525 * @data: Data to pass to @callback.
526 * @data_destroy_func: Free function for @data or %NULL.
528 * Convenience function to connect to the #GCancellable::cancelled
529 * signal. Also handles the race condition that may happen
530 * if the cancellable is cancelled right before connecting.
532 * @callback is called at most once, either directly at the
533 * time of the connect if @cancellable is already cancelled,
534 * or when @cancellable is cancelled in some thread.
536 * @data_destroy_func will be called when the handler is
537 * disconnected, or immediately if the cancellable is already
540 * See #GCancellable::cancelled for details on how to use this.
542 * Returns: The id of the signal handler or 0 if @cancellable has already
548 g_cancellable_connect (GCancellable *cancellable,
551 GDestroyNotify data_destroy_func)
555 g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), 0);
557 G_LOCK (cancellable);
559 if (cancellable->priv->cancelled)
561 void (*_callback) (GCancellable *cancellable,
564 _callback = (void *)callback;
567 _callback (cancellable, data);
569 if (data_destroy_func)
570 data_destroy_func (data);
574 id = g_signal_connect_data (cancellable, "cancelled",
576 (GClosureNotify) data_destroy_func,
579 G_UNLOCK (cancellable);
585 * g_cancellable_disconnect:
586 * @cancellable: A #GCancellable or %NULL.
587 * @handler_id: Handler id of the handler to be disconnected, or %0.
589 * Disconnects a handler from a cancellable instance similar to
590 * g_signal_handler_disconnect(). Additionally, in the event that a
591 * signal handler is currently running, this call will block until the
592 * handler has finished. Calling this function from a
593 * #GCancellable::cancelled signal handler will therefore result in a
596 * This avoids a race condition where a thread cancels at the
597 * same time as the cancellable operation is finished and the
598 * signal handler is removed. See #GCancellable::cancelled for
599 * details on how to use this.
601 * If @cancellable is %NULL or @handler_id is %0 this function does
607 g_cancellable_disconnect (GCancellable *cancellable,
610 GCancellablePrivate *priv;
612 if (handler_id == 0 || cancellable == NULL)
615 G_LOCK (cancellable);
617 priv = cancellable->priv;
619 while (priv->cancelled_running)
621 priv->cancelled_running_waiting = TRUE;
622 g_cond_wait (cancellable_cond,
623 g_static_mutex_get_mutex (& G_LOCK_NAME (cancellable)));
626 g_signal_handler_disconnect (cancellable, handler_id);
627 G_UNLOCK (cancellable);
633 GCancellable *cancellable;
635 } GCancellableSource;
638 cancellable_source_prepare (GSource *source,
641 GCancellableSource *cancellable_source = (GCancellableSource *)source;
644 return g_cancellable_is_cancelled (cancellable_source->cancellable);
648 cancellable_source_check (GSource *source)
650 GCancellableSource *cancellable_source = (GCancellableSource *)source;
652 return g_cancellable_is_cancelled (cancellable_source->cancellable);
656 cancellable_source_dispatch (GSource *source,
657 GSourceFunc callback,
660 GCancellableSourceFunc func = (GCancellableSourceFunc)callback;
661 GCancellableSource *cancellable_source = (GCancellableSource *)source;
663 return (*func) (cancellable_source->cancellable, user_data);
667 cancellable_source_finalize (GSource *source)
669 GCancellableSource *cancellable_source = (GCancellableSource *)source;
671 if (cancellable_source->cancellable)
672 g_object_unref (cancellable_source->cancellable);
676 cancellable_source_closure_callback (GCancellable *cancellable,
679 GClosure *closure = data;
681 GValue params = { 0, };
682 GValue result_value = { 0, };
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 =
701 cancellable_source_prepare,
702 cancellable_source_check,
703 cancellable_source_dispatch,
704 cancellable_source_finalize,
705 (GSourceFunc)cancellable_source_closure_callback,
706 (GSourceDummyMarshal)g_cclosure_marshal_generic,
710 * g_cancellable_source_new: (skip)
711 * @cancellable: a #GCancellable, or %NULL
713 * Creates a source that triggers if @cancellable is cancelled and
714 * calls its callback of type #GCancellableSourceFunc. This is
715 * primarily useful for attaching to another (non-cancellable) source
716 * with g_source_add_child_source() to add cancellability to it.
718 * For convenience, you can call this with a %NULL #GCancellable,
719 * in which case the source will never trigger.
721 * Return value: (transfer full): the new #GSource.
726 g_cancellable_source_new (GCancellable *cancellable)
729 GCancellableSource *cancellable_source;
731 source = g_source_new (&cancellable_source_funcs, sizeof (GCancellableSource));
732 g_source_set_name (source, "GCancellable");
733 cancellable_source = (GCancellableSource *)source;
735 if (g_cancellable_make_pollfd (cancellable,
736 &cancellable_source->pollfd))
738 cancellable_source->cancellable = g_object_ref (cancellable);
739 g_source_add_poll (source, &cancellable_source->pollfd);