Clarify g_cancellable_push_current docs wrt cancellable being NULL (#575013)
[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 set_fd_close_exec (int fd)
193 {
194   int flags;
195
196   flags = fcntl (fd, F_GETFD, 0);
197   if (flags != -1 && (flags & FD_CLOEXEC) == 0)
198     {
199       flags |= FD_CLOEXEC;
200       fcntl (fd, F_SETFD, flags);
201     }
202 }
203
204
205 static void
206 g_cancellable_open_pipe (GCancellable *cancellable)
207 {
208   if (pipe (cancellable->cancel_pipe) == 0)
209     {
210       /* Make them nonblocking, just to be sure we don't block
211        * on errors and stuff
212        */
213       set_fd_nonblocking (cancellable->cancel_pipe[0]);
214       set_fd_nonblocking (cancellable->cancel_pipe[1]);
215       set_fd_close_exec (cancellable->cancel_pipe[0]);
216       set_fd_close_exec (cancellable->cancel_pipe[1]);
217     }
218   else
219     g_warning ("Failed to create pipe for GCancellable. Out of file descriptors?");
220 }
221 #endif
222
223 static void
224 g_cancellable_init (GCancellable *cancellable)
225 {
226   cancellable->cancel_pipe[0] = -1;
227   cancellable->cancel_pipe[1] = -1;
228 }
229
230 /**
231  * g_cancellable_new:
232  * 
233  * Creates a new #GCancellable object.
234  *
235  * Applications that want to start one or more operations
236  * that should be cancellable should create a #GCancellable
237  * and pass it to the operations.
238  *
239  * One #GCancellable can be used in multiple consecutive
240  * operations, but not in multiple concurrent operations.
241  *  
242  * Returns: a #GCancellable.
243  **/
244 GCancellable *
245 g_cancellable_new (void)
246 {
247   return g_object_new (G_TYPE_CANCELLABLE, NULL);
248 }
249
250 /**
251  * g_cancellable_push_current:
252  * @cancellable: a #GCancellable object
253  *
254  * Pushes @cancellable onto the cancellable stack. The current
255  * cancllable can then be recieved using g_cancellable_get_current().
256  *
257  * This is useful when implementing cancellable operations in
258  * code that does not allow you to pass down the cancellable object.
259  *
260  * This is typically called automatically by e.g. #GFile operations,
261  * so you rarely have to call this yourself.
262  **/
263 void
264 g_cancellable_push_current (GCancellable *cancellable)
265 {
266   GSList *l;
267
268   g_return_if_fail (cancellable != NULL);
269
270   l = g_static_private_get (&current_cancellable);
271   l = g_slist_prepend (l, cancellable);
272   g_static_private_set (&current_cancellable, l, NULL);
273 }
274
275 /**
276  * g_cancellable_pop_current:
277  * @cancellable: a #GCancellable object
278  *
279  * Pops @cancellable off the cancellable stack (verifying that @cancellable
280  * is on the top of the stack).
281  **/
282 void
283 g_cancellable_pop_current (GCancellable *cancellable)
284 {
285   GSList *l;
286
287   l = g_static_private_get (&current_cancellable);
288
289   g_return_if_fail (l != NULL);
290   g_return_if_fail (l->data == cancellable);
291
292   l = g_slist_delete_link (l, l);
293   g_static_private_set (&current_cancellable, l, NULL);
294 }
295
296 /**
297  * g_cancellable_get_current:
298  *
299  * Gets the top cancellable from the stack.
300  *
301  * Returns: a #GCancellable from the top of the stack, or %NULL
302  * if the stack is empty.
303  **/
304 GCancellable *
305 g_cancellable_get_current  (void)
306 {
307   GSList *l;
308
309   l = g_static_private_get (&current_cancellable);
310   if (l == NULL)
311     return NULL;
312
313   return G_CANCELLABLE (l->data);
314 }
315
316 /**
317  * g_cancellable_reset:
318  * @cancellable: a #GCancellable object.
319  * 
320  * Resets @cancellable to its uncancelled state. 
321  **/
322 void 
323 g_cancellable_reset (GCancellable *cancellable)
324 {
325   g_return_if_fail (G_IS_CANCELLABLE (cancellable));
326
327   G_LOCK(cancellable);
328   
329   if (cancellable->cancelled_running)
330     {
331       g_critical ("Can't reset a cancellable during an active operation");
332       G_UNLOCK(cancellable);
333       return;
334     }
335   
336   if (cancellable->cancelled)
337     {
338       char ch;
339       
340     /* Make sure we're not leaving old cancel state around */
341       
342 #ifdef G_OS_WIN32
343       if (cancellable->event)
344         ResetEvent (cancellable->event);
345       else
346 #endif
347       if (cancellable->cancel_pipe[0] != -1)
348         read (cancellable->cancel_pipe[0], &ch, 1);
349       cancellable->cancelled = FALSE;
350     }
351   G_UNLOCK(cancellable);
352 }
353
354 /**
355  * g_cancellable_is_cancelled:
356  * @cancellable: a #GCancellable or NULL.
357  * 
358  * Checks if a cancellable job has been cancelled.
359  * 
360  * Returns: %TRUE if @cancellable is cancelled, 
361  * FALSE if called with %NULL or if item is not cancelled. 
362  **/
363 gboolean
364 g_cancellable_is_cancelled (GCancellable *cancellable)
365 {
366   return cancellable != NULL && cancellable->cancelled;
367 }
368
369 /**
370  * g_cancellable_set_error_if_cancelled:
371  * @cancellable: a #GCancellable object.
372  * @error: #GError to append error state to.
373  * 
374  * If the @cancellable is cancelled, sets the error to notify
375  * that the operation was cancelled.
376  * 
377  * Returns: %TRUE if @cancellable was cancelled, %FALSE if it was not.
378  **/
379 gboolean
380 g_cancellable_set_error_if_cancelled (GCancellable  *cancellable,
381                                       GError       **error)
382 {
383   if (g_cancellable_is_cancelled (cancellable))
384     {
385       g_set_error_literal (error,
386                            G_IO_ERROR,
387                            G_IO_ERROR_CANCELLED,
388                            _("Operation was cancelled"));
389       return TRUE;
390     }
391   
392   return FALSE;
393 }
394
395 /**
396  * g_cancellable_get_fd:
397  * @cancellable: a #GCancellable.
398  * 
399  * Gets the file descriptor for a cancellable job. This can be used to
400  * implement cancellable operations on Unix systems. The returned fd will
401  * turn readable when @cancellable is cancelled.
402  *
403  * You are not supposed to read from the fd yourself, just check for
404  * readable status. Reading to unset the readable status is done
405  * with g_cancellable_reset().
406  * 
407  * See also g_cancellable_make_pollfd().
408  *
409  * Returns: A valid file descriptor. %-1 if the file descriptor 
410  * is not supported, or on errors. 
411  **/
412 int
413 g_cancellable_get_fd (GCancellable *cancellable)
414 {
415   int fd;
416   if (cancellable == NULL)
417     return -1;
418
419 #ifdef G_OS_WIN32
420   return -1;
421 #else
422   G_LOCK(cancellable);
423   if (!cancellable->allocated_pipe)
424     {
425       cancellable->allocated_pipe = TRUE;
426       g_cancellable_open_pipe (cancellable);
427     }
428
429   fd = cancellable->cancel_pipe[0];
430   G_UNLOCK(cancellable);
431 #endif
432
433   return fd;
434 }
435
436 /**
437  * g_cancellable_make_pollfd:
438  * @cancellable: a #GCancellable.
439  * @pollfd: a pointer to a #GPollFD
440  * 
441  * Creates a #GPollFD corresponding to @cancellable; this can be passed
442  * to g_poll() and used to poll for cancellation. This is useful both
443  * for unix systems without a native poll and for portability to
444  * windows.
445  *
446  * You are not supposed to read from the fd yourself, just check for
447  * readable status. Reading to unset the readable status is done
448  * with g_cancellable_reset().
449  * 
450  **/
451 void
452 g_cancellable_make_pollfd (GCancellable *cancellable, GPollFD *pollfd)
453 {
454   g_return_if_fail (G_IS_CANCELLABLE (cancellable));
455   g_return_if_fail (pollfd != NULL);
456
457 #ifdef G_OS_WIN32
458   if (!cancellable->event)
459     {
460       /* A manual reset anonymous event, starting unset */
461       cancellable->event = CreateEvent (NULL, TRUE, FALSE, NULL);
462     }
463   pollfd->fd = (gintptr)cancellable->event;
464 #else /* !G_OS_WIN32 */
465   pollfd->fd = g_cancellable_get_fd (cancellable);
466 #endif /* G_OS_WIN32 */
467   pollfd->events = G_IO_IN;
468   pollfd->revents = 0;
469 }
470
471 /**
472  * g_cancellable_cancel:
473  * @cancellable: a #GCancellable object.
474  * 
475  * Will set @cancellable to cancelled, and will emit the
476  * #GCancellable::cancelled signal. (However, see the warning about
477  * race conditions in the documentation for that signal if you are
478  * planning to connect to it.)
479  *
480  * This function is thread-safe. In other words, you can safely call
481  * it from a thread other than the one running the operation that was
482  * passed the @cancellable.
483  *
484  * The convention within gio is that cancelling an asynchronous
485  * operation causes it to complete asynchronously. That is, if you
486  * cancel the operation from the same thread in which it is running,
487  * then the operation's #GAsyncReadyCallback will not be invoked until
488  * the application returns to the main loop.
489  **/
490 void
491 g_cancellable_cancel (GCancellable *cancellable)
492 {
493   gboolean cancel;
494
495   cancel = FALSE;
496
497   G_LOCK(cancellable);
498   if (cancellable != NULL &&
499       !cancellable->cancelled)
500     {
501       char ch = 'x';
502       cancel = TRUE;
503       cancellable->cancelled = TRUE;
504       cancellable->cancelled_running = TRUE;
505 #ifdef G_OS_WIN32
506       if (cancellable->event)
507         SetEvent(cancellable->event);
508 #endif
509       if (cancellable->cancel_pipe[1] != -1)
510         write (cancellable->cancel_pipe[1], &ch, 1);
511     }
512   G_UNLOCK(cancellable);
513
514   if (cancel)
515     {
516       g_object_ref (cancellable);
517       g_signal_emit (cancellable, signals[CANCELLED], 0);
518
519       G_LOCK(cancellable);
520
521       cancellable->cancelled_running = FALSE;
522       if (cancellable->cancelled_running_waiting)
523         g_cond_broadcast (cancellable_cond);
524       cancellable->cancelled_running_waiting = FALSE;
525
526       G_UNLOCK(cancellable);
527
528       g_object_unref (cancellable);
529     }
530 }
531
532 /**
533  * g_cancellable_connect:
534  * @cancellable: A #GCancellable.
535  * @callback: The #GCallback to connect.
536  * @data: Data to pass to @callback.
537  * @data_destroy_func: Free function for @data or %NULL.
538  *
539  * Convenience function to connect to the #GCancellable::cancelled
540  * signal. Also handles the race condition that may happen
541  * if the cancellable is cancelled right before connecting.
542  *
543  * @callback is called at most once, either directly at the
544  * time of the connect if @cancellable is already cancelled,
545  * or when @cancellable is cancelled in some thread.
546  *
547  * @data_destroy_func will be called when the handler is
548  * disconnected, or immediately if the cancellable is already
549  * cancelled.
550  *
551  * See #GCancellable::cancelled for details on how to use this.
552  *
553  * Returns: The id of the signal handler or 0 if @cancellable has already
554  *          been cancelled.
555  *
556  * Since: 2.22
557  */
558 gulong
559 g_cancellable_connect (GCancellable   *cancellable,
560                        GCallback       callback,
561                        gpointer        data,
562                        GDestroyNotify  data_destroy_func)
563 {
564   gulong id;
565
566   g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), 0);
567
568   G_LOCK (cancellable);
569
570   if (cancellable->cancelled)
571     {
572       void (*_callback) (GCancellable *cancellable,
573                          gpointer      user_data);
574
575       _callback = (void *)callback;
576       id = 0;
577
578       _callback (cancellable, data);
579
580       if (data_destroy_func)
581         data_destroy_func (data);
582     }
583   else
584     {
585       id = g_signal_connect_data (cancellable, "cancelled",
586                                   callback, data,
587                                   (GClosureNotify) data_destroy_func,
588                                   0);
589     }
590   G_UNLOCK (cancellable);
591
592   return id;
593 }
594
595 /**
596  * g_cancellable_disconnect:
597  * @cancellable: A #GCancellable or %NULL.
598  * @handler_id: Handler id of the handler to be disconnected, or %0.
599  *
600  * Disconnects a handler from an cancellable instance similar to
601  * g_signal_handler_disconnect() but ensures that once this
602  * function returns the handler will not run anymore in any thread.
603  *
604  * This avoids a race condition where a thread cancels at the
605  * same time as the cancellable operation is finished and the
606  * signal handler is removed. See #GCancellable::cancelled for
607  * details on how to use this.
608  *
609  * If @cancellable is %NULL or @handler_id is %0 this function does
610  * nothing.
611  *
612  * Since: 2.22
613  */
614 void
615 g_cancellable_disconnect (GCancellable  *cancellable,
616                           gulong         handler_id)
617 {
618   if (handler_id == 0 ||  cancellable == NULL)
619     return;
620
621   G_LOCK (cancellable);
622   while (cancellable->cancelled_running)
623     {
624       cancellable->cancelled_running_waiting = TRUE;
625       g_cond_wait (cancellable_cond,
626                    g_static_mutex_get_mutex (& G_LOCK_NAME (cancellable)));
627     }
628
629   g_signal_handler_disconnect (cancellable, handler_id);
630   G_UNLOCK (cancellable);
631 }
632
633 #define __G_CANCELLABLE_C__
634 #include "gioaliasdef.c"