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>
33 #include "gcancellable.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
55 GObject parent_instance;
58 guint cancelled_running : 1;
59 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_finalize (GObject *object)
78 GCancellable *cancellable = G_CANCELLABLE (object);
79 GCancellablePrivate *priv;
81 priv = cancellable->priv;
83 if (priv->cancel_pipe[0] != -1)
84 close (priv->cancel_pipe[0]);
86 if (priv->cancel_pipe[1] != -1)
87 close (priv->cancel_pipe[1]);
91 CloseHandle (priv->event);
94 G_OBJECT_CLASS (g_cancellable_parent_class)->finalize (object);
98 g_cancellable_class_init (GCancellableClass *klass)
100 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
102 g_type_class_add_private (klass, sizeof (GCancellablePrivate));
104 if (cancellable_cond == NULL && g_thread_supported ())
105 cancellable_cond = g_cond_new ();
107 gobject_class->finalize = g_cancellable_finalize;
110 * GCancellable::cancelled:
111 * @cancellable: a #GCancellable.
113 * Emitted when the operation has been cancelled.
115 * Can be used by implementations of cancellable operations. If the
116 * operation is cancelled from another thread, the signal will be
117 * emitted in the thread that cancelled the operation, not the
118 * thread that is running the operation.
120 * Note that disconnecting from this signal (or any signal) in a
121 * multi-threaded program is prone to race conditions. For instance
122 * it is possible that a signal handler may be invoked even
123 * <emphasis>after</emphasis> a call to
124 * g_signal_handler_disconnect() for that handler has already
127 * There is also a problem when cancellation happen
128 * right before connecting to the signal. If this happens the
129 * signal will unexpectedly not be emitted, and checking before
130 * connecting to the signal leaves a race condition where this is
133 * In order to make it safe and easy to connect handlers there
134 * are two helper functions: g_cancellable_connect() and
135 * g_cancellable_disconnect() which protect against problems
138 * An example of how to us this:
140 * /<!-- -->* Make sure we don't do any unnecessary work if already cancelled *<!-- -->/
141 * if (g_cancellable_set_error_if_cancelled (cancellable))
144 * /<!-- -->* Set up all the data needed to be able to
145 * * handle cancellation of the operation *<!-- -->/
146 * my_data = my_data_new (...);
150 * id = g_cancellable_connect (cancellable,
151 * G_CALLBACK (cancelled_handler)
154 * /<!-- -->* cancellable operation here... *<!-- -->/
156 * g_cancellable_disconnect (cancellable, id);
158 * /<!-- -->* cancelled_handler is never called after this, it
159 * * is now safe to free the data *<!-- -->/
160 * my_data_free (my_data);
163 * Note that the cancelled signal is emitted in the thread that
164 * the user cancelled from, which may be the main thread. So, the
165 * cancellable signal should not do something that can block.
168 g_signal_new (I_("cancelled"),
169 G_TYPE_FROM_CLASS (gobject_class),
171 G_STRUCT_OFFSET (GCancellableClass, cancelled),
173 g_cclosure_marshal_VOID__VOID,
180 set_fd_nonblocking (int fd)
184 fcntl_flags = fcntl (fd, F_GETFL);
187 fcntl_flags |= O_NONBLOCK;
189 fcntl_flags |= O_NDELAY;
192 fcntl (fd, F_SETFL, fcntl_flags);
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 set_fd_nonblocking (priv->cancel_pipe[0]);
222 set_fd_nonblocking (priv->cancel_pipe[1]);
223 set_fd_close_exec (priv->cancel_pipe[0]);
224 set_fd_close_exec (priv->cancel_pipe[1]);
230 g_cancellable_init (GCancellable *cancellable)
232 cancellable->priv = G_TYPE_INSTANCE_GET_PRIVATE (cancellable,
234 GCancellablePrivate);
235 cancellable->priv->cancel_pipe[0] = -1;
236 cancellable->priv->cancel_pipe[1] = -1;
242 * Creates a new #GCancellable object.
244 * Applications that want to start one or more operations
245 * that should be cancellable should create a #GCancellable
246 * and pass it to the operations.
248 * One #GCancellable can be used in multiple consecutive
249 * operations, but not in multiple concurrent operations.
251 * Returns: a #GCancellable.
254 g_cancellable_new (void)
256 return g_object_new (G_TYPE_CANCELLABLE, NULL);
260 * g_cancellable_push_current:
261 * @cancellable: a #GCancellable object
263 * Pushes @cancellable onto the cancellable stack. The current
264 * cancllable can then be recieved using g_cancellable_get_current().
266 * This is useful when implementing cancellable operations in
267 * code that does not allow you to pass down the cancellable object.
269 * This is typically called automatically by e.g. #GFile operations,
270 * so you rarely have to call this yourself.
273 g_cancellable_push_current (GCancellable *cancellable)
277 g_return_if_fail (cancellable != NULL);
279 l = g_static_private_get (¤t_cancellable);
280 l = g_slist_prepend (l, cancellable);
281 g_static_private_set (¤t_cancellable, l, NULL);
285 * g_cancellable_pop_current:
286 * @cancellable: a #GCancellable object
288 * Pops @cancellable off the cancellable stack (verifying that @cancellable
289 * is on the top of the stack).
292 g_cancellable_pop_current (GCancellable *cancellable)
296 l = g_static_private_get (¤t_cancellable);
298 g_return_if_fail (l != NULL);
299 g_return_if_fail (l->data == cancellable);
301 l = g_slist_delete_link (l, l);
302 g_static_private_set (¤t_cancellable, l, NULL);
306 * g_cancellable_get_current:
308 * Gets the top cancellable from the stack.
310 * Returns: a #GCancellable from the top of the stack, or %NULL
311 * if the stack is empty.
314 g_cancellable_get_current (void)
318 l = g_static_private_get (¤t_cancellable);
322 return G_CANCELLABLE (l->data);
326 * g_cancellable_reset:
327 * @cancellable: a #GCancellable object.
329 * Resets @cancellable to its uncancelled state.
332 g_cancellable_reset (GCancellable *cancellable)
334 GCancellablePrivate *priv;
336 g_return_if_fail (G_IS_CANCELLABLE (cancellable));
340 priv = cancellable->priv;
342 while (priv->cancelled_running)
344 priv->cancelled_running_waiting = TRUE;
345 g_cond_wait (cancellable_cond,
346 g_static_mutex_get_mutex (& G_LOCK_NAME (cancellable)));
353 /* Make sure we're not leaving old cancel state around */
357 ResetEvent (priv->event);
360 if (priv->cancel_pipe[0] != -1)
361 read (priv->cancel_pipe[0], &ch, 1);
362 priv->cancelled = FALSE;
364 G_UNLOCK(cancellable);
368 * g_cancellable_is_cancelled:
369 * @cancellable: a #GCancellable or NULL.
371 * Checks if a cancellable job has been cancelled.
373 * Returns: %TRUE if @cancellable is cancelled,
374 * FALSE if called with %NULL or if item is not cancelled.
377 g_cancellable_is_cancelled (GCancellable *cancellable)
379 return cancellable != NULL && cancellable->priv->cancelled;
383 * g_cancellable_set_error_if_cancelled:
384 * @cancellable: a #GCancellable object.
385 * @error: #GError to append error state to.
387 * If the @cancellable is cancelled, sets the error to notify
388 * that the operation was cancelled.
390 * Returns: %TRUE if @cancellable was cancelled, %FALSE if it was not.
393 g_cancellable_set_error_if_cancelled (GCancellable *cancellable,
396 if (g_cancellable_is_cancelled (cancellable))
398 g_set_error_literal (error,
400 G_IO_ERROR_CANCELLED,
401 _("Operation was cancelled"));
409 * g_cancellable_get_fd:
410 * @cancellable: a #GCancellable.
412 * Gets the file descriptor for a cancellable job. This can be used to
413 * implement cancellable operations on Unix systems. The returned fd will
414 * turn readable when @cancellable is cancelled.
416 * You are not supposed to read from the fd yourself, just check for
417 * readable status. Reading to unset the readable status is done
418 * with g_cancellable_reset().
420 * See also g_cancellable_make_pollfd().
422 * Returns: A valid file descriptor. %-1 if the file descriptor
423 * is not supported, or on errors.
426 g_cancellable_get_fd (GCancellable *cancellable)
428 GCancellablePrivate *priv;
431 if (cancellable == NULL)
434 priv = cancellable->priv;
440 if (priv->cancel_pipe[0] == -1)
441 g_cancellable_open_pipe (cancellable);
443 fd = priv->cancel_pipe[0];
444 G_UNLOCK(cancellable);
451 * g_cancellable_make_pollfd:
452 * @cancellable: a #GCancellable or %NULL
453 * @pollfd: a pointer to a #GPollFD
455 * Creates a #GPollFD corresponding to @cancellable; this can be passed
456 * to g_poll() and used to poll for cancellation. This is useful both
457 * for unix systems without a native poll and for portability to
460 * If this function returns %FALSE, either no @cancellable was given or
461 * resource limits prevent this function from allocating the necessary
462 * structures for polling. (On Linux, you will likely have reached
463 * the maximum number of file descriptors.) The suggested way to handle
464 * these cases is to ignore the @cancellable.
466 * You are not supposed to read from the fd yourself, just check for
467 * readable status. Reading to unset the readable status is done
468 * with g_cancellable_reset().
470 * @Returns: %TRUE if @pollfd was successfully initialized, %FALSE on
471 * failure to prepare the cancellable.
476 g_cancellable_make_pollfd (GCancellable *cancellable, GPollFD *pollfd)
478 GCancellablePrivate *priv;
481 g_return_val_if_fail (pollfd != NULL, FALSE);
482 if (cancellable == NULL)
484 g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), FALSE);
486 priv = cancellable->priv;
491 /* A manual reset anonymous event, starting unset */
492 priv->event = CreateEvent (NULL, TRUE, FALSE, NULL);
493 if (priv->event == NULL)
496 pollfd->fd = (gintptr)priv->event;
497 #else /* !G_OS_WIN32 */
498 fd = g_cancellable_get_fd (cancellable);
502 #endif /* G_OS_WIN32 */
503 pollfd->events = G_IO_IN;
508 * g_cancellable_cancel:
509 * @cancellable: a #GCancellable object.
511 * Will set @cancellable to cancelled, and will emit the
512 * #GCancellable::cancelled signal. (However, see the warning about
513 * race conditions in the documentation for that signal if you are
514 * planning to connect to it.)
516 * This function is thread-safe. In other words, you can safely call
517 * it from a thread other than the one running the operation that was
518 * passed the @cancellable.
520 * The convention within gio is that cancelling an asynchronous
521 * operation causes it to complete asynchronously. That is, if you
522 * cancel the operation from the same thread in which it is running,
523 * then the operation's #GAsyncReadyCallback will not be invoked until
524 * the application returns to the main loop.
527 g_cancellable_cancel (GCancellable *cancellable)
529 static const char ch = 'x';
531 GCancellablePrivate *priv;
533 if (cancellable == NULL ||
534 cancellable->priv->cancelled)
537 priv = cancellable->priv;
542 priv->cancelled = TRUE;
543 priv->cancelled_running = TRUE;
546 SetEvent(priv->event);
548 if (priv->cancel_pipe[1] != -1)
549 write (priv->cancel_pipe[1], &ch, 1);
550 G_UNLOCK(cancellable);
554 g_object_ref (cancellable);
555 g_signal_emit (cancellable, signals[CANCELLED], 0);
559 priv->cancelled_running = FALSE;
560 if (priv->cancelled_running_waiting)
561 g_cond_broadcast (cancellable_cond);
562 priv->cancelled_running_waiting = FALSE;
564 G_UNLOCK(cancellable);
566 g_object_unref (cancellable);
571 * g_cancellable_connect:
572 * @cancellable: A #GCancellable.
573 * @callback: The #GCallback to connect.
574 * @data: Data to pass to @callback.
575 * @data_destroy_func: Free function for @data or %NULL.
577 * Convenience function to connect to the #GCancellable::cancelled
578 * signal. Also handles the race condition that may happen
579 * if the cancellable is cancelled right before connecting.
581 * @callback is called at most once, either directly at the
582 * time of the connect if @cancellable is already cancelled,
583 * or when @cancellable is cancelled in some thread.
585 * @data_destroy_func will be called when the handler is
586 * disconnected, or immediately if the cancellable is already
589 * See #GCancellable::cancelled for details on how to use this.
591 * Returns: The id of the signal handler or 0 if @cancellable has already
597 g_cancellable_connect (GCancellable *cancellable,
600 GDestroyNotify data_destroy_func)
604 g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), 0);
606 G_LOCK (cancellable);
608 if (cancellable->priv->cancelled)
610 void (*_callback) (GCancellable *cancellable,
613 _callback = (void *)callback;
616 _callback (cancellable, data);
618 if (data_destroy_func)
619 data_destroy_func (data);
623 id = g_signal_connect_data (cancellable, "cancelled",
625 (GClosureNotify) data_destroy_func,
628 G_UNLOCK (cancellable);
634 * g_cancellable_disconnect:
635 * @cancellable: A #GCancellable or %NULL.
636 * @handler_id: Handler id of the handler to be disconnected, or %0.
638 * Disconnects a handler from an cancellable instance similar to
639 * g_signal_handler_disconnect() but ensures that once this
640 * function returns the handler will not run anymore in any thread.
642 * This avoids a race condition where a thread cancels at the
643 * same time as the cancellable operation is finished and the
644 * signal handler is removed. See #GCancellable::cancelled for
645 * details on how to use this.
647 * If @cancellable is %NULL or @handler_id is %0 this function does
653 g_cancellable_disconnect (GCancellable *cancellable,
656 GCancellablePrivate *priv;
658 if (handler_id == 0 || cancellable == NULL)
661 G_LOCK (cancellable);
663 priv = cancellable->priv;
665 while (priv->cancelled_running)
667 priv->cancelled_running_waiting = TRUE;
668 g_cond_wait (cancellable_cond,
669 g_static_mutex_get_mutex (& G_LOCK_NAME (cancellable)));
672 g_signal_handler_disconnect (cancellable, handler_id);
673 G_UNLOCK (cancellable);
676 #define __G_CANCELLABLE_C__
677 #include "gioaliasdef.c"