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 GPrivate current_cancellable;
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_private_get (¤t_cancellable);
205 l = g_slist_prepend (l, cancellable);
206 g_private_set (¤t_cancellable, l);
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_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_private_set (¤t_cancellable, l);
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_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, &G_LOCK_NAME (cancellable));
279 GLIB_PRIVATE_CALL (g_wakeup_acknowledge) (priv->wakeup);
281 priv->cancelled = FALSE;
283 G_UNLOCK(cancellable);
287 * g_cancellable_is_cancelled:
288 * @cancellable: (allow-none): a #GCancellable or %NULL
290 * Checks if a cancellable job has been cancelled.
292 * Returns: %TRUE if @cancellable is cancelled,
293 * FALSE if called with %NULL or if item is not cancelled.
296 g_cancellable_is_cancelled (GCancellable *cancellable)
298 return cancellable != NULL && cancellable->priv->cancelled;
302 * g_cancellable_set_error_if_cancelled:
303 * @cancellable: (allow-none): a #GCancellable or %NULL
304 * @error: #GError to append error state to
306 * If the @cancellable is cancelled, sets the error to notify
307 * that the operation was cancelled.
309 * Returns: %TRUE if @cancellable was cancelled, %FALSE if it was not
312 g_cancellable_set_error_if_cancelled (GCancellable *cancellable,
315 if (g_cancellable_is_cancelled (cancellable))
317 g_set_error_literal (error,
319 G_IO_ERROR_CANCELLED,
320 _("Operation was cancelled"));
328 * g_cancellable_get_fd:
329 * @cancellable: a #GCancellable.
331 * Gets the file descriptor for a cancellable job. This can be used to
332 * implement cancellable operations on Unix systems. The returned fd will
333 * turn readable when @cancellable is cancelled.
335 * You are not supposed to read from the fd yourself, just check for
336 * readable status. Reading to unset the readable status is done
337 * with g_cancellable_reset().
339 * After a successful return from this function, you should use
340 * g_cancellable_release_fd() to free up resources allocated for
341 * the returned file descriptor.
343 * See also g_cancellable_make_pollfd().
345 * Returns: A valid file descriptor. %-1 if the file descriptor
346 * is not supported, or on errors.
349 g_cancellable_get_fd (GCancellable *cancellable)
353 if (cancellable == NULL)
359 g_cancellable_make_pollfd (cancellable, &pollfd);
366 * g_cancellable_make_pollfd:
367 * @cancellable: a #GCancellable or %NULL
368 * @pollfd: a pointer to a #GPollFD
370 * Creates a #GPollFD corresponding to @cancellable; this can be passed
371 * to g_poll() and used to poll for cancellation. This is useful both
372 * for unix systems without a native poll and for portability to
375 * When this function returns %TRUE, you should use
376 * g_cancellable_release_fd() to free up resources allocated for the
377 * @pollfd. After a %FALSE return, do not call g_cancellable_release_fd().
379 * If this function returns %FALSE, either no @cancellable was given or
380 * resource limits prevent this function from allocating the necessary
381 * structures for polling. (On Linux, you will likely have reached
382 * the maximum number of file descriptors.) The suggested way to handle
383 * these cases is to ignore the @cancellable.
385 * You are not supposed to read from the fd yourself, just check for
386 * readable status. Reading to unset the readable status is done
387 * with g_cancellable_reset().
389 * Returns: %TRUE if @pollfd was successfully initialized, %FALSE on
390 * failure to prepare the cancellable.
395 g_cancellable_make_pollfd (GCancellable *cancellable, GPollFD *pollfd)
397 g_return_val_if_fail (pollfd != NULL, FALSE);
398 if (cancellable == NULL)
400 g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), FALSE);
404 cancellable->priv->fd_refcount++;
406 if (cancellable->priv->wakeup == NULL)
408 cancellable->priv->wakeup = GLIB_PRIVATE_CALL (g_wakeup_new) ();
410 if (cancellable->priv->cancelled)
411 GLIB_PRIVATE_CALL (g_wakeup_signal) (cancellable->priv->wakeup);
414 GLIB_PRIVATE_CALL (g_wakeup_get_pollfd) (cancellable->priv->wakeup, pollfd);
416 G_UNLOCK(cancellable);
422 * g_cancellable_release_fd:
423 * @cancellable: a #GCancellable
425 * Releases a resources previously allocated by g_cancellable_get_fd()
426 * or g_cancellable_make_pollfd().
428 * For compatibility reasons with older releases, calling this function
429 * is not strictly required, the resources will be automatically freed
430 * when the @cancellable is finalized. However, the @cancellable will
431 * block scarce file descriptors until it is finalized if this function
432 * is not called. This can cause the application to run out of file
433 * descriptors when many #GCancellables are used at the same time.
438 g_cancellable_release_fd (GCancellable *cancellable)
440 GCancellablePrivate *priv;
442 if (cancellable == NULL)
445 g_return_if_fail (G_IS_CANCELLABLE (cancellable));
446 g_return_if_fail (cancellable->priv->fd_refcount > 0);
448 priv = cancellable->priv;
450 G_LOCK (cancellable);
452 if (priv->fd_refcount == 0)
454 GLIB_PRIVATE_CALL (g_wakeup_free) (priv->wakeup);
457 G_UNLOCK (cancellable);
461 * g_cancellable_cancel:
462 * @cancellable: a #GCancellable object.
464 * Will set @cancellable to cancelled, and will emit the
465 * #GCancellable::cancelled signal. (However, see the warning about
466 * race conditions in the documentation for that signal if you are
467 * planning to connect to it.)
469 * This function is thread-safe. In other words, you can safely call
470 * it from a thread other than the one running the operation that was
471 * passed the @cancellable.
473 * The convention within gio is that cancelling an asynchronous
474 * operation causes it to complete asynchronously. That is, if you
475 * cancel the operation from the same thread in which it is running,
476 * then the operation's #GAsyncReadyCallback will not be invoked until
477 * the application returns to the main loop.
480 g_cancellable_cancel (GCancellable *cancellable)
482 GCancellablePrivate *priv;
484 if (cancellable == NULL ||
485 cancellable->priv->cancelled)
488 priv = cancellable->priv;
493 G_UNLOCK (cancellable);
497 priv->cancelled = TRUE;
498 priv->cancelled_running = TRUE;
501 GLIB_PRIVATE_CALL (g_wakeup_signal) (priv->wakeup);
503 G_UNLOCK(cancellable);
505 g_object_ref (cancellable);
506 g_signal_emit (cancellable, signals[CANCELLED], 0);
510 priv->cancelled_running = FALSE;
511 if (priv->cancelled_running_waiting)
512 g_cond_broadcast (cancellable_cond);
513 priv->cancelled_running_waiting = FALSE;
515 G_UNLOCK(cancellable);
517 g_object_unref (cancellable);
521 * g_cancellable_connect:
522 * @cancellable: A #GCancellable.
523 * @callback: The #GCallback to connect.
524 * @data: Data to pass to @callback.
525 * @data_destroy_func: Free function for @data or %NULL.
527 * Convenience function to connect to the #GCancellable::cancelled
528 * signal. Also handles the race condition that may happen
529 * if the cancellable is cancelled right before connecting.
531 * @callback is called at most once, either directly at the
532 * time of the connect if @cancellable is already cancelled,
533 * or when @cancellable is cancelled in some thread.
535 * @data_destroy_func will be called when the handler is
536 * disconnected, or immediately if the cancellable is already
539 * See #GCancellable::cancelled for details on how to use this.
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_LOCK (cancellable);
558 if (cancellable->priv->cancelled)
560 void (*_callback) (GCancellable *cancellable,
563 _callback = (void *)callback;
566 _callback (cancellable, data);
568 if (data_destroy_func)
569 data_destroy_func (data);
573 id = g_signal_connect_data (cancellable, "cancelled",
575 (GClosureNotify) data_destroy_func,
578 G_UNLOCK (cancellable);
584 * g_cancellable_disconnect:
585 * @cancellable: A #GCancellable or %NULL.
586 * @handler_id: Handler id of the handler to be disconnected, or %0.
588 * Disconnects a handler from a cancellable instance similar to
589 * g_signal_handler_disconnect(). Additionally, in the event that a
590 * signal handler is currently running, this call will block until the
591 * handler has finished. Calling this function from a
592 * #GCancellable::cancelled signal handler will therefore result in a
595 * This avoids a race condition where a thread cancels at the
596 * same time as the cancellable operation is finished and the
597 * signal handler is removed. See #GCancellable::cancelled for
598 * details on how to use this.
600 * If @cancellable is %NULL or @handler_id is %0 this function does
606 g_cancellable_disconnect (GCancellable *cancellable,
609 GCancellablePrivate *priv;
611 if (handler_id == 0 || cancellable == NULL)
614 G_LOCK (cancellable);
616 priv = cancellable->priv;
618 while (priv->cancelled_running)
620 priv->cancelled_running_waiting = TRUE;
621 g_cond_wait (cancellable_cond, &G_LOCK_NAME (cancellable));
624 g_signal_handler_disconnect (cancellable, handler_id);
625 G_UNLOCK (cancellable);
631 GCancellable *cancellable;
633 } GCancellableSource;
636 cancellable_source_prepare (GSource *source,
639 GCancellableSource *cancellable_source = (GCancellableSource *)source;
642 return g_cancellable_is_cancelled (cancellable_source->cancellable);
646 cancellable_source_check (GSource *source)
648 GCancellableSource *cancellable_source = (GCancellableSource *)source;
650 return g_cancellable_is_cancelled (cancellable_source->cancellable);
654 cancellable_source_dispatch (GSource *source,
655 GSourceFunc callback,
658 GCancellableSourceFunc func = (GCancellableSourceFunc)callback;
659 GCancellableSource *cancellable_source = (GCancellableSource *)source;
661 return (*func) (cancellable_source->cancellable, user_data);
665 cancellable_source_finalize (GSource *source)
667 GCancellableSource *cancellable_source = (GCancellableSource *)source;
669 if (cancellable_source->cancellable)
670 g_object_unref (cancellable_source->cancellable);
674 cancellable_source_closure_callback (GCancellable *cancellable,
677 GClosure *closure = data;
679 GValue params = { 0, };
680 GValue result_value = { 0, };
683 g_value_init (&result_value, G_TYPE_BOOLEAN);
685 g_value_init (¶ms, G_TYPE_CANCELLABLE);
686 g_value_set_object (¶ms, cancellable);
688 g_closure_invoke (closure, &result_value, 1, ¶ms, NULL);
690 result = g_value_get_boolean (&result_value);
691 g_value_unset (&result_value);
692 g_value_unset (¶ms);
697 static GSourceFuncs cancellable_source_funcs =
699 cancellable_source_prepare,
700 cancellable_source_check,
701 cancellable_source_dispatch,
702 cancellable_source_finalize,
703 (GSourceFunc)cancellable_source_closure_callback,
704 (GSourceDummyMarshal)g_cclosure_marshal_generic,
708 * g_cancellable_source_new: (skip)
709 * @cancellable: a #GCancellable, or %NULL
711 * Creates a source that triggers if @cancellable is cancelled and
712 * calls its callback of type #GCancellableSourceFunc. This is
713 * primarily useful for attaching to another (non-cancellable) source
714 * with g_source_add_child_source() to add cancellability to it.
716 * For convenience, you can call this with a %NULL #GCancellable,
717 * in which case the source will never trigger.
719 * Return value: (transfer full): the new #GSource.
724 g_cancellable_source_new (GCancellable *cancellable)
727 GCancellableSource *cancellable_source;
729 source = g_source_new (&cancellable_source_funcs, sizeof (GCancellableSource));
730 g_source_set_name (source, "GCancellable");
731 cancellable_source = (GCancellableSource *)source;
733 if (g_cancellable_make_pollfd (cancellable,
734 &cancellable_source->pollfd))
736 cancellable_source->cancellable = g_object_ref (cancellable);
737 g_source_add_poll (source, &cancellable_source->pollfd);