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 set_fd_close_exec (int fd)
201 flags = fcntl (fd, F_GETFD, 0);
202 if (flags != -1 && (flags & FD_CLOEXEC) == 0)
205 fcntl (fd, F_SETFD, flags);
211 g_cancellable_open_pipe (GCancellable *cancellable)
213 GCancellablePrivate *priv;
215 priv = cancellable->priv;
216 if (pipe (priv->cancel_pipe) == 0)
218 /* Make them nonblocking, just to be sure we don't block
219 * on errors and stuff
221 g_unix_set_fd_nonblocking (priv->cancel_pipe[0], TRUE, NULL);
222 g_unix_set_fd_nonblocking (priv->cancel_pipe[1], TRUE, NULL);
223 set_fd_close_exec (priv->cancel_pipe[0]);
224 set_fd_close_exec (priv->cancel_pipe[1]);
232 c = write (priv->cancel_pipe[1], &ch, 1);
233 while (c == -1 && errno == EINTR);
240 g_cancellable_init (GCancellable *cancellable)
242 cancellable->priv = G_TYPE_INSTANCE_GET_PRIVATE (cancellable,
244 GCancellablePrivate);
245 cancellable->priv->cancel_pipe[0] = -1;
246 cancellable->priv->cancel_pipe[1] = -1;
252 * Creates a new #GCancellable object.
254 * Applications that want to start one or more operations
255 * that should be cancellable should create a #GCancellable
256 * and pass it to the operations.
258 * One #GCancellable can be used in multiple consecutive
259 * operations, but not in multiple concurrent operations.
261 * Returns: a #GCancellable.
264 g_cancellable_new (void)
266 return g_object_new (G_TYPE_CANCELLABLE, NULL);
270 * g_cancellable_push_current:
271 * @cancellable: a #GCancellable object
273 * Pushes @cancellable onto the cancellable stack. The current
274 * cancellable can then be recieved using g_cancellable_get_current().
276 * This is useful when implementing cancellable operations in
277 * code that does not allow you to pass down the cancellable object.
279 * This is typically called automatically by e.g. #GFile operations,
280 * so you rarely have to call this yourself.
283 g_cancellable_push_current (GCancellable *cancellable)
287 g_return_if_fail (cancellable != NULL);
289 l = g_static_private_get (¤t_cancellable);
290 l = g_slist_prepend (l, cancellable);
291 g_static_private_set (¤t_cancellable, l, NULL);
295 * g_cancellable_pop_current:
296 * @cancellable: a #GCancellable object
298 * Pops @cancellable off the cancellable stack (verifying that @cancellable
299 * is on the top of the stack).
302 g_cancellable_pop_current (GCancellable *cancellable)
306 l = g_static_private_get (¤t_cancellable);
308 g_return_if_fail (l != NULL);
309 g_return_if_fail (l->data == cancellable);
311 l = g_slist_delete_link (l, l);
312 g_static_private_set (¤t_cancellable, l, NULL);
316 * g_cancellable_get_current:
318 * Gets the top cancellable from the stack.
320 * Returns: (transfer none): a #GCancellable from the top of the stack, or %NULL
321 * if the stack is empty.
324 g_cancellable_get_current (void)
328 l = g_static_private_get (¤t_cancellable);
332 return G_CANCELLABLE (l->data);
336 * g_cancellable_reset:
337 * @cancellable: a #GCancellable object.
339 * Resets @cancellable to its uncancelled state.
342 g_cancellable_reset (GCancellable *cancellable)
344 GCancellablePrivate *priv;
346 g_return_if_fail (G_IS_CANCELLABLE (cancellable));
350 priv = cancellable->priv;
352 while (priv->cancelled_running)
354 priv->cancelled_running_waiting = TRUE;
355 g_cond_wait (cancellable_cond,
356 g_static_mutex_get_mutex (& G_LOCK_NAME (cancellable)));
361 /* Make sure we're not leaving old cancel state around */
365 ResetEvent (priv->event);
367 if (priv->cancel_pipe[0] != -1)
373 c = read (priv->cancel_pipe[0], &ch, 1);
374 while (c == -1 && errno == EINTR);
377 priv->cancelled = FALSE;
379 G_UNLOCK(cancellable);
383 * g_cancellable_is_cancelled:
384 * @cancellable: a #GCancellable or NULL.
386 * Checks if a cancellable job has been cancelled.
388 * Returns: %TRUE if @cancellable is cancelled,
389 * FALSE if called with %NULL or if item is not cancelled.
392 g_cancellable_is_cancelled (GCancellable *cancellable)
394 return cancellable != NULL && cancellable->priv->cancelled;
398 * g_cancellable_set_error_if_cancelled:
399 * @cancellable: a #GCancellable object.
400 * @error: #GError to append error state to.
402 * If the @cancellable is cancelled, sets the error to notify
403 * that the operation was cancelled.
405 * Returns: %TRUE if @cancellable was cancelled, %FALSE if it was not.
408 g_cancellable_set_error_if_cancelled (GCancellable *cancellable,
411 if (g_cancellable_is_cancelled (cancellable))
413 g_set_error_literal (error,
415 G_IO_ERROR_CANCELLED,
416 _("Operation was cancelled"));
424 * g_cancellable_get_fd:
425 * @cancellable: a #GCancellable.
427 * Gets the file descriptor for a cancellable job. This can be used to
428 * implement cancellable operations on Unix systems. The returned fd will
429 * turn readable when @cancellable is cancelled.
431 * You are not supposed to read from the fd yourself, just check for
432 * readable status. Reading to unset the readable status is done
433 * with g_cancellable_reset().
435 * After a successful return from this function, you should use
436 * g_cancellable_release_fd() to free up resources allocated for
437 * the returned file descriptor.
439 * See also g_cancellable_make_pollfd().
441 * Returns: A valid file descriptor. %-1 if the file descriptor
442 * is not supported, or on errors.
445 g_cancellable_get_fd (GCancellable *cancellable)
447 GCancellablePrivate *priv;
450 if (cancellable == NULL)
453 priv = cancellable->priv;
459 if (priv->cancel_pipe[0] == -1)
460 g_cancellable_open_pipe (cancellable);
461 fd = priv->cancel_pipe[0];
464 G_UNLOCK(cancellable);
471 * g_cancellable_make_pollfd:
472 * @cancellable: a #GCancellable or %NULL
473 * @pollfd: a pointer to a #GPollFD
475 * Creates a #GPollFD corresponding to @cancellable; this can be passed
476 * to g_poll() and used to poll for cancellation. This is useful both
477 * for unix systems without a native poll and for portability to
480 * When this function returns %TRUE, you should use
481 * g_cancellable_release_fd() to free up resources allocated for the
482 * @pollfd. After a %FALSE return, do not call g_cancellable_release_fd().
484 * If this function returns %FALSE, either no @cancellable was given or
485 * resource limits prevent this function from allocating the necessary
486 * structures for polling. (On Linux, you will likely have reached
487 * the maximum number of file descriptors.) The suggested way to handle
488 * these cases is to ignore the @cancellable.
490 * You are not supposed to read from the fd yourself, just check for
491 * readable status. Reading to unset the readable status is done
492 * with g_cancellable_reset().
494 * Returns: %TRUE if @pollfd was successfully initialized, %FALSE on
495 * failure to prepare the cancellable.
500 g_cancellable_make_pollfd (GCancellable *cancellable, GPollFD *pollfd)
502 g_return_val_if_fail (pollfd != NULL, FALSE);
503 if (cancellable == NULL)
505 g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), FALSE);
509 GCancellablePrivate *priv;
511 priv = cancellable->priv;
513 if (priv->event == NULL)
515 /* A manual reset anonymous event, starting unset */
516 priv->event = CreateEvent (NULL, TRUE, FALSE, NULL);
517 if (priv->event == NULL)
519 G_UNLOCK(cancellable);
523 SetEvent(priv->event);
526 G_UNLOCK(cancellable);
528 pollfd->fd = (gintptr)priv->event;
529 #else /* !G_OS_WIN32 */
530 int fd = g_cancellable_get_fd (cancellable);
535 #endif /* G_OS_WIN32 */
538 pollfd->events = G_IO_IN;
545 * g_cancellable_release_fd:
546 * @cancellable: a #GCancellable
548 * Releases a resources previously allocated by g_cancellable_get_fd()
549 * or g_cancellable_make_pollfd().
551 * For compatibility reasons with older releases, calling this function
552 * is not strictly required, the resources will be automatically freed
553 * when the @cancellable is finalized. However, the @cancellable will
554 * block scarce file descriptors until it is finalized if this function
555 * is not called. This can cause the application to run out of file
556 * descriptors when many #GCancellables are used at the same time.
561 g_cancellable_release_fd (GCancellable *cancellable)
563 GCancellablePrivate *priv;
565 if (cancellable == NULL)
568 g_return_if_fail (G_IS_CANCELLABLE (cancellable));
569 g_return_if_fail (cancellable->priv->fd_refcount > 0);
571 priv = cancellable->priv;
573 G_LOCK (cancellable);
575 if (priv->fd_refcount == 0)
576 g_cancellable_close_pipe (cancellable);
577 G_UNLOCK (cancellable);
581 * g_cancellable_cancel:
582 * @cancellable: a #GCancellable object.
584 * Will set @cancellable to cancelled, and will emit the
585 * #GCancellable::cancelled signal. (However, see the warning about
586 * race conditions in the documentation for that signal if you are
587 * planning to connect to it.)
589 * This function is thread-safe. In other words, you can safely call
590 * it from a thread other than the one running the operation that was
591 * passed the @cancellable.
593 * The convention within gio is that cancelling an asynchronous
594 * operation causes it to complete asynchronously. That is, if you
595 * cancel the operation from the same thread in which it is running,
596 * then the operation's #GAsyncReadyCallback will not be invoked until
597 * the application returns to the main loop.
600 g_cancellable_cancel (GCancellable *cancellable)
602 GCancellablePrivate *priv;
604 if (cancellable == NULL ||
605 cancellable->priv->cancelled)
608 priv = cancellable->priv;
613 G_UNLOCK (cancellable);
617 priv->cancelled = TRUE;
618 priv->cancelled_running = TRUE;
621 SetEvent (priv->event);
623 if (priv->cancel_pipe[1] != -1)
629 c = write (priv->cancel_pipe[1], &ch, 1);
630 while (c == -1 && errno == EINTR);
632 G_UNLOCK(cancellable);
634 g_object_ref (cancellable);
635 g_signal_emit (cancellable, signals[CANCELLED], 0);
639 priv->cancelled_running = FALSE;
640 if (priv->cancelled_running_waiting)
641 g_cond_broadcast (cancellable_cond);
642 priv->cancelled_running_waiting = FALSE;
644 G_UNLOCK(cancellable);
646 g_object_unref (cancellable);
650 * g_cancellable_connect:
651 * @cancellable: A #GCancellable.
652 * @callback: The #GCallback to connect.
653 * @data: Data to pass to @callback.
654 * @data_destroy_func: Free function for @data or %NULL.
656 * Convenience function to connect to the #GCancellable::cancelled
657 * signal. Also handles the race condition that may happen
658 * if the cancellable is cancelled right before connecting.
660 * @callback is called at most once, either directly at the
661 * time of the connect if @cancellable is already cancelled,
662 * or when @cancellable is cancelled in some thread.
664 * @data_destroy_func will be called when the handler is
665 * disconnected, or immediately if the cancellable is already
668 * See #GCancellable::cancelled for details on how to use this.
670 * Returns: The id of the signal handler or 0 if @cancellable has already
676 g_cancellable_connect (GCancellable *cancellable,
679 GDestroyNotify data_destroy_func)
683 g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), 0);
685 G_LOCK (cancellable);
687 if (cancellable->priv->cancelled)
689 void (*_callback) (GCancellable *cancellable,
692 _callback = (void *)callback;
695 _callback (cancellable, data);
697 if (data_destroy_func)
698 data_destroy_func (data);
702 id = g_signal_connect_data (cancellable, "cancelled",
704 (GClosureNotify) data_destroy_func,
707 G_UNLOCK (cancellable);
713 * g_cancellable_disconnect:
714 * @cancellable: A #GCancellable or %NULL.
715 * @handler_id: Handler id of the handler to be disconnected, or %0.
717 * Disconnects a handler from a cancellable instance similar to
718 * g_signal_handler_disconnect(). Additionally, in the event that a
719 * signal handler is currently running, this call will block until the
720 * handler has finished. Calling this function from a
721 * #GCancellable::cancelled signal handler will therefore result in a
724 * This avoids a race condition where a thread cancels at the
725 * same time as the cancellable operation is finished and the
726 * signal handler is removed. See #GCancellable::cancelled for
727 * details on how to use this.
729 * If @cancellable is %NULL or @handler_id is %0 this function does
735 g_cancellable_disconnect (GCancellable *cancellable,
738 GCancellablePrivate *priv;
740 if (handler_id == 0 || cancellable == NULL)
743 G_LOCK (cancellable);
745 priv = cancellable->priv;
747 while (priv->cancelled_running)
749 priv->cancelled_running_waiting = TRUE;
750 g_cond_wait (cancellable_cond,
751 g_static_mutex_get_mutex (& G_LOCK_NAME (cancellable)));
754 g_signal_handler_disconnect (cancellable, handler_id);
755 G_UNLOCK (cancellable);
761 GCancellable *cancellable;
763 } GCancellableSource;
766 cancellable_source_prepare (GSource *source,
769 GCancellableSource *cancellable_source = (GCancellableSource *)source;
772 return g_cancellable_is_cancelled (cancellable_source->cancellable);
776 cancellable_source_check (GSource *source)
778 GCancellableSource *cancellable_source = (GCancellableSource *)source;
780 return g_cancellable_is_cancelled (cancellable_source->cancellable);
784 cancellable_source_dispatch (GSource *source,
785 GSourceFunc callback,
788 GCancellableSourceFunc func = (GCancellableSourceFunc)callback;
789 GCancellableSource *cancellable_source = (GCancellableSource *)source;
791 return (*func) (cancellable_source->cancellable, user_data);
795 cancellable_source_finalize (GSource *source)
797 GCancellableSource *cancellable_source = (GCancellableSource *)source;
799 if (cancellable_source->cancellable)
800 g_object_unref (cancellable_source->cancellable);
804 cancellable_source_closure_callback (GCancellable *cancellable,
807 GClosure *closure = data;
809 GValue params = { 0, };
810 GValue result_value = { 0, };
813 g_value_init (&result_value, G_TYPE_BOOLEAN);
815 g_value_init (¶ms, G_TYPE_CANCELLABLE);
816 g_value_set_object (¶ms, cancellable);
818 g_closure_invoke (closure, &result_value, 1, ¶ms, NULL);
820 result = g_value_get_boolean (&result_value);
821 g_value_unset (&result_value);
822 g_value_unset (¶ms);
827 static GSourceFuncs cancellable_source_funcs =
829 cancellable_source_prepare,
830 cancellable_source_check,
831 cancellable_source_dispatch,
832 cancellable_source_finalize,
833 (GSourceFunc)cancellable_source_closure_callback,
834 (GSourceDummyMarshal)_gio_marshal_BOOLEAN__VOID,
838 * g_cancellable_source_new: (skip)
839 * @cancellable: a #GCancellable, or %NULL
841 * Creates a source that triggers if @cancellable is cancelled and
842 * calls its callback of type #GCancellableSourceFunc. This is
843 * primarily useful for attaching to another (non-cancellable) source
844 * with g_source_add_child_source() to add cancellability to it.
846 * For convenience, you can call this with a %NULL #GCancellable,
847 * in which case the source will never trigger.
849 * Return value: (transfer full): the new #GSource.
854 g_cancellable_source_new (GCancellable *cancellable)
857 GCancellableSource *cancellable_source;
859 source = g_source_new (&cancellable_source_funcs, sizeof (GCancellableSource));
860 g_source_set_name (source, "GCancellable");
861 cancellable_source = (GCancellableSource *)source;
863 if (g_cancellable_make_pollfd (cancellable,
864 &cancellable_source->pollfd))
866 cancellable_source->cancellable = g_object_ref (cancellable);
867 g_source_add_poll (source, &cancellable_source->pollfd);