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