[gio] minor improvements to g_cancellable_cancel()
[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 #ifdef HAVE_UNISTD_H
25 #include <unistd.h>
26 #endif
27 #include <fcntl.h>
28 #include <gioerror.h>
29 #ifdef G_OS_WIN32
30 #include <windows.h>
31 #include <io.h>
32 #endif
33 #include "gcancellable.h"
34 #include "glibintl.h"
35
36 #include "gioalias.h"
37
38 /**
39  * SECTION:gcancellable
40  * @short_description: Thread-safe Operation Cancellation Stack
41  * @include: gio/gio.h
42  *
43  * GCancellable is a thread-safe operation cancellation stack used 
44  * throughout GIO to allow for cancellation of synchronous and
45  * asynchronous operations.
46  */
47
48 enum {
49   CANCELLED,
50   LAST_SIGNAL
51 };
52
53 struct _GCancellablePrivate
54 {
55   GObject parent_instance;
56
57   guint cancelled : 1;
58   guint allocated_pipe : 1;
59   guint cancelled_running : 1;
60   guint cancelled_running_waiting : 1;
61   int cancel_pipe[2];
62
63 #ifdef G_OS_WIN32
64   HANDLE event;
65 #endif
66 };
67
68 static guint signals[LAST_SIGNAL] = { 0 };
69
70 G_DEFINE_TYPE (GCancellable, g_cancellable, G_TYPE_OBJECT);
71
72 static GStaticPrivate current_cancellable = G_STATIC_PRIVATE_INIT;
73 G_LOCK_DEFINE_STATIC(cancellable);
74 static GCond *cancellable_cond = NULL;
75   
76 static void
77 g_cancellable_finalize (GObject *object)
78 {
79   GCancellable *cancellable = G_CANCELLABLE (object);
80   GCancellablePrivate *priv;
81
82   priv = cancellable->priv;
83
84   if (priv->cancel_pipe[0] != -1)
85     close (priv->cancel_pipe[0]);
86   
87   if (priv->cancel_pipe[1] != -1)
88     close (priv->cancel_pipe[1]);
89
90 #ifdef G_OS_WIN32
91   if (priv->event)
92     CloseHandle (priv->event);
93 #endif
94
95   G_OBJECT_CLASS (g_cancellable_parent_class)->finalize (object);
96 }
97
98 static void
99 g_cancellable_class_init (GCancellableClass *klass)
100 {
101   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
102
103   g_type_class_add_private (klass, sizeof (GCancellablePrivate));
104
105   if (cancellable_cond == NULL && g_thread_supported ())
106     cancellable_cond = g_cond_new ();
107   
108   gobject_class->finalize = g_cancellable_finalize;
109
110   /**
111    * GCancellable::cancelled:
112    * @cancellable: a #GCancellable.
113    * 
114    * Emitted when the operation has been cancelled.
115    * 
116    * Can be used by implementations of cancellable operations. If the
117    * operation is cancelled from another thread, the signal will be
118    * emitted in the thread that cancelled the operation, not the
119    * thread that is running the operation.
120    *
121    * Note that disconnecting from this signal (or any signal) in a
122    * multi-threaded program is prone to race conditions. For instance
123    * it is possible that a signal handler may be invoked even
124    * <emphasis>after</emphasis> a call to
125    * g_signal_handler_disconnect() for that handler has already
126    * returned.
127    * 
128    * There is also a problem when cancellation happen
129    * right before connecting to the signal. If this happens the
130    * signal will unexpectedly not be emitted, and checking before
131    * connecting to the signal leaves a race condition where this is
132    * still happening.
133    *
134    * In order to make it safe and easy to connect handlers there
135    * are two helper functions: g_cancellable_connect() and
136    * g_cancellable_disconnect() which protect against problems
137    * like this.
138    *
139    * An example of how to us this:
140    * |[
141    *     /<!-- -->* Make sure we don't do any unnecessary work if already cancelled *<!-- -->/
142    *     if (g_cancellable_set_error_if_cancelled (cancellable))
143    *       return;
144    *
145    *     /<!-- -->* Set up all the data needed to be able to
146    *      * handle cancellation of the operation *<!-- -->/
147    *     my_data = my_data_new (...);
148    *
149    *     id = 0;
150    *     if (cancellable)
151    *       id = g_cancellable_connect (cancellable,
152    *                                  G_CALLBACK (cancelled_handler)
153    *                                  data, NULL);
154    *
155    *     /<!-- -->* cancellable operation here... *<!-- -->/
156    *
157    *     g_cancellable_disconnect (cancellable, id);
158    *
159    *     /<!-- -->* cancelled_handler is never called after this, it
160    *      * is now safe to free the data *<!-- -->/
161    *     my_data_free (my_data);  
162    * ]|
163    *
164    * Note that the cancelled signal is emitted in the thread that
165    * the user cancelled from, which may be the main thread. So, the
166    * cancellable signal should not do something that can block.
167    */
168   signals[CANCELLED] =
169     g_signal_new (I_("cancelled"),
170                   G_TYPE_FROM_CLASS (gobject_class),
171                   G_SIGNAL_RUN_LAST,
172                   G_STRUCT_OFFSET (GCancellableClass, cancelled),
173                   NULL, NULL,
174                   g_cclosure_marshal_VOID__VOID,
175                   G_TYPE_NONE, 0);
176   
177 }
178
179 #ifndef G_OS_WIN32
180 static void
181 set_fd_nonblocking (int fd)
182 {
183 #ifdef F_GETFL
184   glong fcntl_flags;
185   fcntl_flags = fcntl (fd, F_GETFL);
186
187 #ifdef O_NONBLOCK
188   fcntl_flags |= O_NONBLOCK;
189 #else
190   fcntl_flags |= O_NDELAY;
191 #endif
192
193   fcntl (fd, F_SETFL, fcntl_flags);
194 #endif
195 }
196
197 static void
198 set_fd_close_exec (int fd)
199 {
200   int flags;
201
202   flags = fcntl (fd, F_GETFD, 0);
203   if (flags != -1 && (flags & FD_CLOEXEC) == 0)
204     {
205       flags |= FD_CLOEXEC;
206       fcntl (fd, F_SETFD, flags);
207     }
208 }
209
210
211 static void
212 g_cancellable_open_pipe (GCancellable *cancellable)
213 {
214   GCancellablePrivate *priv;
215
216   priv = cancellable->priv;
217   if (pipe (priv->cancel_pipe) == 0)
218     {
219       /* Make them nonblocking, just to be sure we don't block
220        * on errors and stuff
221        */
222       set_fd_nonblocking (priv->cancel_pipe[0]);
223       set_fd_nonblocking (priv->cancel_pipe[1]);
224       set_fd_close_exec (priv->cancel_pipe[0]);
225       set_fd_close_exec (priv->cancel_pipe[1]);
226     }
227   else
228     g_warning ("Failed to create pipe for GCancellable. Out of file descriptors?");
229 }
230 #endif
231
232 static void
233 g_cancellable_init (GCancellable *cancellable)
234 {
235   cancellable->priv = G_TYPE_INSTANCE_GET_PRIVATE (cancellable,
236                                                    G_TYPE_CANCELLABLE,
237                                                    GCancellablePrivate);
238   cancellable->priv->cancel_pipe[0] = -1;
239   cancellable->priv->cancel_pipe[1] = -1;
240 }
241
242 /**
243  * g_cancellable_new:
244  * 
245  * Creates a new #GCancellable object.
246  *
247  * Applications that want to start one or more operations
248  * that should be cancellable should create a #GCancellable
249  * and pass it to the operations.
250  *
251  * One #GCancellable can be used in multiple consecutive
252  * operations, but not in multiple concurrent operations.
253  *  
254  * Returns: a #GCancellable.
255  **/
256 GCancellable *
257 g_cancellable_new (void)
258 {
259   return g_object_new (G_TYPE_CANCELLABLE, NULL);
260 }
261
262 /**
263  * g_cancellable_push_current:
264  * @cancellable: a #GCancellable object
265  *
266  * Pushes @cancellable onto the cancellable stack. The current
267  * cancllable can then be recieved using g_cancellable_get_current().
268  *
269  * This is useful when implementing cancellable operations in
270  * code that does not allow you to pass down the cancellable object.
271  *
272  * This is typically called automatically by e.g. #GFile operations,
273  * so you rarely have to call this yourself.
274  **/
275 void
276 g_cancellable_push_current (GCancellable *cancellable)
277 {
278   GSList *l;
279
280   g_return_if_fail (cancellable != NULL);
281
282   l = g_static_private_get (&current_cancellable);
283   l = g_slist_prepend (l, cancellable);
284   g_static_private_set (&current_cancellable, l, NULL);
285 }
286
287 /**
288  * g_cancellable_pop_current:
289  * @cancellable: a #GCancellable object
290  *
291  * Pops @cancellable off the cancellable stack (verifying that @cancellable
292  * is on the top of the stack).
293  **/
294 void
295 g_cancellable_pop_current (GCancellable *cancellable)
296 {
297   GSList *l;
298
299   l = g_static_private_get (&current_cancellable);
300
301   g_return_if_fail (l != NULL);
302   g_return_if_fail (l->data == cancellable);
303
304   l = g_slist_delete_link (l, l);
305   g_static_private_set (&current_cancellable, l, NULL);
306 }
307
308 /**
309  * g_cancellable_get_current:
310  *
311  * Gets the top cancellable from the stack.
312  *
313  * Returns: a #GCancellable from the top of the stack, or %NULL
314  * if the stack is empty.
315  **/
316 GCancellable *
317 g_cancellable_get_current  (void)
318 {
319   GSList *l;
320
321   l = g_static_private_get (&current_cancellable);
322   if (l == NULL)
323     return NULL;
324
325   return G_CANCELLABLE (l->data);
326 }
327
328 /**
329  * g_cancellable_reset:
330  * @cancellable: a #GCancellable object.
331  * 
332  * Resets @cancellable to its uncancelled state. 
333  **/
334 void 
335 g_cancellable_reset (GCancellable *cancellable)
336 {
337   GCancellablePrivate *priv;
338
339   g_return_if_fail (G_IS_CANCELLABLE (cancellable));
340
341   G_LOCK(cancellable);
342
343   priv = cancellable->priv;
344   
345   while (priv->cancelled_running)
346     {
347       priv->cancelled_running_waiting = TRUE;
348       g_cond_wait (cancellable_cond,
349                    g_static_mutex_get_mutex (& G_LOCK_NAME (cancellable)));
350     }
351   
352   if (priv->cancelled)
353     {
354       char ch;
355       
356     /* Make sure we're not leaving old cancel state around */
357       
358 #ifdef G_OS_WIN32
359       if (priv->event)
360         ResetEvent (priv->event);
361       else
362 #endif
363       if (priv->cancel_pipe[0] != -1)
364         read (priv->cancel_pipe[0], &ch, 1);
365       priv->cancelled = FALSE;
366     }
367   G_UNLOCK(cancellable);
368 }
369
370 /**
371  * g_cancellable_is_cancelled:
372  * @cancellable: a #GCancellable or NULL.
373  * 
374  * Checks if a cancellable job has been cancelled.
375  * 
376  * Returns: %TRUE if @cancellable is cancelled, 
377  * FALSE if called with %NULL or if item is not cancelled. 
378  **/
379 gboolean
380 g_cancellable_is_cancelled (GCancellable *cancellable)
381 {
382   return cancellable != NULL && cancellable->priv->cancelled;
383 }
384
385 /**
386  * g_cancellable_set_error_if_cancelled:
387  * @cancellable: a #GCancellable object.
388  * @error: #GError to append error state to.
389  * 
390  * If the @cancellable is cancelled, sets the error to notify
391  * that the operation was cancelled.
392  * 
393  * Returns: %TRUE if @cancellable was cancelled, %FALSE if it was not.
394  **/
395 gboolean
396 g_cancellable_set_error_if_cancelled (GCancellable  *cancellable,
397                                       GError       **error)
398 {
399   if (g_cancellable_is_cancelled (cancellable))
400     {
401       g_set_error_literal (error,
402                            G_IO_ERROR,
403                            G_IO_ERROR_CANCELLED,
404                            _("Operation was cancelled"));
405       return TRUE;
406     }
407   
408   return FALSE;
409 }
410
411 /**
412  * g_cancellable_get_fd:
413  * @cancellable: a #GCancellable.
414  * 
415  * Gets the file descriptor for a cancellable job. This can be used to
416  * implement cancellable operations on Unix systems. The returned fd will
417  * turn readable when @cancellable is cancelled.
418  *
419  * You are not supposed to read from the fd yourself, just check for
420  * readable status. Reading to unset the readable status is done
421  * with g_cancellable_reset().
422  * 
423  * See also g_cancellable_make_pollfd().
424  *
425  * Returns: A valid file descriptor. %-1 if the file descriptor 
426  * is not supported, or on errors. 
427  **/
428 int
429 g_cancellable_get_fd (GCancellable *cancellable)
430 {
431   GCancellablePrivate *priv;
432
433   int fd;
434   if (cancellable == NULL)
435     return -1;
436
437   priv = cancellable->priv;
438
439 #ifdef G_OS_WIN32
440   return -1;
441 #else
442   G_LOCK(cancellable);
443   if (!priv->allocated_pipe)
444     {
445       priv->allocated_pipe = TRUE;
446       g_cancellable_open_pipe (cancellable);
447     }
448
449   fd = priv->cancel_pipe[0];
450   G_UNLOCK(cancellable);
451 #endif
452
453   return fd;
454 }
455
456 /**
457  * g_cancellable_make_pollfd:
458  * @cancellable: a #GCancellable.
459  * @pollfd: a pointer to a #GPollFD
460  * 
461  * Creates a #GPollFD corresponding to @cancellable; this can be passed
462  * to g_poll() and used to poll for cancellation. This is useful both
463  * for unix systems without a native poll and for portability to
464  * windows.
465  *
466  * You are not supposed to read from the fd yourself, just check for
467  * readable status. Reading to unset the readable status is done
468  * with g_cancellable_reset().
469  * 
470  **/
471 void
472 g_cancellable_make_pollfd (GCancellable *cancellable, GPollFD *pollfd)
473 {
474   GCancellablePrivate *priv;
475
476   g_return_if_fail (G_IS_CANCELLABLE (cancellable));
477   g_return_if_fail (pollfd != NULL);
478
479   priv = cancellable->priv;
480
481 #ifdef G_OS_WIN32
482   if (!priv->event)
483     {
484       /* A manual reset anonymous event, starting unset */
485       priv->event = CreateEvent (NULL, TRUE, FALSE, NULL);
486     }
487   pollfd->fd = (gintptr)priv->event;
488 #else /* !G_OS_WIN32 */
489   pollfd->fd = g_cancellable_get_fd (cancellable);
490 #endif /* G_OS_WIN32 */
491   pollfd->events = G_IO_IN;
492   pollfd->revents = 0;
493 }
494
495 /**
496  * g_cancellable_cancel:
497  * @cancellable: a #GCancellable object.
498  * 
499  * Will set @cancellable to cancelled, and will emit the
500  * #GCancellable::cancelled signal. (However, see the warning about
501  * race conditions in the documentation for that signal if you are
502  * planning to connect to it.)
503  *
504  * This function is thread-safe. In other words, you can safely call
505  * it from a thread other than the one running the operation that was
506  * passed the @cancellable.
507  *
508  * The convention within gio is that cancelling an asynchronous
509  * operation causes it to complete asynchronously. That is, if you
510  * cancel the operation from the same thread in which it is running,
511  * then the operation's #GAsyncReadyCallback will not be invoked until
512  * the application returns to the main loop.
513  **/
514 void
515 g_cancellable_cancel (GCancellable *cancellable)
516 {
517   static const char ch = 'x';
518   gboolean cancel;
519   GCancellablePrivate *priv;
520
521   if (cancellable == NULL ||
522       priv->cancelled)
523     return;
524
525   priv = cancellable->priv;
526   cancel = FALSE;
527
528   G_LOCK(cancellable);
529   cancel = TRUE;
530   priv->cancelled = TRUE;
531   priv->cancelled_running = TRUE;
532 #ifdef G_OS_WIN32
533   if (priv->event)
534     SetEvent(priv->event);
535 #endif
536   if (priv->cancel_pipe[1] != -1)
537     write (priv->cancel_pipe[1], &ch, 1);
538   G_UNLOCK(cancellable);
539
540   if (cancel)
541     {
542       g_object_ref (cancellable);
543       g_signal_emit (cancellable, signals[CANCELLED], 0);
544
545       G_LOCK(cancellable);
546
547       priv->cancelled_running = FALSE;
548       if (priv->cancelled_running_waiting)
549         g_cond_broadcast (cancellable_cond);
550       priv->cancelled_running_waiting = FALSE;
551
552       G_UNLOCK(cancellable);
553
554       g_object_unref (cancellable);
555     }
556 }
557
558 /**
559  * g_cancellable_connect:
560  * @cancellable: A #GCancellable.
561  * @callback: The #GCallback to connect.
562  * @data: Data to pass to @callback.
563  * @data_destroy_func: Free function for @data or %NULL.
564  *
565  * Convenience function to connect to the #GCancellable::cancelled
566  * signal. Also handles the race condition that may happen
567  * if the cancellable is cancelled right before connecting.
568  *
569  * @callback is called at most once, either directly at the
570  * time of the connect if @cancellable is already cancelled,
571  * or when @cancellable is cancelled in some thread.
572  *
573  * @data_destroy_func will be called when the handler is
574  * disconnected, or immediately if the cancellable is already
575  * cancelled.
576  *
577  * See #GCancellable::cancelled for details on how to use this.
578  *
579  * Returns: The id of the signal handler or 0 if @cancellable has already
580  *          been cancelled.
581  *
582  * Since: 2.22
583  */
584 gulong
585 g_cancellable_connect (GCancellable   *cancellable,
586                        GCallback       callback,
587                        gpointer        data,
588                        GDestroyNotify  data_destroy_func)
589 {
590   gulong id;
591
592   g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), 0);
593
594   G_LOCK (cancellable);
595
596   if (cancellable->priv->cancelled)
597     {
598       void (*_callback) (GCancellable *cancellable,
599                          gpointer      user_data);
600
601       _callback = (void *)callback;
602       id = 0;
603
604       _callback (cancellable, data);
605
606       if (data_destroy_func)
607         data_destroy_func (data);
608     }
609   else
610     {
611       id = g_signal_connect_data (cancellable, "cancelled",
612                                   callback, data,
613                                   (GClosureNotify) data_destroy_func,
614                                   0);
615     }
616   G_UNLOCK (cancellable);
617
618   return id;
619 }
620
621 /**
622  * g_cancellable_disconnect:
623  * @cancellable: A #GCancellable or %NULL.
624  * @handler_id: Handler id of the handler to be disconnected, or %0.
625  *
626  * Disconnects a handler from an cancellable instance similar to
627  * g_signal_handler_disconnect() but ensures that once this
628  * function returns the handler will not run anymore in any thread.
629  *
630  * This avoids a race condition where a thread cancels at the
631  * same time as the cancellable operation is finished and the
632  * signal handler is removed. See #GCancellable::cancelled for
633  * details on how to use this.
634  *
635  * If @cancellable is %NULL or @handler_id is %0 this function does
636  * nothing.
637  *
638  * Since: 2.22
639  */
640 void
641 g_cancellable_disconnect (GCancellable  *cancellable,
642                           gulong         handler_id)
643 {
644   GCancellablePrivate *priv;
645
646   if (handler_id == 0 ||  cancellable == NULL)
647     return;
648
649   G_LOCK (cancellable);
650
651   priv = cancellable->priv;
652
653   while (priv->cancelled_running)
654     {
655       priv->cancelled_running_waiting = TRUE;
656       g_cond_wait (cancellable_cond,
657                    g_static_mutex_get_mutex (& G_LOCK_NAME (cancellable)));
658     }
659
660   g_signal_handler_disconnect (cancellable, handler_id);
661   G_UNLOCK (cancellable);
662 }
663
664 #define __G_CANCELLABLE_C__
665 #include "gioaliasdef.c"