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