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-unix.h"
33 #include "gcancellable.h"
34 #include "gio-marshal.h"
39 * SECTION:gcancellable
40 * @short_description: Thread-safe Operation Cancellation Stack
43 * GCancellable is a thread-safe operation cancellation stack used
44 * throughout GIO to allow for cancellation of synchronous and
45 * asynchronous operations.
53 struct _GCancellablePrivate
56 guint cancelled_running : 1;
57 guint cancelled_running_waiting : 1;
67 static guint signals[LAST_SIGNAL] = { 0 };
69 G_DEFINE_TYPE (GCancellable, g_cancellable, G_TYPE_OBJECT);
71 static GStaticPrivate current_cancellable = G_STATIC_PRIVATE_INIT;
72 G_LOCK_DEFINE_STATIC(cancellable);
73 static GCond *cancellable_cond = NULL;
76 g_cancellable_close_pipe (GCancellable *cancellable)
78 GCancellablePrivate *priv;
80 priv = cancellable->priv;
82 if (priv->cancel_pipe[0] != -1)
84 close (priv->cancel_pipe[0]);
85 priv->cancel_pipe[0] = -1;
88 if (priv->cancel_pipe[1] != -1)
90 close (priv->cancel_pipe[1]);
91 priv->cancel_pipe[1] = -1;
97 CloseHandle (priv->event);
104 g_cancellable_finalize (GObject *object)
106 GCancellable *cancellable = G_CANCELLABLE (object);
108 g_cancellable_close_pipe (cancellable);
110 G_OBJECT_CLASS (g_cancellable_parent_class)->finalize (object);
114 g_cancellable_class_init (GCancellableClass *klass)
116 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
118 g_type_class_add_private (klass, sizeof (GCancellablePrivate));
120 if (cancellable_cond == NULL && g_thread_supported ())
121 cancellable_cond = g_cond_new ();
123 gobject_class->finalize = g_cancellable_finalize;
126 * GCancellable::cancelled:
127 * @cancellable: a #GCancellable.
129 * Emitted when the operation has been cancelled.
131 * Can be used by implementations of cancellable operations. If the
132 * operation is cancelled from another thread, the signal will be
133 * emitted in the thread that cancelled the operation, not the
134 * thread that is running the operation.
136 * Note that disconnecting from this signal (or any signal) in a
137 * multi-threaded program is prone to race conditions. For instance
138 * it is possible that a signal handler may be invoked even
139 * <emphasis>after</emphasis> a call to
140 * g_signal_handler_disconnect() for that handler has already
143 * There is also a problem when cancellation happen
144 * right before connecting to the signal. If this happens the
145 * signal will unexpectedly not be emitted, and checking before
146 * connecting to the signal leaves a race condition where this is
149 * In order to make it safe and easy to connect handlers there
150 * are two helper functions: g_cancellable_connect() and
151 * g_cancellable_disconnect() which protect against problems
154 * An example of how to us this:
156 * /<!-- -->* Make sure we don't do any unnecessary work if already cancelled *<!-- -->/
157 * if (g_cancellable_set_error_if_cancelled (cancellable))
160 * /<!-- -->* Set up all the data needed to be able to
161 * * handle cancellation of the operation *<!-- -->/
162 * my_data = my_data_new (...);
166 * id = g_cancellable_connect (cancellable,
167 * G_CALLBACK (cancelled_handler)
170 * /<!-- -->* cancellable operation here... *<!-- -->/
172 * g_cancellable_disconnect (cancellable, id);
174 * /<!-- -->* cancelled_handler is never called after this, it
175 * * is now safe to free the data *<!-- -->/
176 * my_data_free (my_data);
179 * Note that the cancelled signal is emitted in the thread that
180 * the user cancelled from, which may be the main thread. So, the
181 * cancellable signal should not do something that can block.
184 g_signal_new (I_("cancelled"),
185 G_TYPE_FROM_CLASS (gobject_class),
187 G_STRUCT_OFFSET (GCancellableClass, cancelled),
189 g_cclosure_marshal_VOID__VOID,
197 g_cancellable_open_pipe (GCancellable *cancellable)
199 GCancellablePrivate *priv;
201 priv = cancellable->priv;
202 if (g_unix_pipe_flags (priv->cancel_pipe, FD_CLOEXEC, NULL))
204 /* Make them nonblocking, just to be sure we don't block
205 * on errors and stuff
207 g_unix_set_fd_nonblocking (priv->cancel_pipe[0], TRUE, NULL);
208 g_unix_set_fd_nonblocking (priv->cancel_pipe[1], TRUE, NULL);
216 c = write (priv->cancel_pipe[1], &ch, 1);
217 while (c == -1 && errno == EINTR);
224 g_cancellable_init (GCancellable *cancellable)
226 cancellable->priv = G_TYPE_INSTANCE_GET_PRIVATE (cancellable,
228 GCancellablePrivate);
229 cancellable->priv->cancel_pipe[0] = -1;
230 cancellable->priv->cancel_pipe[1] = -1;
236 * Creates a new #GCancellable object.
238 * Applications that want to start one or more operations
239 * that should be cancellable should create a #GCancellable
240 * and pass it to the operations.
242 * One #GCancellable can be used in multiple consecutive
243 * operations, but not in multiple concurrent operations.
245 * Returns: a #GCancellable.
248 g_cancellable_new (void)
250 return g_object_new (G_TYPE_CANCELLABLE, NULL);
254 * g_cancellable_push_current:
255 * @cancellable: a #GCancellable object
257 * Pushes @cancellable onto the cancellable stack. The current
258 * cancellable can then be recieved using g_cancellable_get_current().
260 * This is useful when implementing cancellable operations in
261 * code that does not allow you to pass down the cancellable object.
263 * This is typically called automatically by e.g. #GFile operations,
264 * so you rarely have to call this yourself.
267 g_cancellable_push_current (GCancellable *cancellable)
271 g_return_if_fail (cancellable != NULL);
273 l = g_static_private_get (¤t_cancellable);
274 l = g_slist_prepend (l, cancellable);
275 g_static_private_set (¤t_cancellable, l, NULL);
279 * g_cancellable_pop_current:
280 * @cancellable: a #GCancellable object
282 * Pops @cancellable off the cancellable stack (verifying that @cancellable
283 * is on the top of the stack).
286 g_cancellable_pop_current (GCancellable *cancellable)
290 l = g_static_private_get (¤t_cancellable);
292 g_return_if_fail (l != NULL);
293 g_return_if_fail (l->data == cancellable);
295 l = g_slist_delete_link (l, l);
296 g_static_private_set (¤t_cancellable, l, NULL);
300 * g_cancellable_get_current:
302 * Gets the top cancellable from the stack.
304 * Returns: (transfer none): a #GCancellable from the top of the stack, or %NULL
305 * if the stack is empty.
308 g_cancellable_get_current (void)
312 l = g_static_private_get (¤t_cancellable);
316 return G_CANCELLABLE (l->data);
320 * g_cancellable_reset:
321 * @cancellable: a #GCancellable object.
323 * Resets @cancellable to its uncancelled state.
326 g_cancellable_reset (GCancellable *cancellable)
328 GCancellablePrivate *priv;
330 g_return_if_fail (G_IS_CANCELLABLE (cancellable));
334 priv = cancellable->priv;
336 while (priv->cancelled_running)
338 priv->cancelled_running_waiting = TRUE;
339 g_cond_wait (cancellable_cond,
340 g_static_mutex_get_mutex (& G_LOCK_NAME (cancellable)));
345 /* Make sure we're not leaving old cancel state around */
349 ResetEvent (priv->event);
351 if (priv->cancel_pipe[0] != -1)
357 c = read (priv->cancel_pipe[0], &ch, 1);
358 while (c == -1 && errno == EINTR);
361 priv->cancelled = FALSE;
363 G_UNLOCK(cancellable);
367 * g_cancellable_is_cancelled:
368 * @cancellable: a #GCancellable or NULL.
370 * Checks if a cancellable job has been cancelled.
372 * Returns: %TRUE if @cancellable is cancelled,
373 * FALSE if called with %NULL or if item is not cancelled.
376 g_cancellable_is_cancelled (GCancellable *cancellable)
378 return cancellable != NULL && cancellable->priv->cancelled;
382 * g_cancellable_set_error_if_cancelled:
383 * @cancellable: a #GCancellable object.
384 * @error: #GError to append error state to.
386 * If the @cancellable is cancelled, sets the error to notify
387 * that the operation was cancelled.
389 * Returns: %TRUE if @cancellable was cancelled, %FALSE if it was not.
392 g_cancellable_set_error_if_cancelled (GCancellable *cancellable,
395 if (g_cancellable_is_cancelled (cancellable))
397 g_set_error_literal (error,
399 G_IO_ERROR_CANCELLED,
400 _("Operation was cancelled"));
408 * g_cancellable_get_fd:
409 * @cancellable: a #GCancellable.
411 * Gets the file descriptor for a cancellable job. This can be used to
412 * implement cancellable operations on Unix systems. The returned fd will
413 * turn readable when @cancellable is cancelled.
415 * You are not supposed to read from the fd yourself, just check for
416 * readable status. Reading to unset the readable status is done
417 * with g_cancellable_reset().
419 * After a successful return from this function, you should use
420 * g_cancellable_release_fd() to free up resources allocated for
421 * the returned file descriptor.
423 * See also g_cancellable_make_pollfd().
425 * Returns: A valid file descriptor. %-1 if the file descriptor
426 * is not supported, or on errors.
429 g_cancellable_get_fd (GCancellable *cancellable)
431 GCancellablePrivate *priv;
434 if (cancellable == NULL)
437 priv = cancellable->priv;
443 if (priv->cancel_pipe[0] == -1)
444 g_cancellable_open_pipe (cancellable);
445 fd = priv->cancel_pipe[0];
448 G_UNLOCK(cancellable);
455 * g_cancellable_make_pollfd:
456 * @cancellable: a #GCancellable or %NULL
457 * @pollfd: a pointer to a #GPollFD
459 * Creates a #GPollFD corresponding to @cancellable; this can be passed
460 * to g_poll() and used to poll for cancellation. This is useful both
461 * for unix systems without a native poll and for portability to
464 * When this function returns %TRUE, you should use
465 * g_cancellable_release_fd() to free up resources allocated for the
466 * @pollfd. After a %FALSE return, do not call g_cancellable_release_fd().
468 * If this function returns %FALSE, either no @cancellable was given or
469 * resource limits prevent this function from allocating the necessary
470 * structures for polling. (On Linux, you will likely have reached
471 * the maximum number of file descriptors.) The suggested way to handle
472 * these cases is to ignore the @cancellable.
474 * You are not supposed to read from the fd yourself, just check for
475 * readable status. Reading to unset the readable status is done
476 * with g_cancellable_reset().
478 * Returns: %TRUE if @pollfd was successfully initialized, %FALSE on
479 * failure to prepare the cancellable.
484 g_cancellable_make_pollfd (GCancellable *cancellable, GPollFD *pollfd)
486 g_return_val_if_fail (pollfd != NULL, FALSE);
487 if (cancellable == NULL)
489 g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), FALSE);
493 GCancellablePrivate *priv;
495 priv = cancellable->priv;
497 if (priv->event == NULL)
499 /* A manual reset anonymous event, starting unset */
500 priv->event = CreateEvent (NULL, TRUE, FALSE, NULL);
501 if (priv->event == NULL)
503 G_UNLOCK(cancellable);
507 SetEvent(priv->event);
510 G_UNLOCK(cancellable);
512 pollfd->fd = (gintptr)priv->event;
513 #else /* !G_OS_WIN32 */
514 int fd = g_cancellable_get_fd (cancellable);
519 #endif /* G_OS_WIN32 */
522 pollfd->events = G_IO_IN;
529 * g_cancellable_release_fd:
530 * @cancellable: a #GCancellable
532 * Releases a resources previously allocated by g_cancellable_get_fd()
533 * or g_cancellable_make_pollfd().
535 * For compatibility reasons with older releases, calling this function
536 * is not strictly required, the resources will be automatically freed
537 * when the @cancellable is finalized. However, the @cancellable will
538 * block scarce file descriptors until it is finalized if this function
539 * is not called. This can cause the application to run out of file
540 * descriptors when many #GCancellables are used at the same time.
545 g_cancellable_release_fd (GCancellable *cancellable)
547 GCancellablePrivate *priv;
549 if (cancellable == NULL)
552 g_return_if_fail (G_IS_CANCELLABLE (cancellable));
553 g_return_if_fail (cancellable->priv->fd_refcount > 0);
555 priv = cancellable->priv;
557 G_LOCK (cancellable);
559 if (priv->fd_refcount == 0)
560 g_cancellable_close_pipe (cancellable);
561 G_UNLOCK (cancellable);
565 * g_cancellable_cancel:
566 * @cancellable: a #GCancellable object.
568 * Will set @cancellable to cancelled, and will emit the
569 * #GCancellable::cancelled signal. (However, see the warning about
570 * race conditions in the documentation for that signal if you are
571 * planning to connect to it.)
573 * This function is thread-safe. In other words, you can safely call
574 * it from a thread other than the one running the operation that was
575 * passed the @cancellable.
577 * The convention within gio is that cancelling an asynchronous
578 * operation causes it to complete asynchronously. That is, if you
579 * cancel the operation from the same thread in which it is running,
580 * then the operation's #GAsyncReadyCallback will not be invoked until
581 * the application returns to the main loop.
584 g_cancellable_cancel (GCancellable *cancellable)
586 GCancellablePrivate *priv;
588 if (cancellable == NULL ||
589 cancellable->priv->cancelled)
592 priv = cancellable->priv;
597 G_UNLOCK (cancellable);
601 priv->cancelled = TRUE;
602 priv->cancelled_running = TRUE;
605 SetEvent (priv->event);
607 if (priv->cancel_pipe[1] != -1)
613 c = write (priv->cancel_pipe[1], &ch, 1);
614 while (c == -1 && errno == EINTR);
616 G_UNLOCK(cancellable);
618 g_object_ref (cancellable);
619 g_signal_emit (cancellable, signals[CANCELLED], 0);
623 priv->cancelled_running = FALSE;
624 if (priv->cancelled_running_waiting)
625 g_cond_broadcast (cancellable_cond);
626 priv->cancelled_running_waiting = FALSE;
628 G_UNLOCK(cancellable);
630 g_object_unref (cancellable);
634 * g_cancellable_connect:
635 * @cancellable: A #GCancellable.
636 * @callback: The #GCallback to connect.
637 * @data: Data to pass to @callback.
638 * @data_destroy_func: Free function for @data or %NULL.
640 * Convenience function to connect to the #GCancellable::cancelled
641 * signal. Also handles the race condition that may happen
642 * if the cancellable is cancelled right before connecting.
644 * @callback is called at most once, either directly at the
645 * time of the connect if @cancellable is already cancelled,
646 * or when @cancellable is cancelled in some thread.
648 * @data_destroy_func will be called when the handler is
649 * disconnected, or immediately if the cancellable is already
652 * See #GCancellable::cancelled for details on how to use this.
654 * Returns: The id of the signal handler or 0 if @cancellable has already
660 g_cancellable_connect (GCancellable *cancellable,
663 GDestroyNotify data_destroy_func)
667 g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), 0);
669 G_LOCK (cancellable);
671 if (cancellable->priv->cancelled)
673 void (*_callback) (GCancellable *cancellable,
676 _callback = (void *)callback;
679 _callback (cancellable, data);
681 if (data_destroy_func)
682 data_destroy_func (data);
686 id = g_signal_connect_data (cancellable, "cancelled",
688 (GClosureNotify) data_destroy_func,
691 G_UNLOCK (cancellable);
697 * g_cancellable_disconnect:
698 * @cancellable: A #GCancellable or %NULL.
699 * @handler_id: Handler id of the handler to be disconnected, or %0.
701 * Disconnects a handler from a cancellable instance similar to
702 * g_signal_handler_disconnect(). Additionally, in the event that a
703 * signal handler is currently running, this call will block until the
704 * handler has finished. Calling this function from a
705 * #GCancellable::cancelled signal handler will therefore result in a
708 * This avoids a race condition where a thread cancels at the
709 * same time as the cancellable operation is finished and the
710 * signal handler is removed. See #GCancellable::cancelled for
711 * details on how to use this.
713 * If @cancellable is %NULL or @handler_id is %0 this function does
719 g_cancellable_disconnect (GCancellable *cancellable,
722 GCancellablePrivate *priv;
724 if (handler_id == 0 || cancellable == NULL)
727 G_LOCK (cancellable);
729 priv = cancellable->priv;
731 while (priv->cancelled_running)
733 priv->cancelled_running_waiting = TRUE;
734 g_cond_wait (cancellable_cond,
735 g_static_mutex_get_mutex (& G_LOCK_NAME (cancellable)));
738 g_signal_handler_disconnect (cancellable, handler_id);
739 G_UNLOCK (cancellable);
745 GCancellable *cancellable;
747 } GCancellableSource;
750 cancellable_source_prepare (GSource *source,
753 GCancellableSource *cancellable_source = (GCancellableSource *)source;
756 return g_cancellable_is_cancelled (cancellable_source->cancellable);
760 cancellable_source_check (GSource *source)
762 GCancellableSource *cancellable_source = (GCancellableSource *)source;
764 return g_cancellable_is_cancelled (cancellable_source->cancellable);
768 cancellable_source_dispatch (GSource *source,
769 GSourceFunc callback,
772 GCancellableSourceFunc func = (GCancellableSourceFunc)callback;
773 GCancellableSource *cancellable_source = (GCancellableSource *)source;
775 return (*func) (cancellable_source->cancellable, user_data);
779 cancellable_source_finalize (GSource *source)
781 GCancellableSource *cancellable_source = (GCancellableSource *)source;
783 if (cancellable_source->cancellable)
784 g_object_unref (cancellable_source->cancellable);
788 cancellable_source_closure_callback (GCancellable *cancellable,
791 GClosure *closure = data;
793 GValue params = { 0, };
794 GValue result_value = { 0, };
797 g_value_init (&result_value, G_TYPE_BOOLEAN);
799 g_value_init (¶ms, G_TYPE_CANCELLABLE);
800 g_value_set_object (¶ms, cancellable);
802 g_closure_invoke (closure, &result_value, 1, ¶ms, NULL);
804 result = g_value_get_boolean (&result_value);
805 g_value_unset (&result_value);
806 g_value_unset (¶ms);
811 static GSourceFuncs cancellable_source_funcs =
813 cancellable_source_prepare,
814 cancellable_source_check,
815 cancellable_source_dispatch,
816 cancellable_source_finalize,
817 (GSourceFunc)cancellable_source_closure_callback,
818 (GSourceDummyMarshal)_gio_marshal_BOOLEAN__VOID,
822 * g_cancellable_source_new: (skip)
823 * @cancellable: a #GCancellable, or %NULL
825 * Creates a source that triggers if @cancellable is cancelled and
826 * calls its callback of type #GCancellableSourceFunc. This is
827 * primarily useful for attaching to another (non-cancellable) source
828 * with g_source_add_child_source() to add cancellability to it.
830 * For convenience, you can call this with a %NULL #GCancellable,
831 * in which case the source will never trigger.
833 * Return value: (transfer full): the new #GSource.
838 g_cancellable_source_new (GCancellable *cancellable)
841 GCancellableSource *cancellable_source;
843 source = g_source_new (&cancellable_source_funcs, sizeof (GCancellableSource));
844 g_source_set_name (source, "GCancellable");
845 cancellable_source = (GCancellableSource *)source;
847 if (g_cancellable_make_pollfd (cancellable,
848 &cancellable_source->pollfd))
850 cancellable_source->cancellable = g_object_ref (cancellable);
851 g_source_add_poll (source, &cancellable_source->pollfd);