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