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"
28 #include <sys/eventfd.h>
37 #include "gcancellable.h"
42 * SECTION:gcancellable
43 * @short_description: Thread-safe Operation Cancellation Stack
46 * GCancellable is a thread-safe operation cancellation stack used
47 * throughout GIO to allow for cancellation of synchronous and
48 * asynchronous operations.
56 struct _GCancellablePrivate
59 guint cancelled_running : 1;
60 guint cancelled_running_waiting : 1;
63 /* If cancel_pipe[0] is != -1 and cancel_pipe[1] is -1, it is an eventfd */
71 static guint signals[LAST_SIGNAL] = { 0 };
73 G_DEFINE_TYPE (GCancellable, g_cancellable, G_TYPE_OBJECT);
75 static GStaticPrivate current_cancellable = G_STATIC_PRIVATE_INIT;
76 G_LOCK_DEFINE_STATIC(cancellable);
77 static GCond *cancellable_cond = NULL;
80 g_cancellable_close_pipe (GCancellable *cancellable)
82 GCancellablePrivate *priv;
84 priv = cancellable->priv;
86 if (priv->cancel_pipe[0] != -1)
88 close (priv->cancel_pipe[0]);
89 priv->cancel_pipe[0] = -1;
92 if (priv->cancel_pipe[1] != -1)
94 close (priv->cancel_pipe[1]);
95 priv->cancel_pipe[1] = -1;
101 CloseHandle (priv->event);
108 g_cancellable_finalize (GObject *object)
110 GCancellable *cancellable = G_CANCELLABLE (object);
112 g_cancellable_close_pipe (cancellable);
114 G_OBJECT_CLASS (g_cancellable_parent_class)->finalize (object);
118 g_cancellable_class_init (GCancellableClass *klass)
120 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
122 g_type_class_add_private (klass, sizeof (GCancellablePrivate));
124 if (cancellable_cond == NULL && g_thread_supported ())
125 cancellable_cond = g_cond_new ();
127 gobject_class->finalize = g_cancellable_finalize;
130 * GCancellable::cancelled:
131 * @cancellable: a #GCancellable.
133 * Emitted when the operation has been cancelled.
135 * Can be used by implementations of cancellable operations. If the
136 * operation is cancelled from another thread, the signal will be
137 * emitted in the thread that cancelled the operation, not the
138 * thread that is running the operation.
140 * Note that disconnecting from this signal (or any signal) in a
141 * multi-threaded program is prone to race conditions. For instance
142 * it is possible that a signal handler may be invoked even
143 * <emphasis>after</emphasis> a call to
144 * g_signal_handler_disconnect() for that handler has already
147 * There is also a problem when cancellation happen
148 * right before connecting to the signal. If this happens the
149 * signal will unexpectedly not be emitted, and checking before
150 * connecting to the signal leaves a race condition where this is
153 * In order to make it safe and easy to connect handlers there
154 * are two helper functions: g_cancellable_connect() and
155 * g_cancellable_disconnect() which protect against problems
158 * An example of how to us this:
160 * /<!-- -->* Make sure we don't do any unnecessary work if already cancelled *<!-- -->/
161 * if (g_cancellable_set_error_if_cancelled (cancellable))
164 * /<!-- -->* Set up all the data needed to be able to
165 * * handle cancellation of the operation *<!-- -->/
166 * my_data = my_data_new (...);
170 * id = g_cancellable_connect (cancellable,
171 * G_CALLBACK (cancelled_handler)
174 * /<!-- -->* cancellable operation here... *<!-- -->/
176 * g_cancellable_disconnect (cancellable, id);
178 * /<!-- -->* cancelled_handler is never called after this, it
179 * * is now safe to free the data *<!-- -->/
180 * my_data_free (my_data);
183 * Note that the cancelled signal is emitted in the thread that
184 * the user cancelled from, which may be the main thread. So, the
185 * cancellable signal should not do something that can block.
188 g_signal_new (I_("cancelled"),
189 G_TYPE_FROM_CLASS (gobject_class),
191 G_STRUCT_OFFSET (GCancellableClass, cancelled),
193 g_cclosure_marshal_VOID__VOID,
201 g_cancellable_write_cancelled (GCancellable *cancellable)
204 GCancellablePrivate *priv;
207 priv = cancellable->priv;
209 if (priv->cancel_pipe[0] == -1)
212 g_assert (cancellable->priv->cancelled);
215 if (priv->cancel_pipe[1] == -1)
220 c = write (priv->cancel_pipe[0], &buf, sizeof (buf));
221 while (c == -1 && errno == EINTR);
228 c = write (priv->cancel_pipe[1], &ch, 1);
229 while (c == -1 && errno == EINTR);
233 g_cancellable_open_pipe (GCancellable *cancellable)
235 GCancellablePrivate *priv;
237 priv = cancellable->priv;
239 priv->cancel_pipe[0] = eventfd (0, EFD_CLOEXEC | EFD_NONBLOCK);
240 if (priv->cancel_pipe[0] >= 0)
243 g_cancellable_write_cancelled (cancellable);
246 else if (errno != ENOSYS)
248 /* Fall through on ENOSYS */
250 if (g_unix_open_pipe (priv->cancel_pipe, FD_CLOEXEC, NULL))
252 /* Make them nonblocking, just to be sure we don't block
253 * on errors and stuff
255 g_unix_set_fd_nonblocking (priv->cancel_pipe[0], TRUE, NULL);
256 g_unix_set_fd_nonblocking (priv->cancel_pipe[1], TRUE, NULL);
259 g_cancellable_write_cancelled (cancellable);
265 g_cancellable_init (GCancellable *cancellable)
267 cancellable->priv = G_TYPE_INSTANCE_GET_PRIVATE (cancellable,
269 GCancellablePrivate);
270 cancellable->priv->cancel_pipe[0] = -1;
271 cancellable->priv->cancel_pipe[1] = -1;
277 * Creates a new #GCancellable object.
279 * Applications that want to start one or more operations
280 * that should be cancellable should create a #GCancellable
281 * and pass it to the operations.
283 * One #GCancellable can be used in multiple consecutive
284 * operations, but not in multiple concurrent operations.
286 * Returns: a #GCancellable.
289 g_cancellable_new (void)
291 return g_object_new (G_TYPE_CANCELLABLE, NULL);
295 * g_cancellable_push_current:
296 * @cancellable: a #GCancellable object
298 * Pushes @cancellable onto the cancellable stack. The current
299 * cancellable can then be recieved using g_cancellable_get_current().
301 * This is useful when implementing cancellable operations in
302 * code that does not allow you to pass down the cancellable object.
304 * This is typically called automatically by e.g. #GFile operations,
305 * so you rarely have to call this yourself.
308 g_cancellable_push_current (GCancellable *cancellable)
312 g_return_if_fail (cancellable != NULL);
314 l = g_static_private_get (¤t_cancellable);
315 l = g_slist_prepend (l, cancellable);
316 g_static_private_set (¤t_cancellable, l, NULL);
320 * g_cancellable_pop_current:
321 * @cancellable: a #GCancellable object
323 * Pops @cancellable off the cancellable stack (verifying that @cancellable
324 * is on the top of the stack).
327 g_cancellable_pop_current (GCancellable *cancellable)
331 l = g_static_private_get (¤t_cancellable);
333 g_return_if_fail (l != NULL);
334 g_return_if_fail (l->data == cancellable);
336 l = g_slist_delete_link (l, l);
337 g_static_private_set (¤t_cancellable, l, NULL);
341 * g_cancellable_get_current:
343 * Gets the top cancellable from the stack.
345 * Returns: (transfer none): a #GCancellable from the top of the stack, or %NULL
346 * if the stack is empty.
349 g_cancellable_get_current (void)
353 l = g_static_private_get (¤t_cancellable);
357 return G_CANCELLABLE (l->data);
361 * g_cancellable_reset:
362 * @cancellable: a #GCancellable object.
364 * Resets @cancellable to its uncancelled state.
367 g_cancellable_reset (GCancellable *cancellable)
369 GCancellablePrivate *priv;
371 g_return_if_fail (G_IS_CANCELLABLE (cancellable));
375 priv = cancellable->priv;
377 while (priv->cancelled_running)
379 priv->cancelled_running_waiting = TRUE;
380 g_cond_wait (cancellable_cond,
381 g_static_mutex_get_mutex (& G_LOCK_NAME (cancellable)));
386 /* Make sure we're not leaving old cancel state around */
390 ResetEvent (priv->event);
392 if (priv->cancel_pipe[0] != -1)
396 if (priv->cancel_pipe[1] == -1)
401 c = read (priv->cancel_pipe[0], &buf, sizeof(buf));
402 while (c == -1 && errno == EINTR);
410 c = read (priv->cancel_pipe[0], &ch, 1);
411 while (c == -1 && errno == EINTR);
415 priv->cancelled = FALSE;
417 G_UNLOCK(cancellable);
421 * g_cancellable_is_cancelled:
422 * @cancellable: a #GCancellable or NULL.
424 * Checks if a cancellable job has been cancelled.
426 * Returns: %TRUE if @cancellable is cancelled,
427 * FALSE if called with %NULL or if item is not cancelled.
430 g_cancellable_is_cancelled (GCancellable *cancellable)
432 return cancellable != NULL && cancellable->priv->cancelled;
436 * g_cancellable_set_error_if_cancelled:
437 * @cancellable: a #GCancellable object.
438 * @error: #GError to append error state to.
440 * If the @cancellable is cancelled, sets the error to notify
441 * that the operation was cancelled.
443 * Returns: %TRUE if @cancellable was cancelled, %FALSE if it was not.
446 g_cancellable_set_error_if_cancelled (GCancellable *cancellable,
449 if (g_cancellable_is_cancelled (cancellable))
451 g_set_error_literal (error,
453 G_IO_ERROR_CANCELLED,
454 _("Operation was cancelled"));
462 * g_cancellable_get_fd:
463 * @cancellable: a #GCancellable.
465 * Gets the file descriptor for a cancellable job. This can be used to
466 * implement cancellable operations on Unix systems. The returned fd will
467 * turn readable when @cancellable is cancelled.
469 * You are not supposed to read from the fd yourself, just check for
470 * readable status. Reading to unset the readable status is done
471 * with g_cancellable_reset().
473 * After a successful return from this function, you should use
474 * g_cancellable_release_fd() to free up resources allocated for
475 * the returned file descriptor.
477 * See also g_cancellable_make_pollfd().
479 * Returns: A valid file descriptor. %-1 if the file descriptor
480 * is not supported, or on errors.
483 g_cancellable_get_fd (GCancellable *cancellable)
485 GCancellablePrivate *priv;
488 if (cancellable == NULL)
491 priv = cancellable->priv;
497 if (priv->cancel_pipe[0] == -1)
498 g_cancellable_open_pipe (cancellable);
499 fd = priv->cancel_pipe[0];
502 G_UNLOCK(cancellable);
509 * g_cancellable_make_pollfd:
510 * @cancellable: a #GCancellable or %NULL
511 * @pollfd: a pointer to a #GPollFD
513 * Creates a #GPollFD corresponding to @cancellable; this can be passed
514 * to g_poll() and used to poll for cancellation. This is useful both
515 * for unix systems without a native poll and for portability to
518 * When this function returns %TRUE, you should use
519 * g_cancellable_release_fd() to free up resources allocated for the
520 * @pollfd. After a %FALSE return, do not call g_cancellable_release_fd().
522 * If this function returns %FALSE, either no @cancellable was given or
523 * resource limits prevent this function from allocating the necessary
524 * structures for polling. (On Linux, you will likely have reached
525 * the maximum number of file descriptors.) The suggested way to handle
526 * these cases is to ignore the @cancellable.
528 * You are not supposed to read from the fd yourself, just check for
529 * readable status. Reading to unset the readable status is done
530 * with g_cancellable_reset().
532 * Returns: %TRUE if @pollfd was successfully initialized, %FALSE on
533 * failure to prepare the cancellable.
538 g_cancellable_make_pollfd (GCancellable *cancellable, GPollFD *pollfd)
540 g_return_val_if_fail (pollfd != NULL, FALSE);
541 if (cancellable == NULL)
543 g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), FALSE);
547 GCancellablePrivate *priv;
549 priv = cancellable->priv;
551 if (priv->event == NULL)
553 /* A manual reset anonymous event, starting unset */
554 priv->event = CreateEvent (NULL, TRUE, FALSE, NULL);
555 if (priv->event == NULL)
557 G_UNLOCK(cancellable);
561 SetEvent(priv->event);
564 G_UNLOCK(cancellable);
566 pollfd->fd = (gintptr)priv->event;
567 #else /* !G_OS_WIN32 */
568 int fd = g_cancellable_get_fd (cancellable);
573 #endif /* G_OS_WIN32 */
576 pollfd->events = G_IO_IN;
583 * g_cancellable_release_fd:
584 * @cancellable: a #GCancellable
586 * Releases a resources previously allocated by g_cancellable_get_fd()
587 * or g_cancellable_make_pollfd().
589 * For compatibility reasons with older releases, calling this function
590 * is not strictly required, the resources will be automatically freed
591 * when the @cancellable is finalized. However, the @cancellable will
592 * block scarce file descriptors until it is finalized if this function
593 * is not called. This can cause the application to run out of file
594 * descriptors when many #GCancellables are used at the same time.
599 g_cancellable_release_fd (GCancellable *cancellable)
601 GCancellablePrivate *priv;
603 if (cancellable == NULL)
606 g_return_if_fail (G_IS_CANCELLABLE (cancellable));
607 g_return_if_fail (cancellable->priv->fd_refcount > 0);
609 priv = cancellable->priv;
611 G_LOCK (cancellable);
613 if (priv->fd_refcount == 0)
614 g_cancellable_close_pipe (cancellable);
615 G_UNLOCK (cancellable);
619 * g_cancellable_cancel:
620 * @cancellable: a #GCancellable object.
622 * Will set @cancellable to cancelled, and will emit the
623 * #GCancellable::cancelled signal. (However, see the warning about
624 * race conditions in the documentation for that signal if you are
625 * planning to connect to it.)
627 * This function is thread-safe. In other words, you can safely call
628 * it from a thread other than the one running the operation that was
629 * passed the @cancellable.
631 * The convention within gio is that cancelling an asynchronous
632 * operation causes it to complete asynchronously. That is, if you
633 * cancel the operation from the same thread in which it is running,
634 * then the operation's #GAsyncReadyCallback will not be invoked until
635 * the application returns to the main loop.
638 g_cancellable_cancel (GCancellable *cancellable)
640 GCancellablePrivate *priv;
642 if (cancellable == NULL ||
643 cancellable->priv->cancelled)
646 priv = cancellable->priv;
651 G_UNLOCK (cancellable);
655 priv->cancelled = TRUE;
656 priv->cancelled_running = TRUE;
659 SetEvent (priv->event);
662 g_cancellable_write_cancelled (cancellable);
664 G_UNLOCK(cancellable);
666 g_object_ref (cancellable);
667 g_signal_emit (cancellable, signals[CANCELLED], 0);
671 priv->cancelled_running = FALSE;
672 if (priv->cancelled_running_waiting)
673 g_cond_broadcast (cancellable_cond);
674 priv->cancelled_running_waiting = FALSE;
676 G_UNLOCK(cancellable);
678 g_object_unref (cancellable);
682 * g_cancellable_connect:
683 * @cancellable: A #GCancellable.
684 * @callback: The #GCallback to connect.
685 * @data: Data to pass to @callback.
686 * @data_destroy_func: Free function for @data or %NULL.
688 * Convenience function to connect to the #GCancellable::cancelled
689 * signal. Also handles the race condition that may happen
690 * if the cancellable is cancelled right before connecting.
692 * @callback is called at most once, either directly at the
693 * time of the connect if @cancellable is already cancelled,
694 * or when @cancellable is cancelled in some thread.
696 * @data_destroy_func will be called when the handler is
697 * disconnected, or immediately if the cancellable is already
700 * See #GCancellable::cancelled for details on how to use this.
702 * Returns: The id of the signal handler or 0 if @cancellable has already
708 g_cancellable_connect (GCancellable *cancellable,
711 GDestroyNotify data_destroy_func)
715 g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), 0);
717 G_LOCK (cancellable);
719 if (cancellable->priv->cancelled)
721 void (*_callback) (GCancellable *cancellable,
724 _callback = (void *)callback;
727 _callback (cancellable, data);
729 if (data_destroy_func)
730 data_destroy_func (data);
734 id = g_signal_connect_data (cancellable, "cancelled",
736 (GClosureNotify) data_destroy_func,
739 G_UNLOCK (cancellable);
745 * g_cancellable_disconnect:
746 * @cancellable: A #GCancellable or %NULL.
747 * @handler_id: Handler id of the handler to be disconnected, or %0.
749 * Disconnects a handler from a cancellable instance similar to
750 * g_signal_handler_disconnect(). Additionally, in the event that a
751 * signal handler is currently running, this call will block until the
752 * handler has finished. Calling this function from a
753 * #GCancellable::cancelled signal handler will therefore result in a
756 * This avoids a race condition where a thread cancels at the
757 * same time as the cancellable operation is finished and the
758 * signal handler is removed. See #GCancellable::cancelled for
759 * details on how to use this.
761 * If @cancellable is %NULL or @handler_id is %0 this function does
767 g_cancellable_disconnect (GCancellable *cancellable,
770 GCancellablePrivate *priv;
772 if (handler_id == 0 || cancellable == NULL)
775 G_LOCK (cancellable);
777 priv = cancellable->priv;
779 while (priv->cancelled_running)
781 priv->cancelled_running_waiting = TRUE;
782 g_cond_wait (cancellable_cond,
783 g_static_mutex_get_mutex (& G_LOCK_NAME (cancellable)));
786 g_signal_handler_disconnect (cancellable, handler_id);
787 G_UNLOCK (cancellable);
793 GCancellable *cancellable;
795 } GCancellableSource;
798 cancellable_source_prepare (GSource *source,
801 GCancellableSource *cancellable_source = (GCancellableSource *)source;
804 return g_cancellable_is_cancelled (cancellable_source->cancellable);
808 cancellable_source_check (GSource *source)
810 GCancellableSource *cancellable_source = (GCancellableSource *)source;
812 return g_cancellable_is_cancelled (cancellable_source->cancellable);
816 cancellable_source_dispatch (GSource *source,
817 GSourceFunc callback,
820 GCancellableSourceFunc func = (GCancellableSourceFunc)callback;
821 GCancellableSource *cancellable_source = (GCancellableSource *)source;
823 return (*func) (cancellable_source->cancellable, user_data);
827 cancellable_source_finalize (GSource *source)
829 GCancellableSource *cancellable_source = (GCancellableSource *)source;
831 if (cancellable_source->cancellable)
832 g_object_unref (cancellable_source->cancellable);
836 cancellable_source_closure_callback (GCancellable *cancellable,
839 GClosure *closure = data;
841 GValue params = { 0, };
842 GValue result_value = { 0, };
845 g_value_init (&result_value, G_TYPE_BOOLEAN);
847 g_value_init (¶ms, G_TYPE_CANCELLABLE);
848 g_value_set_object (¶ms, cancellable);
850 g_closure_invoke (closure, &result_value, 1, ¶ms, NULL);
852 result = g_value_get_boolean (&result_value);
853 g_value_unset (&result_value);
854 g_value_unset (¶ms);
859 static GSourceFuncs cancellable_source_funcs =
861 cancellable_source_prepare,
862 cancellable_source_check,
863 cancellable_source_dispatch,
864 cancellable_source_finalize,
865 (GSourceFunc)cancellable_source_closure_callback,
866 (GSourceDummyMarshal)g_cclosure_marshal_generic,
870 * g_cancellable_source_new: (skip)
871 * @cancellable: a #GCancellable, or %NULL
873 * Creates a source that triggers if @cancellable is cancelled and
874 * calls its callback of type #GCancellableSourceFunc. This is
875 * primarily useful for attaching to another (non-cancellable) source
876 * with g_source_add_child_source() to add cancellability to it.
878 * For convenience, you can call this with a %NULL #GCancellable,
879 * in which case the source will never trigger.
881 * Return value: (transfer full): the new #GSource.
886 g_cancellable_source_new (GCancellable *cancellable)
889 GCancellableSource *cancellable_source;
891 source = g_source_new (&cancellable_source_funcs, sizeof (GCancellableSource));
892 g_source_set_name (source, "GCancellable");
893 cancellable_source = (GCancellableSource *)source;
895 if (g_cancellable_make_pollfd (cancellable,
896 &cancellable_source->pollfd))
898 cancellable_source->cancellable = g_object_ref (cancellable);
899 g_source_add_poll (source, &cancellable_source->pollfd);