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 "gcancellable.h"
31 * SECTION:gcancellable
32 * @short_description: Thread-safe Operation Cancellation Stack
35 * GCancellable is a thread-safe operation cancellation stack used
36 * throughout GIO to allow for cancellation of synchronous and
37 * asynchronous operations.
45 struct _GCancellablePrivate
48 guint cancelled_running : 1;
49 guint cancelled_running_waiting : 1;
55 static guint signals[LAST_SIGNAL] = { 0 };
57 G_DEFINE_TYPE (GCancellable, g_cancellable, G_TYPE_OBJECT);
59 static GStaticPrivate current_cancellable = G_STATIC_PRIVATE_INIT;
60 G_LOCK_DEFINE_STATIC(cancellable);
61 static GCond *cancellable_cond = NULL;
64 g_cancellable_finalize (GObject *object)
66 GCancellable *cancellable = G_CANCELLABLE (object);
68 if (cancellable->priv->wakeup)
69 g_wakeup_free (cancellable->priv->wakeup);
71 G_OBJECT_CLASS (g_cancellable_parent_class)->finalize (object);
75 g_cancellable_class_init (GCancellableClass *klass)
77 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
79 g_type_class_add_private (klass, sizeof (GCancellablePrivate));
81 if (cancellable_cond == NULL && g_thread_supported ())
82 cancellable_cond = g_cond_new ();
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
100 * <emphasis>after</emphasis> a call to
101 * g_signal_handler_disconnect() for that handler has already
104 * There is also a problem when cancellation happen
105 * right before connecting to the signal. If this happens the
106 * signal will unexpectedly not be emitted, and checking before
107 * connecting to the signal leaves a race condition where this is
110 * In order to make it safe and easy to connect handlers there
111 * are two helper functions: g_cancellable_connect() and
112 * g_cancellable_disconnect() which protect against problems
115 * An example of how to us this:
117 * /<!-- -->* Make sure we don't do any unnecessary work if already cancelled *<!-- -->/
118 * if (g_cancellable_set_error_if_cancelled (cancellable))
121 * /<!-- -->* Set up all the data needed to be able to
122 * * handle cancellation of the operation *<!-- -->/
123 * my_data = my_data_new (...);
127 * id = g_cancellable_connect (cancellable,
128 * G_CALLBACK (cancelled_handler)
131 * /<!-- -->* cancellable operation here... *<!-- -->/
133 * g_cancellable_disconnect (cancellable, id);
135 * /<!-- -->* cancelled_handler is never called after this, it
136 * * is now safe to free the data *<!-- -->/
137 * my_data_free (my_data);
140 * Note that the cancelled signal is emitted in the thread that
141 * the user cancelled from, which may be the main thread. So, the
142 * cancellable signal should not do something that can block.
145 g_signal_new (I_("cancelled"),
146 G_TYPE_FROM_CLASS (gobject_class),
148 G_STRUCT_OFFSET (GCancellableClass, cancelled),
150 g_cclosure_marshal_VOID__VOID,
156 g_cancellable_init (GCancellable *cancellable)
158 cancellable->priv = G_TYPE_INSTANCE_GET_PRIVATE (cancellable,
160 GCancellablePrivate);
166 * Creates a new #GCancellable object.
168 * Applications that want to start one or more operations
169 * that should be cancellable should create a #GCancellable
170 * and pass it to the operations.
172 * One #GCancellable can be used in multiple consecutive
173 * operations, but not in multiple concurrent operations.
175 * Returns: a #GCancellable.
178 g_cancellable_new (void)
180 return g_object_new (G_TYPE_CANCELLABLE, NULL);
184 * g_cancellable_push_current:
185 * @cancellable: a #GCancellable object
187 * Pushes @cancellable onto the cancellable stack. The current
188 * cancellable can then be recieved using g_cancellable_get_current().
190 * This is useful when implementing cancellable operations in
191 * code that does not allow you to pass down the cancellable object.
193 * This is typically called automatically by e.g. #GFile operations,
194 * so you rarely have to call this yourself.
197 g_cancellable_push_current (GCancellable *cancellable)
201 g_return_if_fail (cancellable != NULL);
203 l = g_static_private_get (¤t_cancellable);
204 l = g_slist_prepend (l, cancellable);
205 g_static_private_set (¤t_cancellable, l, NULL);
209 * g_cancellable_pop_current:
210 * @cancellable: a #GCancellable object
212 * Pops @cancellable off the cancellable stack (verifying that @cancellable
213 * is on the top of the stack).
216 g_cancellable_pop_current (GCancellable *cancellable)
220 l = g_static_private_get (¤t_cancellable);
222 g_return_if_fail (l != NULL);
223 g_return_if_fail (l->data == cancellable);
225 l = g_slist_delete_link (l, l);
226 g_static_private_set (¤t_cancellable, l, NULL);
230 * g_cancellable_get_current:
232 * Gets the top cancellable from the stack.
234 * Returns: (transfer none): a #GCancellable from the top of the stack, or %NULL
235 * if the stack is empty.
238 g_cancellable_get_current (void)
242 l = g_static_private_get (¤t_cancellable);
246 return G_CANCELLABLE (l->data);
250 * g_cancellable_reset:
251 * @cancellable: a #GCancellable object.
253 * Resets @cancellable to its uncancelled state.
256 g_cancellable_reset (GCancellable *cancellable)
258 GCancellablePrivate *priv;
260 g_return_if_fail (G_IS_CANCELLABLE (cancellable));
264 priv = cancellable->priv;
266 while (priv->cancelled_running)
268 priv->cancelled_running_waiting = TRUE;
269 g_cond_wait (cancellable_cond,
270 g_static_mutex_get_mutex (& G_LOCK_NAME (cancellable)));
276 g_wakeup_acknowledge (priv->wakeup);
278 priv->cancelled = FALSE;
280 G_UNLOCK(cancellable);
284 * g_cancellable_is_cancelled:
285 * @cancellable: a #GCancellable or NULL.
287 * Checks if a cancellable job has been cancelled.
289 * Returns: %TRUE if @cancellable is cancelled,
290 * FALSE if called with %NULL or if item is not cancelled.
293 g_cancellable_is_cancelled (GCancellable *cancellable)
295 return cancellable != NULL && cancellable->priv->cancelled;
299 * g_cancellable_set_error_if_cancelled:
300 * @cancellable: a #GCancellable object.
301 * @error: #GError to append error state to.
303 * If the @cancellable is cancelled, sets the error to notify
304 * that the operation was cancelled.
306 * Returns: %TRUE if @cancellable was cancelled, %FALSE if it was not.
309 g_cancellable_set_error_if_cancelled (GCancellable *cancellable,
312 if (g_cancellable_is_cancelled (cancellable))
314 g_set_error_literal (error,
316 G_IO_ERROR_CANCELLED,
317 _("Operation was cancelled"));
325 * g_cancellable_get_fd:
326 * @cancellable: a #GCancellable.
328 * Gets the file descriptor for a cancellable job. This can be used to
329 * implement cancellable operations on Unix systems. The returned fd will
330 * turn readable when @cancellable is cancelled.
332 * You are not supposed to read from the fd yourself, just check for
333 * readable status. Reading to unset the readable status is done
334 * with g_cancellable_reset().
336 * After a successful return from this function, you should use
337 * g_cancellable_release_fd() to free up resources allocated for
338 * the returned file descriptor.
340 * See also g_cancellable_make_pollfd().
342 * Returns: A valid file descriptor. %-1 if the file descriptor
343 * is not supported, or on errors.
346 g_cancellable_get_fd (GCancellable *cancellable)
353 g_cancellable_make_pollfd (cancellable, &pollfd);
360 * g_cancellable_make_pollfd:
361 * @cancellable: a #GCancellable or %NULL
362 * @pollfd: a pointer to a #GPollFD
364 * Creates a #GPollFD corresponding to @cancellable; this can be passed
365 * to g_poll() and used to poll for cancellation. This is useful both
366 * for unix systems without a native poll and for portability to
369 * When this function returns %TRUE, you should use
370 * g_cancellable_release_fd() to free up resources allocated for the
371 * @pollfd. After a %FALSE return, do not call g_cancellable_release_fd().
373 * If this function returns %FALSE, either no @cancellable was given or
374 * resource limits prevent this function from allocating the necessary
375 * structures for polling. (On Linux, you will likely have reached
376 * the maximum number of file descriptors.) The suggested way to handle
377 * these cases is to ignore the @cancellable.
379 * You are not supposed to read from the fd yourself, just check for
380 * readable status. Reading to unset the readable status is done
381 * with g_cancellable_reset().
383 * Returns: %TRUE if @pollfd was successfully initialized, %FALSE on
384 * failure to prepare the cancellable.
389 g_cancellable_make_pollfd (GCancellable *cancellable, GPollFD *pollfd)
391 g_return_val_if_fail (pollfd != NULL, FALSE);
392 if (cancellable == NULL)
394 g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), FALSE);
398 cancellable->priv->fd_refcount++;
400 if (cancellable->priv->wakeup == NULL)
402 cancellable->priv->wakeup = g_wakeup_new ();
404 if (cancellable->priv->cancelled)
405 g_wakeup_signal (cancellable->priv->wakeup);
408 g_wakeup_get_pollfd (cancellable->priv->wakeup, pollfd);
410 G_UNLOCK(cancellable);
416 * g_cancellable_release_fd:
417 * @cancellable: a #GCancellable
419 * Releases a resources previously allocated by g_cancellable_get_fd()
420 * or g_cancellable_make_pollfd().
422 * For compatibility reasons with older releases, calling this function
423 * is not strictly required, the resources will be automatically freed
424 * when the @cancellable is finalized. However, the @cancellable will
425 * block scarce file descriptors until it is finalized if this function
426 * is not called. This can cause the application to run out of file
427 * descriptors when many #GCancellables are used at the same time.
432 g_cancellable_release_fd (GCancellable *cancellable)
434 GCancellablePrivate *priv;
436 if (cancellable == NULL)
439 g_return_if_fail (G_IS_CANCELLABLE (cancellable));
440 g_return_if_fail (cancellable->priv->fd_refcount > 0);
442 priv = cancellable->priv;
444 G_LOCK (cancellable);
446 if (priv->fd_refcount == 0)
448 g_wakeup_free (priv->wakeup);
451 G_UNLOCK (cancellable);
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;
487 G_UNLOCK (cancellable);
491 priv->cancelled = TRUE;
492 priv->cancelled_running = TRUE;
495 g_wakeup_signal (priv->wakeup);
497 G_UNLOCK(cancellable);
499 g_object_ref (cancellable);
500 g_signal_emit (cancellable, signals[CANCELLED], 0);
504 priv->cancelled_running = FALSE;
505 if (priv->cancelled_running_waiting)
506 g_cond_broadcast (cancellable_cond);
507 priv->cancelled_running_waiting = FALSE;
509 G_UNLOCK(cancellable);
511 g_object_unref (cancellable);
515 * g_cancellable_connect:
516 * @cancellable: A #GCancellable.
517 * @callback: The #GCallback to connect.
518 * @data: Data to pass to @callback.
519 * @data_destroy_func: Free function for @data or %NULL.
521 * Convenience function to connect to the #GCancellable::cancelled
522 * signal. Also handles the race condition that may happen
523 * if the cancellable is cancelled right before connecting.
525 * @callback is called at most once, either directly at the
526 * time of the connect if @cancellable is already cancelled,
527 * or when @cancellable is cancelled in some thread.
529 * @data_destroy_func will be called when the handler is
530 * disconnected, or immediately if the cancellable is already
533 * See #GCancellable::cancelled for details on how to use this.
535 * Returns: The id of the signal handler or 0 if @cancellable has already
541 g_cancellable_connect (GCancellable *cancellable,
544 GDestroyNotify data_destroy_func)
548 g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), 0);
550 G_LOCK (cancellable);
552 if (cancellable->priv->cancelled)
554 void (*_callback) (GCancellable *cancellable,
557 _callback = (void *)callback;
560 _callback (cancellable, data);
562 if (data_destroy_func)
563 data_destroy_func (data);
567 id = g_signal_connect_data (cancellable, "cancelled",
569 (GClosureNotify) data_destroy_func,
572 G_UNLOCK (cancellable);
578 * g_cancellable_disconnect:
579 * @cancellable: A #GCancellable or %NULL.
580 * @handler_id: Handler id of the handler to be disconnected, or %0.
582 * Disconnects a handler from a cancellable instance similar to
583 * g_signal_handler_disconnect(). Additionally, in the event that a
584 * signal handler is currently running, this call will block until the
585 * handler has finished. Calling this function from a
586 * #GCancellable::cancelled signal handler will therefore result in a
589 * This avoids a race condition where a thread cancels at the
590 * same time as the cancellable operation is finished and the
591 * signal handler is removed. See #GCancellable::cancelled for
592 * details on how to use this.
594 * If @cancellable is %NULL or @handler_id is %0 this function does
600 g_cancellable_disconnect (GCancellable *cancellable,
603 GCancellablePrivate *priv;
605 if (handler_id == 0 || cancellable == NULL)
608 G_LOCK (cancellable);
610 priv = cancellable->priv;
612 while (priv->cancelled_running)
614 priv->cancelled_running_waiting = TRUE;
615 g_cond_wait (cancellable_cond,
616 g_static_mutex_get_mutex (& G_LOCK_NAME (cancellable)));
619 g_signal_handler_disconnect (cancellable, handler_id);
620 G_UNLOCK (cancellable);
626 GCancellable *cancellable;
628 } GCancellableSource;
631 cancellable_source_prepare (GSource *source,
634 GCancellableSource *cancellable_source = (GCancellableSource *)source;
637 return g_cancellable_is_cancelled (cancellable_source->cancellable);
641 cancellable_source_check (GSource *source)
643 GCancellableSource *cancellable_source = (GCancellableSource *)source;
645 return g_cancellable_is_cancelled (cancellable_source->cancellable);
649 cancellable_source_dispatch (GSource *source,
650 GSourceFunc callback,
653 GCancellableSourceFunc func = (GCancellableSourceFunc)callback;
654 GCancellableSource *cancellable_source = (GCancellableSource *)source;
656 return (*func) (cancellable_source->cancellable, user_data);
660 cancellable_source_finalize (GSource *source)
662 GCancellableSource *cancellable_source = (GCancellableSource *)source;
664 if (cancellable_source->cancellable)
665 g_object_unref (cancellable_source->cancellable);
669 cancellable_source_closure_callback (GCancellable *cancellable,
672 GClosure *closure = data;
674 GValue params = { 0, };
675 GValue result_value = { 0, };
678 g_value_init (&result_value, G_TYPE_BOOLEAN);
680 g_value_init (¶ms, G_TYPE_CANCELLABLE);
681 g_value_set_object (¶ms, cancellable);
683 g_closure_invoke (closure, &result_value, 1, ¶ms, NULL);
685 result = g_value_get_boolean (&result_value);
686 g_value_unset (&result_value);
687 g_value_unset (¶ms);
692 static GSourceFuncs cancellable_source_funcs =
694 cancellable_source_prepare,
695 cancellable_source_check,
696 cancellable_source_dispatch,
697 cancellable_source_finalize,
698 (GSourceFunc)cancellable_source_closure_callback,
699 (GSourceDummyMarshal)g_cclosure_marshal_generic,
703 * g_cancellable_source_new: (skip)
704 * @cancellable: a #GCancellable, or %NULL
706 * Creates a source that triggers if @cancellable is cancelled and
707 * calls its callback of type #GCancellableSourceFunc. This is
708 * primarily useful for attaching to another (non-cancellable) source
709 * with g_source_add_child_source() to add cancellability to it.
711 * For convenience, you can call this with a %NULL #GCancellable,
712 * in which case the source will never trigger.
714 * Return value: (transfer full): the new #GSource.
719 g_cancellable_source_new (GCancellable *cancellable)
722 GCancellableSource *cancellable_source;
724 source = g_source_new (&cancellable_source_funcs, sizeof (GCancellableSource));
725 g_source_set_name (source, "GCancellable");
726 cancellable_source = (GCancellableSource *)source;
728 if (g_cancellable_make_pollfd (cancellable,
729 &cancellable_source->pollfd))
731 cancellable_source->cancellable = g_object_ref (cancellable);
732 g_source_add_poll (source, &cancellable_source->pollfd);