gtestutils: Fix a typo in a documentation comment
[glib.git] / gio / gcancellable.c
blob2d098367f0bca57f3c9b1e4a4849481c8cedf182
1 /* GIO - GLib Input, Output and Streaming Library
2 *
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, see <http://www.gnu.org/licenses/>.
18 * Author: Alexander Larsson <alexl@redhat.com>
21 #include "config.h"
22 #include "glib.h"
23 #include <gioerror.h>
24 #include "glib-private.h"
25 #include "gcancellable.h"
26 #include "glibintl.h"
29 /**
30 * SECTION:gcancellable
31 * @short_description: Thread-safe Operation Cancellation Stack
32 * @include: gio/gio.h
34 * GCancellable is a thread-safe operation cancellation stack used
35 * throughout GIO to allow for cancellation of synchronous and
36 * asynchronous operations.
39 enum {
40 CANCELLED,
41 LAST_SIGNAL
44 struct _GCancellablePrivate
46 guint cancelled : 1;
47 guint cancelled_running : 1;
48 guint cancelled_running_waiting : 1;
50 guint fd_refcount;
51 GWakeup *wakeup;
54 static guint signals[LAST_SIGNAL] = { 0 };
56 G_DEFINE_TYPE_WITH_PRIVATE (GCancellable, g_cancellable, G_TYPE_OBJECT)
58 static GPrivate current_cancellable;
59 static GMutex cancellable_mutex;
60 static GCond cancellable_cond;
62 static void
63 g_cancellable_finalize (GObject *object)
65 GCancellable *cancellable = G_CANCELLABLE (object);
67 if (cancellable->priv->wakeup)
68 GLIB_PRIVATE_CALL (g_wakeup_free) (cancellable->priv->wakeup);
70 G_OBJECT_CLASS (g_cancellable_parent_class)->finalize (object);
73 static void
74 g_cancellable_class_init (GCancellableClass *klass)
76 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
78 gobject_class->finalize = g_cancellable_finalize;
80 /**
81 * GCancellable::cancelled:
82 * @cancellable: a #GCancellable.
84 * Emitted when the operation has been cancelled.
86 * Can be used by implementations of cancellable operations. If the
87 * operation is cancelled from another thread, the signal will be
88 * emitted in the thread that cancelled the operation, not the
89 * thread that is running the operation.
91 * Note that disconnecting from this signal (or any signal) in a
92 * multi-threaded program is prone to race conditions. For instance
93 * it is possible that a signal handler may be invoked even after
94 * a call to g_signal_handler_disconnect() for that handler has
95 * already returned.
97 * There is also a problem when cancellation happens right before
98 * connecting to the signal. If this happens the signal will
99 * unexpectedly not be emitted, and checking before connecting to
100 * the signal leaves a race condition where this is still happening.
102 * In order to make it safe and easy to connect handlers there
103 * are two helper functions: g_cancellable_connect() and
104 * g_cancellable_disconnect() which protect against problems
105 * like this.
107 * An example of how to us this:
108 * |[<!-- language="C" -->
109 * // Make sure we don't do unnecessary work if already cancelled
110 * if (g_cancellable_set_error_if_cancelled (cancellable, error))
111 * return;
113 * // Set up all the data needed to be able to handle cancellation
114 * // of the operation
115 * my_data = my_data_new (...);
117 * id = 0;
118 * if (cancellable)
119 * id = g_cancellable_connect (cancellable,
120 * G_CALLBACK (cancelled_handler)
121 * data, NULL);
123 * // cancellable operation here...
125 * g_cancellable_disconnect (cancellable, id);
127 * // cancelled_handler is never called after this, it is now safe
128 * // to free the data
129 * my_data_free (my_data);
130 * ]|
132 * Note that the cancelled signal is emitted in the thread that
133 * the user cancelled from, which may be the main thread. So, the
134 * cancellable signal should not do something that can block.
136 signals[CANCELLED] =
137 g_signal_new (I_("cancelled"),
138 G_TYPE_FROM_CLASS (gobject_class),
139 G_SIGNAL_RUN_LAST,
140 G_STRUCT_OFFSET (GCancellableClass, cancelled),
141 NULL, NULL,
142 g_cclosure_marshal_VOID__VOID,
143 G_TYPE_NONE, 0);
147 static void
148 g_cancellable_init (GCancellable *cancellable)
150 cancellable->priv = g_cancellable_get_instance_private (cancellable);
154 * g_cancellable_new:
156 * Creates a new #GCancellable object.
158 * Applications that want to start one or more operations
159 * that should be cancellable should create a #GCancellable
160 * and pass it to the operations.
162 * One #GCancellable can be used in multiple consecutive
163 * operations or in multiple concurrent operations.
165 * Returns: a #GCancellable.
167 GCancellable *
168 g_cancellable_new (void)
170 return g_object_new (G_TYPE_CANCELLABLE, NULL);
174 * g_cancellable_push_current:
175 * @cancellable: a #GCancellable object
177 * Pushes @cancellable onto the cancellable stack. The current
178 * cancellable can then be received using g_cancellable_get_current().
180 * This is useful when implementing cancellable operations in
181 * code that does not allow you to pass down the cancellable object.
183 * This is typically called automatically by e.g. #GFile operations,
184 * so you rarely have to call this yourself.
186 void
187 g_cancellable_push_current (GCancellable *cancellable)
189 GSList *l;
191 g_return_if_fail (cancellable != NULL);
193 l = g_private_get (&current_cancellable);
194 l = g_slist_prepend (l, cancellable);
195 g_private_set (&current_cancellable, l);
199 * g_cancellable_pop_current:
200 * @cancellable: a #GCancellable object
202 * Pops @cancellable off the cancellable stack (verifying that @cancellable
203 * is on the top of the stack).
205 void
206 g_cancellable_pop_current (GCancellable *cancellable)
208 GSList *l;
210 l = g_private_get (&current_cancellable);
212 g_return_if_fail (l != NULL);
213 g_return_if_fail (l->data == cancellable);
215 l = g_slist_delete_link (l, l);
216 g_private_set (&current_cancellable, l);
220 * g_cancellable_get_current:
222 * Gets the top cancellable from the stack.
224 * Returns: (nullable) (transfer none): a #GCancellable from the top
225 * of the stack, or %NULL if the stack is empty.
227 GCancellable *
228 g_cancellable_get_current (void)
230 GSList *l;
232 l = g_private_get (&current_cancellable);
233 if (l == NULL)
234 return NULL;
236 return G_CANCELLABLE (l->data);
240 * g_cancellable_reset:
241 * @cancellable: a #GCancellable object.
243 * Resets @cancellable to its uncancelled state.
245 * If cancellable is currently in use by any cancellable operation
246 * then the behavior of this function is undefined.
248 * Note that it is generally not a good idea to reuse an existing
249 * cancellable for more operations after it has been cancelled once,
250 * as this function might tempt you to do. The recommended practice
251 * is to drop the reference to a cancellable after cancelling it,
252 * and let it die with the outstanding async operations. You should
253 * create a fresh cancellable for further async operations.
255 void
256 g_cancellable_reset (GCancellable *cancellable)
258 GCancellablePrivate *priv;
260 g_return_if_fail (G_IS_CANCELLABLE (cancellable));
262 g_mutex_lock (&cancellable_mutex);
264 priv = cancellable->priv;
266 while (priv->cancelled_running)
268 priv->cancelled_running_waiting = TRUE;
269 g_cond_wait (&cancellable_cond, &cancellable_mutex);
272 if (priv->cancelled)
274 if (priv->wakeup)
275 GLIB_PRIVATE_CALL (g_wakeup_acknowledge) (priv->wakeup);
277 priv->cancelled = FALSE;
280 g_mutex_unlock (&cancellable_mutex);
284 * g_cancellable_is_cancelled:
285 * @cancellable: (nullable): 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.
292 gboolean
293 g_cancellable_is_cancelled (GCancellable *cancellable)
295 return cancellable != NULL && cancellable->priv->cancelled;
299 * g_cancellable_set_error_if_cancelled:
300 * @cancellable: (nullable): a #GCancellable or %NULL
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
308 gboolean
309 g_cancellable_set_error_if_cancelled (GCancellable *cancellable,
310 GError **error)
312 if (g_cancellable_is_cancelled (cancellable))
314 g_set_error_literal (error,
315 G_IO_ERROR,
316 G_IO_ERROR_CANCELLED,
317 _("Operation was cancelled"));
318 return TRUE;
321 return FALSE;
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)
348 GPollFD pollfd;
350 if (cancellable == NULL)
351 return -1;
353 #ifdef G_OS_WIN32
354 pollfd.fd = -1;
355 #else
356 g_cancellable_make_pollfd (cancellable, &pollfd);
357 #endif
359 return pollfd.fd;
363 * g_cancellable_make_pollfd:
364 * @cancellable: (nullable): a #GCancellable or %NULL
365 * @pollfd: a pointer to a #GPollFD
367 * Creates a #GPollFD corresponding to @cancellable; this can be passed
368 * to g_poll() and used to poll for cancellation. This is useful both
369 * for unix systems without a native poll and for portability to
370 * windows.
372 * When this function returns %TRUE, you should use
373 * g_cancellable_release_fd() to free up resources allocated for the
374 * @pollfd. After a %FALSE return, do not call g_cancellable_release_fd().
376 * If this function returns %FALSE, either no @cancellable was given or
377 * resource limits prevent this function from allocating the necessary
378 * structures for polling. (On Linux, you will likely have reached
379 * the maximum number of file descriptors.) The suggested way to handle
380 * these cases is to ignore the @cancellable.
382 * You are not supposed to read from the fd yourself, just check for
383 * readable status. Reading to unset the readable status is done
384 * with g_cancellable_reset().
386 * Returns: %TRUE if @pollfd was successfully initialized, %FALSE on
387 * failure to prepare the cancellable.
389 * Since: 2.22
391 gboolean
392 g_cancellable_make_pollfd (GCancellable *cancellable, GPollFD *pollfd)
394 g_return_val_if_fail (pollfd != NULL, FALSE);
395 if (cancellable == NULL)
396 return FALSE;
397 g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), FALSE);
399 g_mutex_lock (&cancellable_mutex);
401 cancellable->priv->fd_refcount++;
403 if (cancellable->priv->wakeup == NULL)
405 cancellable->priv->wakeup = GLIB_PRIVATE_CALL (g_wakeup_new) ();
407 if (cancellable->priv->cancelled)
408 GLIB_PRIVATE_CALL (g_wakeup_signal) (cancellable->priv->wakeup);
411 GLIB_PRIVATE_CALL (g_wakeup_get_pollfd) (cancellable->priv->wakeup, pollfd);
413 g_mutex_unlock (&cancellable_mutex);
415 return TRUE;
419 * g_cancellable_release_fd:
420 * @cancellable: a #GCancellable
422 * Releases a resources previously allocated by g_cancellable_get_fd()
423 * or g_cancellable_make_pollfd().
425 * For compatibility reasons with older releases, calling this function
426 * is not strictly required, the resources will be automatically freed
427 * when the @cancellable is finalized. However, the @cancellable will
428 * block scarce file descriptors until it is finalized if this function
429 * is not called. This can cause the application to run out of file
430 * descriptors when many #GCancellables are used at the same time.
432 * Since: 2.22
434 void
435 g_cancellable_release_fd (GCancellable *cancellable)
437 GCancellablePrivate *priv;
439 if (cancellable == NULL)
440 return;
442 g_return_if_fail (G_IS_CANCELLABLE (cancellable));
443 g_return_if_fail (cancellable->priv->fd_refcount > 0);
445 priv = cancellable->priv;
447 g_mutex_lock (&cancellable_mutex);
449 priv->fd_refcount--;
450 if (priv->fd_refcount == 0)
452 GLIB_PRIVATE_CALL (g_wakeup_free) (priv->wakeup);
453 priv->wakeup = NULL;
456 g_mutex_unlock (&cancellable_mutex);
460 * g_cancellable_cancel:
461 * @cancellable: (nullable): a #GCancellable object.
463 * Will set @cancellable to cancelled, and will emit the
464 * #GCancellable::cancelled signal. (However, see the warning about
465 * race conditions in the documentation for that signal if you are
466 * planning to connect to it.)
468 * This function is thread-safe. In other words, you can safely call
469 * it from a thread other than the one running the operation that was
470 * passed the @cancellable.
472 * If @cancellable is %NULL, this function returns immediately for convenience.
474 * The convention within GIO is that cancelling an asynchronous
475 * operation causes it to complete asynchronously. That is, if you
476 * cancel the operation from the same thread in which it is running,
477 * then the operation's #GAsyncReadyCallback will not be invoked until
478 * the application returns to the main loop.
480 void
481 g_cancellable_cancel (GCancellable *cancellable)
483 GCancellablePrivate *priv;
485 if (cancellable == NULL ||
486 cancellable->priv->cancelled)
487 return;
489 priv = cancellable->priv;
491 g_mutex_lock (&cancellable_mutex);
493 if (priv->cancelled)
495 g_mutex_unlock (&cancellable_mutex);
496 return;
499 priv->cancelled = TRUE;
500 priv->cancelled_running = TRUE;
502 if (priv->wakeup)
503 GLIB_PRIVATE_CALL (g_wakeup_signal) (priv->wakeup);
505 g_mutex_unlock (&cancellable_mutex);
507 g_object_ref (cancellable);
508 g_signal_emit (cancellable, signals[CANCELLED], 0);
510 g_mutex_lock (&cancellable_mutex);
512 priv->cancelled_running = FALSE;
513 if (priv->cancelled_running_waiting)
514 g_cond_broadcast (&cancellable_cond);
515 priv->cancelled_running_waiting = FALSE;
517 g_mutex_unlock (&cancellable_mutex);
519 g_object_unref (cancellable);
523 * g_cancellable_connect:
524 * @cancellable: A #GCancellable.
525 * @callback: The #GCallback to connect.
526 * @data: Data to pass to @callback.
527 * @data_destroy_func: (nullable): Free function for @data or %NULL.
529 * Convenience function to connect to the #GCancellable::cancelled
530 * signal. Also handles the race condition that may happen
531 * if the cancellable is cancelled right before connecting.
533 * @callback is called at most once, either directly at the
534 * time of the connect if @cancellable is already cancelled,
535 * or when @cancellable is cancelled in some thread.
537 * @data_destroy_func will be called when the handler is
538 * disconnected, or immediately if the cancellable is already
539 * cancelled.
541 * See #GCancellable::cancelled for details on how to use this.
543 * Since GLib 2.40, the lock protecting @cancellable is not held when
544 * @callback is invoked. This lifts a restriction in place for
545 * earlier GLib versions which now makes it easier to write cleanup
546 * code that unconditionally invokes e.g. g_cancellable_cancel().
548 * Returns: The id of the signal handler or 0 if @cancellable has already
549 * been cancelled.
551 * Since: 2.22
553 gulong
554 g_cancellable_connect (GCancellable *cancellable,
555 GCallback callback,
556 gpointer data,
557 GDestroyNotify data_destroy_func)
559 gulong id;
561 g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), 0);
563 g_mutex_lock (&cancellable_mutex);
565 if (cancellable->priv->cancelled)
567 void (*_callback) (GCancellable *cancellable,
568 gpointer user_data);
570 g_mutex_unlock (&cancellable_mutex);
572 _callback = (void *)callback;
573 id = 0;
575 _callback (cancellable, data);
577 if (data_destroy_func)
578 data_destroy_func (data);
580 else
582 id = g_signal_connect_data (cancellable, "cancelled",
583 callback, data,
584 (GClosureNotify) data_destroy_func,
587 g_mutex_unlock (&cancellable_mutex);
591 return id;
595 * g_cancellable_disconnect:
596 * @cancellable: (nullable): A #GCancellable or %NULL.
597 * @handler_id: Handler id of the handler to be disconnected, or %0.
599 * Disconnects a handler from a cancellable instance similar to
600 * g_signal_handler_disconnect(). Additionally, in the event that a
601 * signal handler is currently running, this call will block until the
602 * handler has finished. Calling this function from a
603 * #GCancellable::cancelled signal handler will therefore result in a
604 * deadlock.
606 * This avoids a race condition where a thread cancels at the
607 * same time as the cancellable operation is finished and the
608 * signal handler is removed. See #GCancellable::cancelled for
609 * details on how to use this.
611 * If @cancellable is %NULL or @handler_id is %0 this function does
612 * nothing.
614 * Since: 2.22
616 void
617 g_cancellable_disconnect (GCancellable *cancellable,
618 gulong handler_id)
620 GCancellablePrivate *priv;
622 if (handler_id == 0 || cancellable == NULL)
623 return;
625 g_mutex_lock (&cancellable_mutex);
627 priv = cancellable->priv;
629 while (priv->cancelled_running)
631 priv->cancelled_running_waiting = TRUE;
632 g_cond_wait (&cancellable_cond, &cancellable_mutex);
635 g_signal_handler_disconnect (cancellable, handler_id);
637 g_mutex_unlock (&cancellable_mutex);
640 typedef struct {
641 GSource source;
643 GCancellable *cancellable;
644 guint cancelled_handler;
645 } GCancellableSource;
647 static void
648 cancellable_source_cancelled (GCancellable *cancellable,
649 gpointer user_data)
651 GSource *source = user_data;
653 if (!g_source_is_destroyed (source))
654 g_source_set_ready_time (source, 0);
657 static gboolean
658 cancellable_source_dispatch (GSource *source,
659 GSourceFunc callback,
660 gpointer user_data)
662 GCancellableSourceFunc func = (GCancellableSourceFunc)callback;
663 GCancellableSource *cancellable_source = (GCancellableSource *)source;
665 g_source_set_ready_time (source, -1);
666 return (*func) (cancellable_source->cancellable, user_data);
669 static void
670 cancellable_source_finalize (GSource *source)
672 GCancellableSource *cancellable_source = (GCancellableSource *)source;
674 if (cancellable_source->cancellable)
676 g_cancellable_disconnect (cancellable_source->cancellable,
677 cancellable_source->cancelled_handler);
678 g_object_unref (cancellable_source->cancellable);
682 static gboolean
683 cancellable_source_closure_callback (GCancellable *cancellable,
684 gpointer data)
686 GClosure *closure = data;
688 GValue params = G_VALUE_INIT;
689 GValue result_value = G_VALUE_INIT;
690 gboolean result;
692 g_value_init (&result_value, G_TYPE_BOOLEAN);
694 g_value_init (&params, G_TYPE_CANCELLABLE);
695 g_value_set_object (&params, cancellable);
697 g_closure_invoke (closure, &result_value, 1, &params, NULL);
699 result = g_value_get_boolean (&result_value);
700 g_value_unset (&result_value);
701 g_value_unset (&params);
703 return result;
706 static GSourceFuncs cancellable_source_funcs =
708 NULL,
709 NULL,
710 cancellable_source_dispatch,
711 cancellable_source_finalize,
712 (GSourceFunc)cancellable_source_closure_callback,
716 * g_cancellable_source_new: (skip)
717 * @cancellable: (nullable): a #GCancellable, or %NULL
719 * Creates a source that triggers if @cancellable is cancelled and
720 * calls its callback of type #GCancellableSourceFunc. This is
721 * primarily useful for attaching to another (non-cancellable) source
722 * with g_source_add_child_source() to add cancellability to it.
724 * For convenience, you can call this with a %NULL #GCancellable,
725 * in which case the source will never trigger.
727 * The new #GSource will hold a reference to the #GCancellable.
729 * Returns: (transfer full): the new #GSource.
731 * Since: 2.28
733 GSource *
734 g_cancellable_source_new (GCancellable *cancellable)
736 GSource *source;
737 GCancellableSource *cancellable_source;
739 source = g_source_new (&cancellable_source_funcs, sizeof (GCancellableSource));
740 g_source_set_name (source, "GCancellable");
741 cancellable_source = (GCancellableSource *)source;
743 if (cancellable)
745 cancellable_source->cancellable = g_object_ref (cancellable);
747 /* We intentionally don't use g_cancellable_connect() here,
748 * because we don't want the "at most once" behavior.
750 cancellable_source->cancelled_handler =
751 g_signal_connect (cancellable, "cancelled",
752 G_CALLBACK (cancellable_source_cancelled),
753 source);
754 if (g_cancellable_is_cancelled (cancellable))
755 g_source_set_ready_time (source, 0);
758 return source;