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