GCancellable: Use Linux eventfd() instead of pipe
[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 #include "glib.h"
25 #ifdef G_OS_UNIX
26 #include "glib-unix.h"
27 #ifdef HAVE_EVENTFD
28 #include <sys/eventfd.h>
29 #endif
30 #endif
31 #include <gioerror.h>
32 #ifdef G_OS_WIN32
33 #include <errno.h>
34 #include <windows.h>
35 #include <io.h>
36 #endif
37 #include "gcancellable.h"
38 #include "glibintl.h"
39
40
41 /**
42  * SECTION:gcancellable
43  * @short_description: Thread-safe Operation Cancellation Stack
44  * @include: gio/gio.h
45  *
46  * GCancellable is a thread-safe operation cancellation stack used 
47  * throughout GIO to allow for cancellation of synchronous and
48  * asynchronous operations.
49  */
50
51 enum {
52   CANCELLED,
53   LAST_SIGNAL
54 };
55
56 struct _GCancellablePrivate
57 {
58   guint cancelled : 1;
59   guint cancelled_running : 1;
60   guint cancelled_running_waiting : 1;
61
62   guint fd_refcount;
63   /* If cancel_pipe[0] is != -1 and cancel_pipe[1] is -1, it is an eventfd */
64   int cancel_pipe[2];
65
66 #ifdef G_OS_WIN32
67   HANDLE event;
68 #endif
69 };
70
71 static guint signals[LAST_SIGNAL] = { 0 };
72
73 G_DEFINE_TYPE (GCancellable, g_cancellable, G_TYPE_OBJECT);
74
75 static GStaticPrivate current_cancellable = G_STATIC_PRIVATE_INIT;
76 G_LOCK_DEFINE_STATIC(cancellable);
77 static GCond *cancellable_cond = NULL;
78   
79 static void
80 g_cancellable_close_pipe (GCancellable *cancellable)
81 {
82   GCancellablePrivate *priv;
83   
84   priv = cancellable->priv;
85
86   if (priv->cancel_pipe[0] != -1)
87     {
88       close (priv->cancel_pipe[0]);
89       priv->cancel_pipe[0] = -1;
90     }
91   
92   if (priv->cancel_pipe[1] != -1)
93     {
94       close (priv->cancel_pipe[1]);
95       priv->cancel_pipe[1] = -1;
96     }
97
98 #ifdef G_OS_WIN32
99   if (priv->event)
100     {
101       CloseHandle (priv->event);
102       priv->event = NULL;
103     }
104 #endif
105 }
106
107 static void
108 g_cancellable_finalize (GObject *object)
109 {
110   GCancellable *cancellable = G_CANCELLABLE (object);
111
112   g_cancellable_close_pipe (cancellable);
113
114   G_OBJECT_CLASS (g_cancellable_parent_class)->finalize (object);
115 }
116
117 static void
118 g_cancellable_class_init (GCancellableClass *klass)
119 {
120   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
121
122   g_type_class_add_private (klass, sizeof (GCancellablePrivate));
123
124   if (cancellable_cond == NULL && g_thread_supported ())
125     cancellable_cond = g_cond_new ();
126   
127   gobject_class->finalize = g_cancellable_finalize;
128
129   /**
130    * GCancellable::cancelled:
131    * @cancellable: a #GCancellable.
132    * 
133    * Emitted when the operation has been cancelled.
134    * 
135    * Can be used by implementations of cancellable operations. If the
136    * operation is cancelled from another thread, the signal will be
137    * emitted in the thread that cancelled the operation, not the
138    * thread that is running the operation.
139    *
140    * Note that disconnecting from this signal (or any signal) in a
141    * multi-threaded program is prone to race conditions. For instance
142    * it is possible that a signal handler may be invoked even
143    * <emphasis>after</emphasis> a call to
144    * g_signal_handler_disconnect() for that handler has already
145    * returned.
146    * 
147    * There is also a problem when cancellation happen
148    * right before connecting to the signal. If this happens the
149    * signal will unexpectedly not be emitted, and checking before
150    * connecting to the signal leaves a race condition where this is
151    * still happening.
152    *
153    * In order to make it safe and easy to connect handlers there
154    * are two helper functions: g_cancellable_connect() and
155    * g_cancellable_disconnect() which protect against problems
156    * like this.
157    *
158    * An example of how to us this:
159    * |[
160    *     /<!-- -->* Make sure we don't do any unnecessary work if already cancelled *<!-- -->/
161    *     if (g_cancellable_set_error_if_cancelled (cancellable))
162    *       return;
163    *
164    *     /<!-- -->* Set up all the data needed to be able to
165    *      * handle cancellation of the operation *<!-- -->/
166    *     my_data = my_data_new (...);
167    *
168    *     id = 0;
169    *     if (cancellable)
170    *       id = g_cancellable_connect (cancellable,
171    *                                  G_CALLBACK (cancelled_handler)
172    *                                  data, NULL);
173    *
174    *     /<!-- -->* cancellable operation here... *<!-- -->/
175    *
176    *     g_cancellable_disconnect (cancellable, id);
177    *
178    *     /<!-- -->* cancelled_handler is never called after this, it
179    *      * is now safe to free the data *<!-- -->/
180    *     my_data_free (my_data);  
181    * ]|
182    *
183    * Note that the cancelled signal is emitted in the thread that
184    * the user cancelled from, which may be the main thread. So, the
185    * cancellable signal should not do something that can block.
186    */
187   signals[CANCELLED] =
188     g_signal_new (I_("cancelled"),
189                   G_TYPE_FROM_CLASS (gobject_class),
190                   G_SIGNAL_RUN_LAST,
191                   G_STRUCT_OFFSET (GCancellableClass, cancelled),
192                   NULL, NULL,
193                   g_cclosure_marshal_VOID__VOID,
194                   G_TYPE_NONE, 0);
195   
196 }
197
198 #ifndef G_OS_WIN32
199
200 static void
201 g_cancellable_write_cancelled (GCancellable *cancellable)
202 {
203   gssize c;
204   GCancellablePrivate *priv;
205   const char ch = 'x';
206
207   priv = cancellable->priv;
208
209   if (priv->cancel_pipe[0] == -1)
210     return;
211
212   g_assert (cancellable->priv->cancelled);
213
214 #ifdef HAVE_EVENTFD
215   if (priv->cancel_pipe[1] == -1)
216     {
217       guint64 buf = 1;
218       
219       do 
220         c = write (priv->cancel_pipe[0], &buf, sizeof (buf));
221       while (c == -1 && errno == EINTR);
222
223       return;
224     }
225 #endif
226
227   do
228     c = write (priv->cancel_pipe[1], &ch, 1);
229   while (c == -1 && errno == EINTR);
230 }
231
232 static void
233 g_cancellable_open_pipe (GCancellable *cancellable)
234 {
235   GCancellablePrivate *priv;
236
237   priv = cancellable->priv;
238 #ifdef HAVE_EVENTFD
239   priv->cancel_pipe[0] = eventfd (0, EFD_CLOEXEC | EFD_NONBLOCK);
240   if (priv->cancel_pipe[0] >= 0)
241     {
242       if (priv->cancelled)
243         g_cancellable_write_cancelled (cancellable);
244       return;
245     }
246   else if (errno != ENOSYS)
247     return;
248   /* Fall through on ENOSYS */
249 #endif
250   if (g_unix_open_pipe (priv->cancel_pipe, FD_CLOEXEC, NULL))
251     {
252       /* Make them nonblocking, just to be sure we don't block
253        * on errors and stuff
254        */
255       g_unix_set_fd_nonblocking (priv->cancel_pipe[0], TRUE, NULL);
256       g_unix_set_fd_nonblocking (priv->cancel_pipe[1], TRUE, NULL);
257       
258       if (priv->cancelled)
259         g_cancellable_write_cancelled (cancellable);
260     }
261 }
262 #endif
263
264 static void
265 g_cancellable_init (GCancellable *cancellable)
266 {
267   cancellable->priv = G_TYPE_INSTANCE_GET_PRIVATE (cancellable,
268                                                    G_TYPE_CANCELLABLE,
269                                                    GCancellablePrivate);
270   cancellable->priv->cancel_pipe[0] = -1;
271   cancellable->priv->cancel_pipe[1] = -1;
272 }
273
274 /**
275  * g_cancellable_new:
276  * 
277  * Creates a new #GCancellable object.
278  *
279  * Applications that want to start one or more operations
280  * that should be cancellable should create a #GCancellable
281  * and pass it to the operations.
282  *
283  * One #GCancellable can be used in multiple consecutive
284  * operations, but not in multiple concurrent operations.
285  *  
286  * Returns: a #GCancellable.
287  **/
288 GCancellable *
289 g_cancellable_new (void)
290 {
291   return g_object_new (G_TYPE_CANCELLABLE, NULL);
292 }
293
294 /**
295  * g_cancellable_push_current:
296  * @cancellable: a #GCancellable object
297  *
298  * Pushes @cancellable onto the cancellable stack. The current
299  * cancellable can then be recieved using g_cancellable_get_current().
300  *
301  * This is useful when implementing cancellable operations in
302  * code that does not allow you to pass down the cancellable object.
303  *
304  * This is typically called automatically by e.g. #GFile operations,
305  * so you rarely have to call this yourself.
306  **/
307 void
308 g_cancellable_push_current (GCancellable *cancellable)
309 {
310   GSList *l;
311
312   g_return_if_fail (cancellable != NULL);
313
314   l = g_static_private_get (&current_cancellable);
315   l = g_slist_prepend (l, cancellable);
316   g_static_private_set (&current_cancellable, l, NULL);
317 }
318
319 /**
320  * g_cancellable_pop_current:
321  * @cancellable: a #GCancellable object
322  *
323  * Pops @cancellable off the cancellable stack (verifying that @cancellable
324  * is on the top of the stack).
325  **/
326 void
327 g_cancellable_pop_current (GCancellable *cancellable)
328 {
329   GSList *l;
330
331   l = g_static_private_get (&current_cancellable);
332
333   g_return_if_fail (l != NULL);
334   g_return_if_fail (l->data == cancellable);
335
336   l = g_slist_delete_link (l, l);
337   g_static_private_set (&current_cancellable, l, NULL);
338 }
339
340 /**
341  * g_cancellable_get_current:
342  *
343  * Gets the top cancellable from the stack.
344  *
345  * Returns: (transfer none): a #GCancellable from the top of the stack, or %NULL
346  * if the stack is empty.
347  **/
348 GCancellable *
349 g_cancellable_get_current  (void)
350 {
351   GSList *l;
352
353   l = g_static_private_get (&current_cancellable);
354   if (l == NULL)
355     return NULL;
356
357   return G_CANCELLABLE (l->data);
358 }
359
360 /**
361  * g_cancellable_reset:
362  * @cancellable: a #GCancellable object.
363  * 
364  * Resets @cancellable to its uncancelled state. 
365  **/
366 void 
367 g_cancellable_reset (GCancellable *cancellable)
368 {
369   GCancellablePrivate *priv;
370
371   g_return_if_fail (G_IS_CANCELLABLE (cancellable));
372
373   G_LOCK(cancellable);
374
375   priv = cancellable->priv;
376   
377   while (priv->cancelled_running)
378     {
379       priv->cancelled_running_waiting = TRUE;
380       g_cond_wait (cancellable_cond,
381                    g_static_mutex_get_mutex (& G_LOCK_NAME (cancellable)));
382     }
383   
384   if (priv->cancelled)
385     {
386     /* Make sure we're not leaving old cancel state around */
387       
388 #ifdef G_OS_WIN32
389       if (priv->event)
390         ResetEvent (priv->event);
391 #endif
392       if (priv->cancel_pipe[0] != -1)
393         {
394           gssize c;
395 #ifdef HAVE_EVENTFD
396           if (priv->cancel_pipe[1] == -1)
397             {
398               guint64 buf;
399
400               do
401                 c = read (priv->cancel_pipe[0], &buf, sizeof(buf));
402               while (c == -1 && errno == EINTR);
403             }
404           else
405 #endif
406             {
407               char ch;
408
409               do
410                 c = read (priv->cancel_pipe[0], &ch, 1);
411               while (c == -1 && errno == EINTR);
412             }
413         }
414
415       priv->cancelled = FALSE;
416     }
417   G_UNLOCK(cancellable);
418 }
419
420 /**
421  * g_cancellable_is_cancelled:
422  * @cancellable: a #GCancellable or NULL.
423  * 
424  * Checks if a cancellable job has been cancelled.
425  * 
426  * Returns: %TRUE if @cancellable is cancelled, 
427  * FALSE if called with %NULL or if item is not cancelled. 
428  **/
429 gboolean
430 g_cancellable_is_cancelled (GCancellable *cancellable)
431 {
432   return cancellable != NULL && cancellable->priv->cancelled;
433 }
434
435 /**
436  * g_cancellable_set_error_if_cancelled:
437  * @cancellable: a #GCancellable object.
438  * @error: #GError to append error state to.
439  * 
440  * If the @cancellable is cancelled, sets the error to notify
441  * that the operation was cancelled.
442  * 
443  * Returns: %TRUE if @cancellable was cancelled, %FALSE if it was not.
444  **/
445 gboolean
446 g_cancellable_set_error_if_cancelled (GCancellable  *cancellable,
447                                       GError       **error)
448 {
449   if (g_cancellable_is_cancelled (cancellable))
450     {
451       g_set_error_literal (error,
452                            G_IO_ERROR,
453                            G_IO_ERROR_CANCELLED,
454                            _("Operation was cancelled"));
455       return TRUE;
456     }
457   
458   return FALSE;
459 }
460
461 /**
462  * g_cancellable_get_fd:
463  * @cancellable: a #GCancellable.
464  * 
465  * Gets the file descriptor for a cancellable job. This can be used to
466  * implement cancellable operations on Unix systems. The returned fd will
467  * turn readable when @cancellable is cancelled.
468  *
469  * You are not supposed to read from the fd yourself, just check for
470  * readable status. Reading to unset the readable status is done
471  * with g_cancellable_reset().
472  * 
473  * After a successful return from this function, you should use 
474  * g_cancellable_release_fd() to free up resources allocated for 
475  * the returned file descriptor.
476  *
477  * See also g_cancellable_make_pollfd().
478  *
479  * Returns: A valid file descriptor. %-1 if the file descriptor 
480  * is not supported, or on errors. 
481  **/
482 int
483 g_cancellable_get_fd (GCancellable *cancellable)
484 {
485   GCancellablePrivate *priv;
486   int fd;
487
488   if (cancellable == NULL)
489     return -1;
490
491   priv = cancellable->priv;
492
493 #ifdef G_OS_WIN32
494   return -1;
495 #else
496   G_LOCK(cancellable);
497   if (priv->cancel_pipe[0] == -1)
498     g_cancellable_open_pipe (cancellable);
499   fd = priv->cancel_pipe[0];
500   if (fd != -1)
501     priv->fd_refcount++;
502   G_UNLOCK(cancellable);
503 #endif
504
505   return fd;
506 }
507
508 /**
509  * g_cancellable_make_pollfd:
510  * @cancellable: a #GCancellable or %NULL
511  * @pollfd: a pointer to a #GPollFD
512  * 
513  * Creates a #GPollFD corresponding to @cancellable; this can be passed
514  * to g_poll() and used to poll for cancellation. This is useful both
515  * for unix systems without a native poll and for portability to
516  * windows.
517  *
518  * When this function returns %TRUE, you should use 
519  * g_cancellable_release_fd() to free up resources allocated for the 
520  * @pollfd. After a %FALSE return, do not call g_cancellable_release_fd().
521  *
522  * If this function returns %FALSE, either no @cancellable was given or
523  * resource limits prevent this function from allocating the necessary 
524  * structures for polling. (On Linux, you will likely have reached 
525  * the maximum number of file descriptors.) The suggested way to handle
526  * these cases is to ignore the @cancellable.
527  *
528  * You are not supposed to read from the fd yourself, just check for
529  * readable status. Reading to unset the readable status is done
530  * with g_cancellable_reset().
531  *
532  * Returns: %TRUE if @pollfd was successfully initialized, %FALSE on 
533  *          failure to prepare the cancellable.
534  * 
535  * Since: 2.22
536  **/
537 gboolean
538 g_cancellable_make_pollfd (GCancellable *cancellable, GPollFD *pollfd)
539 {
540   g_return_val_if_fail (pollfd != NULL, FALSE);
541   if (cancellable == NULL)
542     return FALSE;
543   g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), FALSE);
544
545   {
546 #ifdef G_OS_WIN32
547     GCancellablePrivate *priv;
548
549     priv = cancellable->priv;
550     G_LOCK(cancellable);
551     if (priv->event == NULL)
552       {
553         /* A manual reset anonymous event, starting unset */
554         priv->event = CreateEvent (NULL, TRUE, FALSE, NULL);
555         if (priv->event == NULL)
556           {
557             G_UNLOCK(cancellable);
558             return FALSE;
559           }
560         if (priv->cancelled)
561           SetEvent(priv->event);
562       }
563     priv->fd_refcount++;
564     G_UNLOCK(cancellable);
565
566     pollfd->fd = (gintptr)priv->event;
567 #else /* !G_OS_WIN32 */
568     int fd = g_cancellable_get_fd (cancellable);
569
570     if (fd == -1)
571       return FALSE;
572     pollfd->fd = fd;
573 #endif /* G_OS_WIN32 */
574   }
575
576   pollfd->events = G_IO_IN;
577   pollfd->revents = 0;
578
579   return TRUE;
580 }
581
582 /**
583  * g_cancellable_release_fd:
584  * @cancellable: a #GCancellable
585  *
586  * Releases a resources previously allocated by g_cancellable_get_fd()
587  * or g_cancellable_make_pollfd().
588  *
589  * For compatibility reasons with older releases, calling this function 
590  * is not strictly required, the resources will be automatically freed
591  * when the @cancellable is finalized. However, the @cancellable will
592  * block scarce file descriptors until it is finalized if this function
593  * is not called. This can cause the application to run out of file 
594  * descriptors when many #GCancellables are used at the same time.
595  * 
596  * Since: 2.22
597  **/
598 void
599 g_cancellable_release_fd (GCancellable *cancellable)
600 {
601   GCancellablePrivate *priv;
602
603   if (cancellable == NULL)
604     return;
605
606   g_return_if_fail (G_IS_CANCELLABLE (cancellable));
607   g_return_if_fail (cancellable->priv->fd_refcount > 0);
608
609   priv = cancellable->priv;
610
611   G_LOCK (cancellable);
612   priv->fd_refcount--;
613   if (priv->fd_refcount == 0)
614     g_cancellable_close_pipe (cancellable);
615   G_UNLOCK (cancellable);
616 }
617
618 /**
619  * g_cancellable_cancel:
620  * @cancellable: a #GCancellable object.
621  * 
622  * Will set @cancellable to cancelled, and will emit the
623  * #GCancellable::cancelled signal. (However, see the warning about
624  * race conditions in the documentation for that signal if you are
625  * planning to connect to it.)
626  *
627  * This function is thread-safe. In other words, you can safely call
628  * it from a thread other than the one running the operation that was
629  * passed the @cancellable.
630  *
631  * The convention within gio is that cancelling an asynchronous
632  * operation causes it to complete asynchronously. That is, if you
633  * cancel the operation from the same thread in which it is running,
634  * then the operation's #GAsyncReadyCallback will not be invoked until
635  * the application returns to the main loop.
636  **/
637 void
638 g_cancellable_cancel (GCancellable *cancellable)
639 {
640   GCancellablePrivate *priv;
641
642   if (cancellable == NULL ||
643       cancellable->priv->cancelled)
644     return;
645
646   priv = cancellable->priv;
647
648   G_LOCK(cancellable);
649   if (priv->cancelled)
650     {
651       G_UNLOCK (cancellable);
652       return;
653     }
654
655   priv->cancelled = TRUE;
656   priv->cancelled_running = TRUE;
657 #ifdef G_OS_WIN32
658   if (priv->event)
659     SetEvent (priv->event);
660 #endif
661   
662   g_cancellable_write_cancelled (cancellable);
663
664   G_UNLOCK(cancellable);
665
666   g_object_ref (cancellable);
667   g_signal_emit (cancellable, signals[CANCELLED], 0);
668
669   G_LOCK(cancellable);
670
671   priv->cancelled_running = FALSE;
672   if (priv->cancelled_running_waiting)
673     g_cond_broadcast (cancellable_cond);
674   priv->cancelled_running_waiting = FALSE;
675
676   G_UNLOCK(cancellable);
677
678   g_object_unref (cancellable);
679 }
680
681 /**
682  * g_cancellable_connect:
683  * @cancellable: A #GCancellable.
684  * @callback: The #GCallback to connect.
685  * @data: Data to pass to @callback.
686  * @data_destroy_func: Free function for @data or %NULL.
687  *
688  * Convenience function to connect to the #GCancellable::cancelled
689  * signal. Also handles the race condition that may happen
690  * if the cancellable is cancelled right before connecting.
691  *
692  * @callback is called at most once, either directly at the
693  * time of the connect if @cancellable is already cancelled,
694  * or when @cancellable is cancelled in some thread.
695  *
696  * @data_destroy_func will be called when the handler is
697  * disconnected, or immediately if the cancellable is already
698  * cancelled.
699  *
700  * See #GCancellable::cancelled for details on how to use this.
701  *
702  * Returns: The id of the signal handler or 0 if @cancellable has already
703  *          been cancelled.
704  *
705  * Since: 2.22
706  */
707 gulong
708 g_cancellable_connect (GCancellable   *cancellable,
709                        GCallback       callback,
710                        gpointer        data,
711                        GDestroyNotify  data_destroy_func)
712 {
713   gulong id;
714
715   g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), 0);
716
717   G_LOCK (cancellable);
718
719   if (cancellable->priv->cancelled)
720     {
721       void (*_callback) (GCancellable *cancellable,
722                          gpointer      user_data);
723
724       _callback = (void *)callback;
725       id = 0;
726
727       _callback (cancellable, data);
728
729       if (data_destroy_func)
730         data_destroy_func (data);
731     }
732   else
733     {
734       id = g_signal_connect_data (cancellable, "cancelled",
735                                   callback, data,
736                                   (GClosureNotify) data_destroy_func,
737                                   0);
738     }
739   G_UNLOCK (cancellable);
740
741   return id;
742 }
743
744 /**
745  * g_cancellable_disconnect:
746  * @cancellable: A #GCancellable or %NULL.
747  * @handler_id: Handler id of the handler to be disconnected, or %0.
748  *
749  * Disconnects a handler from a cancellable instance similar to
750  * g_signal_handler_disconnect().  Additionally, in the event that a
751  * signal handler is currently running, this call will block until the
752  * handler has finished.  Calling this function from a
753  * #GCancellable::cancelled signal handler will therefore result in a
754  * deadlock.
755  *
756  * This avoids a race condition where a thread cancels at the
757  * same time as the cancellable operation is finished and the
758  * signal handler is removed. See #GCancellable::cancelled for
759  * details on how to use this.
760  *
761  * If @cancellable is %NULL or @handler_id is %0 this function does
762  * nothing.
763  *
764  * Since: 2.22
765  */
766 void
767 g_cancellable_disconnect (GCancellable  *cancellable,
768                           gulong         handler_id)
769 {
770   GCancellablePrivate *priv;
771
772   if (handler_id == 0 ||  cancellable == NULL)
773     return;
774
775   G_LOCK (cancellable);
776
777   priv = cancellable->priv;
778
779   while (priv->cancelled_running)
780     {
781       priv->cancelled_running_waiting = TRUE;
782       g_cond_wait (cancellable_cond,
783                    g_static_mutex_get_mutex (& G_LOCK_NAME (cancellable)));
784     }
785
786   g_signal_handler_disconnect (cancellable, handler_id);
787   G_UNLOCK (cancellable);
788 }
789
790 typedef struct {
791   GSource       source;
792
793   GCancellable *cancellable;
794   GPollFD       pollfd;
795 } GCancellableSource;
796
797 static gboolean
798 cancellable_source_prepare (GSource *source,
799                             gint    *timeout)
800 {
801   GCancellableSource *cancellable_source = (GCancellableSource *)source;
802
803   *timeout = -1;
804   return g_cancellable_is_cancelled (cancellable_source->cancellable);
805 }
806
807 static gboolean
808 cancellable_source_check (GSource *source)
809 {
810   GCancellableSource *cancellable_source = (GCancellableSource *)source;
811
812   return g_cancellable_is_cancelled (cancellable_source->cancellable);
813 }
814
815 static gboolean
816 cancellable_source_dispatch (GSource     *source,
817                              GSourceFunc  callback,
818                              gpointer     user_data)
819 {
820   GCancellableSourceFunc func = (GCancellableSourceFunc)callback;
821   GCancellableSource *cancellable_source = (GCancellableSource *)source;
822
823   return (*func) (cancellable_source->cancellable, user_data);
824 }
825
826 static void
827 cancellable_source_finalize (GSource *source)
828 {
829   GCancellableSource *cancellable_source = (GCancellableSource *)source;
830
831   if (cancellable_source->cancellable)
832     g_object_unref (cancellable_source->cancellable);
833 }
834
835 static gboolean
836 cancellable_source_closure_callback (GCancellable *cancellable,
837                                      gpointer      data)
838 {
839   GClosure *closure = data;
840
841   GValue params = { 0, };
842   GValue result_value = { 0, };
843   gboolean result;
844
845   g_value_init (&result_value, G_TYPE_BOOLEAN);
846
847   g_value_init (&params, G_TYPE_CANCELLABLE);
848   g_value_set_object (&params, cancellable);
849
850   g_closure_invoke (closure, &result_value, 1, &params, NULL);
851
852   result = g_value_get_boolean (&result_value);
853   g_value_unset (&result_value);
854   g_value_unset (&params);
855
856   return result;
857 }
858
859 static GSourceFuncs cancellable_source_funcs =
860 {
861   cancellable_source_prepare,
862   cancellable_source_check,
863   cancellable_source_dispatch,
864   cancellable_source_finalize,
865   (GSourceFunc)cancellable_source_closure_callback,
866   (GSourceDummyMarshal)g_cclosure_marshal_generic,
867 };
868
869 /**
870  * g_cancellable_source_new: (skip)
871  * @cancellable: a #GCancellable, or %NULL
872  *
873  * Creates a source that triggers if @cancellable is cancelled and
874  * calls its callback of type #GCancellableSourceFunc. This is
875  * primarily useful for attaching to another (non-cancellable) source
876  * with g_source_add_child_source() to add cancellability to it.
877  *
878  * For convenience, you can call this with a %NULL #GCancellable,
879  * in which case the source will never trigger.
880  *
881  * Return value: (transfer full): the new #GSource.
882  *
883  * Since: 2.28
884  */
885 GSource *
886 g_cancellable_source_new (GCancellable *cancellable)
887 {
888   GSource *source;
889   GCancellableSource *cancellable_source;
890
891   source = g_source_new (&cancellable_source_funcs, sizeof (GCancellableSource));
892   g_source_set_name (source, "GCancellable");
893   cancellable_source = (GCancellableSource *)source;
894
895   if (g_cancellable_make_pollfd (cancellable,
896                                  &cancellable_source->pollfd))
897     {
898       cancellable_source->cancellable = g_object_ref (cancellable);
899       g_source_add_poll (source, &cancellable_source->pollfd);
900     }
901
902   return source;
903 }