G_LOCK: port from GStaticMutex to GMutex
[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, &G_LOCK_NAME (cancellable));
274     }
275
276   if (priv->cancelled)
277     {
278       if (priv->wakeup)
279         GLIB_PRIVATE_CALL (g_wakeup_acknowledge) (priv->wakeup);
280
281       priv->cancelled = FALSE;
282     }
283   G_UNLOCK(cancellable);
284 }
285
286 /**
287  * g_cancellable_is_cancelled:
288  * @cancellable: (allow-none): a #GCancellable or %NULL
289  *
290  * Checks if a cancellable job has been cancelled.
291  *
292  * Returns: %TRUE if @cancellable is cancelled,
293  * FALSE if called with %NULL or if item is not cancelled.
294  **/
295 gboolean
296 g_cancellable_is_cancelled (GCancellable *cancellable)
297 {
298   return cancellable != NULL && cancellable->priv->cancelled;
299 }
300
301 /**
302  * g_cancellable_set_error_if_cancelled:
303  * @cancellable: (allow-none): a #GCancellable or %NULL
304  * @error: #GError to append error state to
305  *
306  * If the @cancellable is cancelled, sets the error to notify
307  * that the operation was cancelled.
308  *
309  * Returns: %TRUE if @cancellable was cancelled, %FALSE if it was not
310  */
311 gboolean
312 g_cancellable_set_error_if_cancelled (GCancellable  *cancellable,
313                                       GError       **error)
314 {
315   if (g_cancellable_is_cancelled (cancellable))
316     {
317       g_set_error_literal (error,
318                            G_IO_ERROR,
319                            G_IO_ERROR_CANCELLED,
320                            _("Operation was cancelled"));
321       return TRUE;
322     }
323
324   return FALSE;
325 }
326
327 /**
328  * g_cancellable_get_fd:
329  * @cancellable: a #GCancellable.
330  * 
331  * Gets the file descriptor for a cancellable job. This can be used to
332  * implement cancellable operations on Unix systems. The returned fd will
333  * turn readable when @cancellable is cancelled.
334  *
335  * You are not supposed to read from the fd yourself, just check for
336  * readable status. Reading to unset the readable status is done
337  * with g_cancellable_reset().
338  * 
339  * After a successful return from this function, you should use 
340  * g_cancellable_release_fd() to free up resources allocated for 
341  * the returned file descriptor.
342  *
343  * See also g_cancellable_make_pollfd().
344  *
345  * Returns: A valid file descriptor. %-1 if the file descriptor 
346  * is not supported, or on errors. 
347  **/
348 int
349 g_cancellable_get_fd (GCancellable *cancellable)
350 {
351   GPollFD pollfd;
352
353   if (cancellable == NULL)
354           return -1;
355
356 #ifdef G_OS_WIN32
357   pollfd.fd = -1;
358 #else
359   g_cancellable_make_pollfd (cancellable, &pollfd);
360 #endif
361
362   return pollfd.fd;
363 }
364
365 /**
366  * g_cancellable_make_pollfd:
367  * @cancellable: a #GCancellable or %NULL
368  * @pollfd: a pointer to a #GPollFD
369  * 
370  * Creates a #GPollFD corresponding to @cancellable; this can be passed
371  * to g_poll() and used to poll for cancellation. This is useful both
372  * for unix systems without a native poll and for portability to
373  * windows.
374  *
375  * When this function returns %TRUE, you should use 
376  * g_cancellable_release_fd() to free up resources allocated for the 
377  * @pollfd. After a %FALSE return, do not call g_cancellable_release_fd().
378  *
379  * If this function returns %FALSE, either no @cancellable was given or
380  * resource limits prevent this function from allocating the necessary 
381  * structures for polling. (On Linux, you will likely have reached 
382  * the maximum number of file descriptors.) The suggested way to handle
383  * these cases is to ignore the @cancellable.
384  *
385  * You are not supposed to read from the fd yourself, just check for
386  * readable status. Reading to unset the readable status is done
387  * with g_cancellable_reset().
388  *
389  * Returns: %TRUE if @pollfd was successfully initialized, %FALSE on 
390  *          failure to prepare the cancellable.
391  * 
392  * Since: 2.22
393  **/
394 gboolean
395 g_cancellable_make_pollfd (GCancellable *cancellable, GPollFD *pollfd)
396 {
397   g_return_val_if_fail (pollfd != NULL, FALSE);
398   if (cancellable == NULL)
399     return FALSE;
400   g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), FALSE);
401
402   G_LOCK(cancellable);
403
404   cancellable->priv->fd_refcount++;
405
406   if (cancellable->priv->wakeup == NULL)
407     {
408       cancellable->priv->wakeup = GLIB_PRIVATE_CALL (g_wakeup_new) ();
409
410       if (cancellable->priv->cancelled)
411         GLIB_PRIVATE_CALL (g_wakeup_signal) (cancellable->priv->wakeup);
412     }
413
414   GLIB_PRIVATE_CALL (g_wakeup_get_pollfd) (cancellable->priv->wakeup, pollfd);
415
416   G_UNLOCK(cancellable);
417
418   return TRUE;
419 }
420
421 /**
422  * g_cancellable_release_fd:
423  * @cancellable: a #GCancellable
424  *
425  * Releases a resources previously allocated by g_cancellable_get_fd()
426  * or g_cancellable_make_pollfd().
427  *
428  * For compatibility reasons with older releases, calling this function 
429  * is not strictly required, the resources will be automatically freed
430  * when the @cancellable is finalized. However, the @cancellable will
431  * block scarce file descriptors until it is finalized if this function
432  * is not called. This can cause the application to run out of file 
433  * descriptors when many #GCancellables are used at the same time.
434  * 
435  * Since: 2.22
436  **/
437 void
438 g_cancellable_release_fd (GCancellable *cancellable)
439 {
440   GCancellablePrivate *priv;
441
442   if (cancellable == NULL)
443     return;
444
445   g_return_if_fail (G_IS_CANCELLABLE (cancellable));
446   g_return_if_fail (cancellable->priv->fd_refcount > 0);
447
448   priv = cancellable->priv;
449
450   G_LOCK (cancellable);
451   priv->fd_refcount--;
452   if (priv->fd_refcount == 0)
453     {
454       GLIB_PRIVATE_CALL (g_wakeup_free) (priv->wakeup);
455       priv->wakeup = NULL;
456     }
457   G_UNLOCK (cancellable);
458 }
459
460 /**
461  * g_cancellable_cancel:
462  * @cancellable: a #GCancellable object.
463  * 
464  * Will set @cancellable to cancelled, and will emit the
465  * #GCancellable::cancelled signal. (However, see the warning about
466  * race conditions in the documentation for that signal if you are
467  * planning to connect to it.)
468  *
469  * This function is thread-safe. In other words, you can safely call
470  * it from a thread other than the one running the operation that was
471  * passed the @cancellable.
472  *
473  * The convention within gio is that cancelling an asynchronous
474  * operation causes it to complete asynchronously. That is, if you
475  * cancel the operation from the same thread in which it is running,
476  * then the operation's #GAsyncReadyCallback will not be invoked until
477  * the application returns to the main loop.
478  **/
479 void
480 g_cancellable_cancel (GCancellable *cancellable)
481 {
482   GCancellablePrivate *priv;
483
484   if (cancellable == NULL ||
485       cancellable->priv->cancelled)
486     return;
487
488   priv = cancellable->priv;
489
490   G_LOCK(cancellable);
491   if (priv->cancelled)
492     {
493       G_UNLOCK (cancellable);
494       return;
495     }
496
497   priv->cancelled = TRUE;
498   priv->cancelled_running = TRUE;
499
500   if (priv->wakeup)
501     GLIB_PRIVATE_CALL (g_wakeup_signal) (priv->wakeup);
502
503   G_UNLOCK(cancellable);
504
505   g_object_ref (cancellable);
506   g_signal_emit (cancellable, signals[CANCELLED], 0);
507
508   G_LOCK(cancellable);
509
510   priv->cancelled_running = FALSE;
511   if (priv->cancelled_running_waiting)
512     g_cond_broadcast (cancellable_cond);
513   priv->cancelled_running_waiting = FALSE;
514
515   G_UNLOCK(cancellable);
516
517   g_object_unref (cancellable);
518 }
519
520 /**
521  * g_cancellable_connect:
522  * @cancellable: A #GCancellable.
523  * @callback: The #GCallback to connect.
524  * @data: Data to pass to @callback.
525  * @data_destroy_func: Free function for @data or %NULL.
526  *
527  * Convenience function to connect to the #GCancellable::cancelled
528  * signal. Also handles the race condition that may happen
529  * if the cancellable is cancelled right before connecting.
530  *
531  * @callback is called at most once, either directly at the
532  * time of the connect if @cancellable is already cancelled,
533  * or when @cancellable is cancelled in some thread.
534  *
535  * @data_destroy_func will be called when the handler is
536  * disconnected, or immediately if the cancellable is already
537  * cancelled.
538  *
539  * See #GCancellable::cancelled for details on how to use this.
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_LOCK (cancellable);
557
558   if (cancellable->priv->cancelled)
559     {
560       void (*_callback) (GCancellable *cancellable,
561                          gpointer      user_data);
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_UNLOCK (cancellable);
579
580   return id;
581 }
582
583 /**
584  * g_cancellable_disconnect:
585  * @cancellable: A #GCancellable or %NULL.
586  * @handler_id: Handler id of the handler to be disconnected, or %0.
587  *
588  * Disconnects a handler from a cancellable instance similar to
589  * g_signal_handler_disconnect().  Additionally, in the event that a
590  * signal handler is currently running, this call will block until the
591  * handler has finished.  Calling this function from a
592  * #GCancellable::cancelled signal handler will therefore result in a
593  * deadlock.
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  * If @cancellable is %NULL or @handler_id is %0 this function does
601  * nothing.
602  *
603  * Since: 2.22
604  */
605 void
606 g_cancellable_disconnect (GCancellable  *cancellable,
607                           gulong         handler_id)
608 {
609   GCancellablePrivate *priv;
610
611   if (handler_id == 0 ||  cancellable == NULL)
612     return;
613
614   G_LOCK (cancellable);
615
616   priv = cancellable->priv;
617
618   while (priv->cancelled_running)
619     {
620       priv->cancelled_running_waiting = TRUE;
621       g_cond_wait (cancellable_cond, &G_LOCK_NAME (cancellable));
622     }
623
624   g_signal_handler_disconnect (cancellable, handler_id);
625   G_UNLOCK (cancellable);
626 }
627
628 typedef struct {
629   GSource       source;
630
631   GCancellable *cancellable;
632   GPollFD       pollfd;
633 } GCancellableSource;
634
635 static gboolean
636 cancellable_source_prepare (GSource *source,
637                             gint    *timeout)
638 {
639   GCancellableSource *cancellable_source = (GCancellableSource *)source;
640
641   *timeout = -1;
642   return g_cancellable_is_cancelled (cancellable_source->cancellable);
643 }
644
645 static gboolean
646 cancellable_source_check (GSource *source)
647 {
648   GCancellableSource *cancellable_source = (GCancellableSource *)source;
649
650   return g_cancellable_is_cancelled (cancellable_source->cancellable);
651 }
652
653 static gboolean
654 cancellable_source_dispatch (GSource     *source,
655                              GSourceFunc  callback,
656                              gpointer     user_data)
657 {
658   GCancellableSourceFunc func = (GCancellableSourceFunc)callback;
659   GCancellableSource *cancellable_source = (GCancellableSource *)source;
660
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     g_object_unref (cancellable_source->cancellable);
671 }
672
673 static gboolean
674 cancellable_source_closure_callback (GCancellable *cancellable,
675                                      gpointer      data)
676 {
677   GClosure *closure = data;
678
679   GValue params = { 0, };
680   GValue result_value = { 0, };
681   gboolean result;
682
683   g_value_init (&result_value, G_TYPE_BOOLEAN);
684
685   g_value_init (&params, G_TYPE_CANCELLABLE);
686   g_value_set_object (&params, cancellable);
687
688   g_closure_invoke (closure, &result_value, 1, &params, NULL);
689
690   result = g_value_get_boolean (&result_value);
691   g_value_unset (&result_value);
692   g_value_unset (&params);
693
694   return result;
695 }
696
697 static GSourceFuncs cancellable_source_funcs =
698 {
699   cancellable_source_prepare,
700   cancellable_source_check,
701   cancellable_source_dispatch,
702   cancellable_source_finalize,
703   (GSourceFunc)cancellable_source_closure_callback,
704   (GSourceDummyMarshal)g_cclosure_marshal_generic,
705 };
706
707 /**
708  * g_cancellable_source_new: (skip)
709  * @cancellable: a #GCancellable, or %NULL
710  *
711  * Creates a source that triggers if @cancellable is cancelled and
712  * calls its callback of type #GCancellableSourceFunc. This is
713  * primarily useful for attaching to another (non-cancellable) source
714  * with g_source_add_child_source() to add cancellability to it.
715  *
716  * For convenience, you can call this with a %NULL #GCancellable,
717  * in which case the source will never trigger.
718  *
719  * Return value: (transfer full): the new #GSource.
720  *
721  * Since: 2.28
722  */
723 GSource *
724 g_cancellable_source_new (GCancellable *cancellable)
725 {
726   GSource *source;
727   GCancellableSource *cancellable_source;
728
729   source = g_source_new (&cancellable_source_funcs, sizeof (GCancellableSource));
730   g_source_set_name (source, "GCancellable");
731   cancellable_source = (GCancellableSource *)source;
732
733   if (g_cancellable_make_pollfd (cancellable,
734                                  &cancellable_source->pollfd))
735     {
736       cancellable_source->cancellable = g_object_ref (cancellable);
737       g_source_add_poll (source, &cancellable_source->pollfd);
738     }
739
740   return source;
741 }