Fix old wiki links
[platform/upstream/glib.git] / gio / gcancellable.c
1 /* GIO - GLib Input, Output and Streaming Library
2  * 
3  * Copyright (C) 2006-2007 Red Hat, Inc.
4  *
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.
9  *
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.
14  *
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/>.
17  *
18  * Author: Alexander Larsson <alexl@redhat.com>
19  */
20
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"
27
28
29 /**
30  * SECTION:gcancellable
31  * @short_description: Thread-safe Operation Cancellation Stack
32  * @include: gio/gio.h
33  *
34  * GCancellable is a thread-safe operation cancellation stack used 
35  * throughout GIO to allow for cancellation of synchronous and
36  * asynchronous operations.
37  */
38
39 enum {
40   CANCELLED,
41   LAST_SIGNAL
42 };
43
44 struct _GCancellablePrivate
45 {
46   guint cancelled : 1;
47   guint cancelled_running : 1;
48   guint cancelled_running_waiting : 1;
49
50   guint fd_refcount;
51   GWakeup *wakeup;
52 };
53
54 static guint signals[LAST_SIGNAL] = { 0 };
55
56 G_DEFINE_TYPE_WITH_PRIVATE (GCancellable, g_cancellable, G_TYPE_OBJECT)
57
58 static GPrivate current_cancellable;
59 static GMutex cancellable_mutex;
60 static GCond cancellable_cond;
61
62 static void
63 g_cancellable_finalize (GObject *object)
64 {
65   GCancellable *cancellable = G_CANCELLABLE (object);
66
67   if (cancellable->priv->wakeup)
68     GLIB_PRIVATE_CALL (g_wakeup_free) (cancellable->priv->wakeup);
69
70   G_OBJECT_CLASS (g_cancellable_parent_class)->finalize (object);
71 }
72
73 static void
74 g_cancellable_class_init (GCancellableClass *klass)
75 {
76   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
77
78   gobject_class->finalize = g_cancellable_finalize;
79
80   /**
81    * GCancellable::cancelled:
82    * @cancellable: a #GCancellable.
83    * 
84    * Emitted when the operation has been cancelled.
85    * 
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.
90    *
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.
96    * 
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.
101    *
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.
106    *
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;
112    *
113    *     // Set up all the data needed to be able to handle cancellation
114    *     // of the operation
115    *     my_data = my_data_new (...);
116    *
117    *     id = 0;
118    *     if (cancellable)
119    *       id = g_cancellable_connect (cancellable,
120    *                                  G_CALLBACK (cancelled_handler)
121    *                                  data, NULL);
122    *
123    *     // cancellable operation here...
124    *
125    *     g_cancellable_disconnect (cancellable, id);
126    *
127    *     // cancelled_handler is never called after this, it is now safe
128    *     // to free the data
129    *     my_data_free (my_data);  
130    * ]|
131    *
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.
135    */
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);
144   
145 }
146
147 static void
148 g_cancellable_init (GCancellable *cancellable)
149 {
150   cancellable->priv = g_cancellable_get_instance_private (cancellable);
151 }
152
153 /**
154  * g_cancellable_new:
155  * 
156  * Creates a new #GCancellable object.
157  *
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.
161  *
162  * One #GCancellable can be used in multiple consecutive
163  * operations or in multiple concurrent operations.
164  *  
165  * Returns: a #GCancellable.
166  **/
167 GCancellable *
168 g_cancellable_new (void)
169 {
170   return g_object_new (G_TYPE_CANCELLABLE, NULL);
171 }
172
173 /**
174  * g_cancellable_push_current:
175  * @cancellable: a #GCancellable object
176  *
177  * Pushes @cancellable onto the cancellable stack. The current
178  * cancellable can then be received using g_cancellable_get_current().
179  *
180  * This is useful when implementing cancellable operations in
181  * code that does not allow you to pass down the cancellable object.
182  *
183  * This is typically called automatically by e.g. #GFile operations,
184  * so you rarely have to call this yourself.
185  **/
186 void
187 g_cancellable_push_current (GCancellable *cancellable)
188 {
189   GSList *l;
190
191   g_return_if_fail (cancellable != NULL);
192
193   l = g_private_get (&current_cancellable);
194   l = g_slist_prepend (l, cancellable);
195   g_private_set (&current_cancellable, l);
196 }
197
198 /**
199  * g_cancellable_pop_current:
200  * @cancellable: a #GCancellable object
201  *
202  * Pops @cancellable off the cancellable stack (verifying that @cancellable
203  * is on the top of the stack).
204  **/
205 void
206 g_cancellable_pop_current (GCancellable *cancellable)
207 {
208   GSList *l;
209
210   l = g_private_get (&current_cancellable);
211
212   g_return_if_fail (l != NULL);
213   g_return_if_fail (l->data == cancellable);
214
215   l = g_slist_delete_link (l, l);
216   g_private_set (&current_cancellable, l);
217 }
218
219 /**
220  * g_cancellable_get_current:
221  *
222  * Gets the top cancellable from the stack.
223  *
224  * Returns: (nullable) (transfer none): a #GCancellable from the top
225  * of the stack, or %NULL if the stack is empty.
226  **/
227 GCancellable *
228 g_cancellable_get_current  (void)
229 {
230   GSList *l;
231
232   l = g_private_get (&current_cancellable);
233   if (l == NULL)
234     return NULL;
235
236   return G_CANCELLABLE (l->data);
237 }
238
239 /**
240  * g_cancellable_reset:
241  * @cancellable: a #GCancellable object.
242  * 
243  * Resets @cancellable to its uncancelled state.
244  *
245  * If cancellable is currently in use by any cancellable operation
246  * then the behavior of this function is undefined.
247  **/
248 void 
249 g_cancellable_reset (GCancellable *cancellable)
250 {
251   GCancellablePrivate *priv;
252
253   g_return_if_fail (G_IS_CANCELLABLE (cancellable));
254
255   g_mutex_lock (&cancellable_mutex);
256
257   priv = cancellable->priv;
258
259   while (priv->cancelled_running)
260     {
261       priv->cancelled_running_waiting = TRUE;
262       g_cond_wait (&cancellable_cond, &cancellable_mutex);
263     }
264
265   if (priv->cancelled)
266     {
267       if (priv->wakeup)
268         GLIB_PRIVATE_CALL (g_wakeup_acknowledge) (priv->wakeup);
269
270       priv->cancelled = FALSE;
271     }
272
273   g_mutex_unlock (&cancellable_mutex);
274 }
275
276 /**
277  * g_cancellable_is_cancelled:
278  * @cancellable: (allow-none): a #GCancellable or %NULL
279  *
280  * Checks if a cancellable job has been cancelled.
281  *
282  * Returns: %TRUE if @cancellable is cancelled,
283  * FALSE if called with %NULL or if item is not cancelled.
284  **/
285 gboolean
286 g_cancellable_is_cancelled (GCancellable *cancellable)
287 {
288   return cancellable != NULL && cancellable->priv->cancelled;
289 }
290
291 /**
292  * g_cancellable_set_error_if_cancelled:
293  * @cancellable: (allow-none): a #GCancellable or %NULL
294  * @error: #GError to append error state to
295  *
296  * If the @cancellable is cancelled, sets the error to notify
297  * that the operation was cancelled.
298  *
299  * Returns: %TRUE if @cancellable was cancelled, %FALSE if it was not
300  */
301 gboolean
302 g_cancellable_set_error_if_cancelled (GCancellable  *cancellable,
303                                       GError       **error)
304 {
305   if (g_cancellable_is_cancelled (cancellable))
306     {
307       g_set_error_literal (error,
308                            G_IO_ERROR,
309                            G_IO_ERROR_CANCELLED,
310                            _("Operation was cancelled"));
311       return TRUE;
312     }
313
314   return FALSE;
315 }
316
317 /**
318  * g_cancellable_get_fd:
319  * @cancellable: a #GCancellable.
320  * 
321  * Gets the file descriptor for a cancellable job. This can be used to
322  * implement cancellable operations on Unix systems. The returned fd will
323  * turn readable when @cancellable is cancelled.
324  *
325  * You are not supposed to read from the fd yourself, just check for
326  * readable status. Reading to unset the readable status is done
327  * with g_cancellable_reset().
328  * 
329  * After a successful return from this function, you should use 
330  * g_cancellable_release_fd() to free up resources allocated for 
331  * the returned file descriptor.
332  *
333  * See also g_cancellable_make_pollfd().
334  *
335  * Returns: A valid file descriptor. %-1 if the file descriptor 
336  * is not supported, or on errors. 
337  **/
338 int
339 g_cancellable_get_fd (GCancellable *cancellable)
340 {
341   GPollFD pollfd;
342
343   if (cancellable == NULL)
344           return -1;
345
346 #ifdef G_OS_WIN32
347   pollfd.fd = -1;
348 #else
349   g_cancellable_make_pollfd (cancellable, &pollfd);
350 #endif
351
352   return pollfd.fd;
353 }
354
355 /**
356  * g_cancellable_make_pollfd:
357  * @cancellable: (allow-none): a #GCancellable or %NULL
358  * @pollfd: a pointer to a #GPollFD
359  * 
360  * Creates a #GPollFD corresponding to @cancellable; this can be passed
361  * to g_poll() and used to poll for cancellation. This is useful both
362  * for unix systems without a native poll and for portability to
363  * windows.
364  *
365  * When this function returns %TRUE, you should use 
366  * g_cancellable_release_fd() to free up resources allocated for the 
367  * @pollfd. After a %FALSE return, do not call g_cancellable_release_fd().
368  *
369  * If this function returns %FALSE, either no @cancellable was given or
370  * resource limits prevent this function from allocating the necessary 
371  * structures for polling. (On Linux, you will likely have reached 
372  * the maximum number of file descriptors.) The suggested way to handle
373  * these cases is to ignore the @cancellable.
374  *
375  * You are not supposed to read from the fd yourself, just check for
376  * readable status. Reading to unset the readable status is done
377  * with g_cancellable_reset().
378  *
379  * Returns: %TRUE if @pollfd was successfully initialized, %FALSE on 
380  *          failure to prepare the cancellable.
381  * 
382  * Since: 2.22
383  **/
384 gboolean
385 g_cancellable_make_pollfd (GCancellable *cancellable, GPollFD *pollfd)
386 {
387   g_return_val_if_fail (pollfd != NULL, FALSE);
388   if (cancellable == NULL)
389     return FALSE;
390   g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), FALSE);
391
392   g_mutex_lock (&cancellable_mutex);
393
394   cancellable->priv->fd_refcount++;
395
396   if (cancellable->priv->wakeup == NULL)
397     {
398       cancellable->priv->wakeup = GLIB_PRIVATE_CALL (g_wakeup_new) ();
399
400       if (cancellable->priv->cancelled)
401         GLIB_PRIVATE_CALL (g_wakeup_signal) (cancellable->priv->wakeup);
402     }
403
404   GLIB_PRIVATE_CALL (g_wakeup_get_pollfd) (cancellable->priv->wakeup, pollfd);
405
406   g_mutex_unlock (&cancellable_mutex);
407
408   return TRUE;
409 }
410
411 /**
412  * g_cancellable_release_fd:
413  * @cancellable: a #GCancellable
414  *
415  * Releases a resources previously allocated by g_cancellable_get_fd()
416  * or g_cancellable_make_pollfd().
417  *
418  * For compatibility reasons with older releases, calling this function 
419  * is not strictly required, the resources will be automatically freed
420  * when the @cancellable is finalized. However, the @cancellable will
421  * block scarce file descriptors until it is finalized if this function
422  * is not called. This can cause the application to run out of file 
423  * descriptors when many #GCancellables are used at the same time.
424  * 
425  * Since: 2.22
426  **/
427 void
428 g_cancellable_release_fd (GCancellable *cancellable)
429 {
430   GCancellablePrivate *priv;
431
432   if (cancellable == NULL)
433     return;
434
435   g_return_if_fail (G_IS_CANCELLABLE (cancellable));
436   g_return_if_fail (cancellable->priv->fd_refcount > 0);
437
438   priv = cancellable->priv;
439
440   g_mutex_lock (&cancellable_mutex);
441
442   priv->fd_refcount--;
443   if (priv->fd_refcount == 0)
444     {
445       GLIB_PRIVATE_CALL (g_wakeup_free) (priv->wakeup);
446       priv->wakeup = NULL;
447     }
448
449   g_mutex_unlock (&cancellable_mutex);
450 }
451
452 /**
453  * g_cancellable_cancel:
454  * @cancellable: a #GCancellable object.
455  * 
456  * Will set @cancellable to cancelled, and will emit the
457  * #GCancellable::cancelled signal. (However, see the warning about
458  * race conditions in the documentation for that signal if you are
459  * planning to connect to it.)
460  *
461  * This function is thread-safe. In other words, you can safely call
462  * it from a thread other than the one running the operation that was
463  * passed the @cancellable.
464  *
465  * The convention within gio is that cancelling an asynchronous
466  * operation causes it to complete asynchronously. That is, if you
467  * cancel the operation from the same thread in which it is running,
468  * then the operation's #GAsyncReadyCallback will not be invoked until
469  * the application returns to the main loop.
470  **/
471 void
472 g_cancellable_cancel (GCancellable *cancellable)
473 {
474   GCancellablePrivate *priv;
475
476   if (cancellable == NULL ||
477       cancellable->priv->cancelled)
478     return;
479
480   priv = cancellable->priv;
481
482   g_mutex_lock (&cancellable_mutex);
483
484   if (priv->cancelled)
485     {
486       g_mutex_unlock (&cancellable_mutex);
487       return;
488     }
489
490   priv->cancelled = TRUE;
491   priv->cancelled_running = TRUE;
492
493   if (priv->wakeup)
494     GLIB_PRIVATE_CALL (g_wakeup_signal) (priv->wakeup);
495
496   g_mutex_unlock (&cancellable_mutex);
497
498   g_object_ref (cancellable);
499   g_signal_emit (cancellable, signals[CANCELLED], 0);
500
501   g_mutex_lock (&cancellable_mutex);
502
503   priv->cancelled_running = FALSE;
504   if (priv->cancelled_running_waiting)
505     g_cond_broadcast (&cancellable_cond);
506   priv->cancelled_running_waiting = FALSE;
507
508   g_mutex_unlock (&cancellable_mutex);
509
510   g_object_unref (cancellable);
511 }
512
513 /**
514  * g_cancellable_connect:
515  * @cancellable: A #GCancellable.
516  * @callback: The #GCallback to connect.
517  * @data: Data to pass to @callback.
518  * @data_destroy_func: (allow-none): Free function for @data or %NULL.
519  *
520  * Convenience function to connect to the #GCancellable::cancelled
521  * signal. Also handles the race condition that may happen
522  * if the cancellable is cancelled right before connecting.
523  *
524  * @callback is called at most once, either directly at the
525  * time of the connect if @cancellable is already cancelled,
526  * or when @cancellable is cancelled in some thread.
527  *
528  * @data_destroy_func will be called when the handler is
529  * disconnected, or immediately if the cancellable is already
530  * cancelled.
531  *
532  * See #GCancellable::cancelled for details on how to use this.
533  *
534  * Since GLib 2.40, the lock protecting @cancellable is not held when
535  * @callback is invoked.  This lifts a restriction in place for
536  * earlier GLib versions which now makes it easier to write cleanup
537  * code that unconditionally invokes e.g. g_cancellable_cancel().
538  *
539  * Returns: The id of the signal handler or 0 if @cancellable has already
540  *          been cancelled.
541  *
542  * Since: 2.22
543  */
544 gulong
545 g_cancellable_connect (GCancellable   *cancellable,
546                        GCallback       callback,
547                        gpointer        data,
548                        GDestroyNotify  data_destroy_func)
549 {
550   gulong id;
551
552   g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), 0);
553
554   g_mutex_lock (&cancellable_mutex);
555
556   if (cancellable->priv->cancelled)
557     {
558       void (*_callback) (GCancellable *cancellable,
559                          gpointer      user_data);
560
561       g_mutex_unlock (&cancellable_mutex);
562
563       _callback = (void *)callback;
564       id = 0;
565
566       _callback (cancellable, data);
567
568       if (data_destroy_func)
569         data_destroy_func (data);
570     }
571   else
572     {
573       id = g_signal_connect_data (cancellable, "cancelled",
574                                   callback, data,
575                                   (GClosureNotify) data_destroy_func,
576                                   0);
577
578       g_mutex_unlock (&cancellable_mutex);
579     }
580
581
582   return id;
583 }
584
585 /**
586  * g_cancellable_disconnect:
587  * @cancellable: (allow-none): A #GCancellable or %NULL.
588  * @handler_id: Handler id of the handler to be disconnected, or %0.
589  *
590  * Disconnects a handler from a cancellable instance similar to
591  * g_signal_handler_disconnect().  Additionally, in the event that a
592  * signal handler is currently running, this call will block until the
593  * handler has finished.  Calling this function from a
594  * #GCancellable::cancelled signal handler will therefore result in a
595  * deadlock.
596  *
597  * This avoids a race condition where a thread cancels at the
598  * same time as the cancellable operation is finished and the
599  * signal handler is removed. See #GCancellable::cancelled for
600  * details on how to use this.
601  *
602  * If @cancellable is %NULL or @handler_id is %0 this function does
603  * nothing.
604  *
605  * Since: 2.22
606  */
607 void
608 g_cancellable_disconnect (GCancellable  *cancellable,
609                           gulong         handler_id)
610 {
611   GCancellablePrivate *priv;
612
613   if (handler_id == 0 ||  cancellable == NULL)
614     return;
615
616   g_mutex_lock (&cancellable_mutex);
617
618   priv = cancellable->priv;
619
620   while (priv->cancelled_running)
621     {
622       priv->cancelled_running_waiting = TRUE;
623       g_cond_wait (&cancellable_cond, &cancellable_mutex);
624     }
625
626   g_signal_handler_disconnect (cancellable, handler_id);
627
628   g_mutex_unlock (&cancellable_mutex);
629 }
630
631 typedef struct {
632   GSource       source;
633
634   GCancellable *cancellable;
635   guint         cancelled_handler;
636 } GCancellableSource;
637
638 static void
639 cancellable_source_cancelled (GCancellable *cancellable,
640                               gpointer      user_data)
641 {
642   GSource *source = user_data;
643
644   if (!g_source_is_destroyed (source))
645     g_source_set_ready_time (source, 0);
646 }
647
648 static gboolean
649 cancellable_source_dispatch (GSource     *source,
650                              GSourceFunc  callback,
651                              gpointer     user_data)
652 {
653   GCancellableSourceFunc func = (GCancellableSourceFunc)callback;
654   GCancellableSource *cancellable_source = (GCancellableSource *)source;
655
656   g_source_set_ready_time (source, -1);
657   return (*func) (cancellable_source->cancellable, user_data);
658 }
659
660 static void
661 cancellable_source_finalize (GSource *source)
662 {
663   GCancellableSource *cancellable_source = (GCancellableSource *)source;
664
665   if (cancellable_source->cancellable)
666     {
667       g_cancellable_disconnect (cancellable_source->cancellable,
668                                 cancellable_source->cancelled_handler);
669       g_object_unref (cancellable_source->cancellable);
670     }
671 }
672
673 static gboolean
674 cancellable_source_closure_callback (GCancellable *cancellable,
675                                      gpointer      data)
676 {
677   GClosure *closure = data;
678
679   GValue params = G_VALUE_INIT;
680   GValue result_value = G_VALUE_INIT;
681   gboolean result;
682
683   g_value_init (&result_value, G_TYPE_BOOLEAN);
684
685   g_value_init (&params, G_TYPE_CANCELLABLE);
686   g_value_set_object (&params, cancellable);
687
688   g_closure_invoke (closure, &result_value, 1, &params, NULL);
689
690   result = g_value_get_boolean (&result_value);
691   g_value_unset (&result_value);
692   g_value_unset (&params);
693
694   return result;
695 }
696
697 static GSourceFuncs cancellable_source_funcs =
698 {
699   NULL,
700   NULL,
701   cancellable_source_dispatch,
702   cancellable_source_finalize,
703   (GSourceFunc)cancellable_source_closure_callback,
704 };
705
706 /**
707  * g_cancellable_source_new: (skip)
708  * @cancellable: (allow-none): a #GCancellable, or %NULL
709  *
710  * Creates a source that triggers if @cancellable is cancelled and
711  * calls its callback of type #GCancellableSourceFunc. This is
712  * primarily useful for attaching to another (non-cancellable) source
713  * with g_source_add_child_source() to add cancellability to it.
714  *
715  * For convenience, you can call this with a %NULL #GCancellable,
716  * in which case the source will never trigger.
717  *
718  * Returns: (transfer full): the new #GSource.
719  *
720  * Since: 2.28
721  */
722 GSource *
723 g_cancellable_source_new (GCancellable *cancellable)
724 {
725   GSource *source;
726   GCancellableSource *cancellable_source;
727
728   source = g_source_new (&cancellable_source_funcs, sizeof (GCancellableSource));
729   g_source_set_name (source, "GCancellable");
730   cancellable_source = (GCancellableSource *)source;
731
732   if (cancellable)
733     {
734       cancellable_source->cancellable = g_object_ref (cancellable);
735
736       /* We intentionally don't use g_cancellable_connect() here,
737        * because we don't want the "at most once" behavior.
738        */
739       cancellable_source->cancelled_handler =
740         g_signal_connect (cancellable, "cancelled",
741                           G_CALLBACK (cancellable_source_cancelled),
742                           source);
743       if (g_cancellable_is_cancelled (cancellable))
744         g_source_set_ready_time (source, 0);
745     }
746
747   return source;
748 }