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