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