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