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