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