Eradicate links and xrefs
[platform/upstream/glib.git] / gio / gtask.c
1 /* GIO - GLib Input, Output and Streaming Library
2  *
3  * Copyright 2011 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, see <http://www.gnu.org/licenses/>.
17  */
18
19 #include "config.h"
20
21 #include "gtask.h"
22
23 #include "gasyncresult.h"
24 #include "gcancellable.h"
25
26 /**
27  * SECTION:gtask
28  * @short_description: Cancellable synchronous or asynchronous task
29  *     and result
30  * @include: gio/gio.h
31  * @see_also: #GAsyncResult
32  *
33  * A #GTask represents and manages a cancellable "task".
34  *
35  * ## Asynchronous operations
36  *
37  * The most common usage of #GTask is as a #GAsyncResult, to
38  * manage data during an asynchronous operation. You call
39  * g_task_new() in the "start" method, followed by
40  * g_task_set_task_data() and the like if you need to keep some
41  * additional data associated with the task, and then pass the
42  * task object around through your asynchronous operation.
43  * Eventually, you will call a method such as
44  * g_task_return_pointer() or g_task_return_error(), which will
45  * save the value you give it and then invoke the task's callback
46  * function (waiting until the next iteration of the main
47  * loop first, if necessary). The caller will pass the #GTask back
48  * to the operation's finish function (as a #GAsyncResult), and
49  * you can use g_task_propagate_pointer() or the like to extract
50  * the return value.
51  *
52  * Here is an example for using GTask as a GAsyncResult:
53  * |[<!-- language="C" -->
54  *     typedef struct {
55  *       CakeFrostingType frosting;
56  *       char *message;
57  *     } DecorationData;
58  *
59  *     static void
60  *     decoration_data_free (DecorationData *decoration)
61  *     {
62  *       g_free (decoration->message);
63  *       g_slice_free (DecorationData, decoration);
64  *     }
65  *
66  *     static void
67  *     baked_cb (Cake     *cake,
68  *               gpointer  user_data)
69  *     {
70  *       GTask *task = user_data;
71  *       DecorationData *decoration = g_task_get_task_data (task);
72  *       GError *error = NULL;
73  *
74  *       if (cake == NULL)
75  *         {
76  *           g_task_return_new_error (task, BAKER_ERROR, BAKER_ERROR_NO_FLOUR,
77  *                                    "Go to the supermarket");
78  *           g_object_unref (task);
79  *           return;
80  *         }
81  *
82  *       if (!cake_decorate (cake, decoration->frosting, decoration->message, &error))
83  *         {
84  *           g_object_unref (cake);
85  *           /&ast; g_task_return_error() takes ownership of error &ast;/
86  *           g_task_return_error (task, error);
87  *           g_object_unref (task);
88  *           return;
89  *         }
90  *
91  *       g_task_return_pointer (task, cake, g_object_unref);
92  *       g_object_unref (task);
93  *     }
94  *
95  *     void
96  *     baker_bake_cake_async (Baker               *self,
97  *                            guint                radius,
98  *                            CakeFlavor           flavor,
99  *                            CakeFrostingType     frosting,
100  *                            const char          *message,
101  *                            GCancellable        *cancellable,
102  *                            GAsyncReadyCallback  callback,
103  *                            gpointer             user_data)
104  *     {
105  *       GTask *task;
106  *       DecorationData *decoration;
107  *       Cake  *cake;
108  *
109  *       task = g_task_new (self, cancellable, callback, user_data);
110  *       if (radius < 3)
111  *         {
112  *           g_task_return_new_error (task, BAKER_ERROR, BAKER_ERROR_TOO_SMALL,
113  *                                    "%ucm radius cakes are silly",
114  *                                    radius);
115  *           g_object_unref (task);
116  *           return;
117  *         }
118  *
119  *       cake = _baker_get_cached_cake (self, radius, flavor, frosting, message);
120  *       if (cake != NULL)
121  *         {
122  *           /&ast; _baker_get_cached_cake() returns a reffed cake &ast;/
123  *           g_task_return_pointer (task, cake, g_object_unref);
124  *           g_object_unref (task);
125  *           return;
126  *         }
127  *
128  *       decoration = g_slice_new (DecorationData);
129  *       decoration->frosting = frosting;
130  *       decoration->message = g_strdup (message);
131  *       g_task_set_task_data (task, decoration, (GDestroyNotify) decoration_data_free);
132  *
133  *       _baker_begin_cake (self, radius, flavor, cancellable, baked_cb, task);
134  *     }
135  *
136  *     Cake *
137  *     baker_bake_cake_finish (Baker         *self,
138  *                             GAsyncResult  *result,
139  *                             GError       **error)
140  *     {
141  *       g_return_val_if_fail (g_task_is_valid (result, self), NULL);
142  *
143  *       return g_task_propagate_pointer (G_TASK (result), error);
144  *     }
145  * ]|
146  *
147  * ## Chained asynchronous operations
148  *
149  * #GTask also tries to simplify asynchronous operations that
150  * internally chain together several smaller asynchronous
151  * operations. g_task_get_cancellable(), g_task_get_context(),
152  * and g_task_get_priority() allow you to get back the task's
153  * #GCancellable, #GMainContext, and [I/O priority][io-priority]
154  * when starting a new subtask, so you don't have to keep track
155  * of them yourself. g_task_attach_source() simplifies the case
156  * of waiting for a source to fire (automatically using the correct
157  * #GMainContext and priority).
158  *
159  * Here is an example for chained asynchronous operations:
160  *   |[<!-- language="C" -->
161  *     typedef struct {
162  *       Cake *cake;
163  *       CakeFrostingType frosting;
164  *       char *message;
165  *     } BakingData;
166  *
167  *     static void
168  *     decoration_data_free (BakingData *bd)
169  *     {
170  *       if (bd->cake)
171  *         g_object_unref (bd->cake);
172  *       g_free (bd->message);
173  *       g_slice_free (BakingData, bd);
174  *     }
175  *
176  *     static void
177  *     decorated_cb (Cake         *cake,
178  *                   GAsyncResult *result,
179  *                   gpointer      user_data)
180  *     {
181  *       GTask *task = user_data;
182  *       GError *error = NULL;
183  *
184  *       if (!cake_decorate_finish (cake, result, &error))
185  *         {
186  *           g_object_unref (cake);
187  *           g_task_return_error (task, error);
188  *           g_object_unref (task);
189  *           return;
190  *         }
191  *
192  *       /&ast; baking_data_free() will drop its ref on the cake, so
193  *        &ast; we have to take another here to give to the caller.
194  *        &ast;/
195  *       g_task_return_pointer (result, g_object_ref (cake), g_object_unref);
196  *       g_object_unref (task);
197  *     }
198  *
199  *     static void
200  *     decorator_ready (gpointer user_data)
201  *     {
202  *       GTask *task = user_data;
203  *       BakingData *bd = g_task_get_task_data (task);
204  *
205  *       cake_decorate_async (bd->cake, bd->frosting, bd->message,
206  *                            g_task_get_cancellable (task),
207  *                            decorated_cb, task);
208  *     }
209  *
210  *     static void
211  *     baked_cb (Cake     *cake,
212  *               gpointer  user_data)
213  *     {
214  *       GTask *task = user_data;
215  *       BakingData *bd = g_task_get_task_data (task);
216  *       GError *error = NULL;
217  *
218  *       if (cake == NULL)
219  *         {
220  *           g_task_return_new_error (task, BAKER_ERROR, BAKER_ERROR_NO_FLOUR,
221  *                                    "Go to the supermarket");
222  *           g_object_unref (task);
223  *           return;
224  *         }
225  *
226  *       bd->cake = cake;
227  *
228  *       /&ast; Bail out now if the user has already cancelled &ast;/
229  *       if (g_task_return_error_if_cancelled (task))
230  *         {
231  *           g_object_unref (task);
232  *           return;
233  *         }
234  *
235  *       if (cake_decorator_available (cake))
236  *         decorator_ready (task);
237  *       else
238  *         {
239  *           GSource *source;
240  *
241  *           source = cake_decorator_wait_source_new (cake);
242  *           /&ast; Attach @source to @task's GMainContext and have it call
243  *            &ast; decorator_ready() when it is ready.
244  *            &ast;/
245  *           g_task_attach_source (task, source,
246  *                                 G_CALLBACK (decorator_ready));
247  *           g_source_unref (source);
248  *         }
249  *     }
250  *
251  *     void
252  *     baker_bake_cake_async (Baker               *self,
253  *                            guint                radius,
254  *                            CakeFlavor           flavor,
255  *                            CakeFrostingType     frosting,
256  *                            const char          *message,
257  *                            gint                 priority,
258  *                            GCancellable        *cancellable,
259  *                            GAsyncReadyCallback  callback,
260  *                            gpointer             user_data)
261  *     {
262  *       GTask *task;
263  *       BakingData *bd;
264  *
265  *       task = g_task_new (self, cancellable, callback, user_data);
266  *       g_task_set_priority (task, priority);
267  *
268  *       bd = g_slice_new0 (BakingData);
269  *       bd->frosting = frosting;
270  *       bd->message = g_strdup (message);
271  *       g_task_set_task_data (task, bd, (GDestroyNotify) baking_data_free);
272  *
273  *       _baker_begin_cake (self, radius, flavor, cancellable, baked_cb, task);
274  *     }
275  *
276  *     Cake *
277  *     baker_bake_cake_finish (Baker         *self,
278  *                             GAsyncResult  *result,
279  *                             GError       **error)
280  *     {
281  *       g_return_val_if_fail (g_task_is_valid (result, self), NULL);
282  *
283  *       return g_task_propagate_pointer (G_TASK (result), error);
284  *     }
285  * ]|
286  *
287  * ## Asynchronous operations from synchronous ones
288  *
289  * You can use g_task_run_in_thread() to turn a synchronous
290  * operation into an asynchronous one, by running it in a thread
291  * which will then dispatch the result back to the caller's
292  * #GMainContext when it completes.
293  *
294  * Running a task in a thread:
295  *   |[<!-- language="C" -->
296  *     typedef struct {
297  *       guint radius;
298  *       CakeFlavor flavor;
299  *       CakeFrostingType frosting;
300  *       char *message;
301  *     } CakeData;
302  *
303  *     static void
304  *     cake_data_free (CakeData *cake_data)
305  *     {
306  *       g_free (cake_data->message);
307  *       g_slice_free (CakeData, cake_data);
308  *     }
309  *
310  *     static void
311  *     bake_cake_thread (GTask         *task,
312  *                       gpointer       source_object,
313  *                       gpointer       task_data,
314  *                       GCancellable  *cancellable)
315  *     {
316  *       Baker *self = source_object;
317  *       CakeData *cake_data = task_data;
318  *       Cake *cake;
319  *       GError *error = NULL;
320  *
321  *       cake = bake_cake (baker, cake_data->radius, cake_data->flavor,
322  *                         cake_data->frosting, cake_data->message,
323  *                         cancellable, &error);
324  *       if (cake)
325  *         g_task_return_pointer (task, cake, g_object_unref);
326  *       else
327  *         g_task_return_error (task, error);
328  *     }
329  *
330  *     void
331  *     baker_bake_cake_async (Baker               *self,
332  *                            guint                radius,
333  *                            CakeFlavor           flavor,
334  *                            CakeFrostingType     frosting,
335  *                            const char          *message,
336  *                            GCancellable        *cancellable,
337  *                            GAsyncReadyCallback  callback,
338  *                            gpointer             user_data)
339  *     {
340  *       CakeData *cake_data;
341  *       GTask *task;
342  *
343  *       cake_data = g_slice_new (CakeData);
344  *       cake_data->radius = radius;
345  *       cake_data->flavor = flavor;
346  *       cake_data->frosting = frosting;
347  *       cake_data->message = g_strdup (message);
348  *       task = g_task_new (self, cancellable, callback, user_data);
349  *       g_task_set_task_data (task, cake_data, (GDestroyNotify) cake_data_free);
350  *       g_task_run_in_thread (task, bake_cake_thread);
351  *     }
352  *
353  *     Cake *
354  *     baker_bake_cake_finish (Baker         *self,
355  *                             GAsyncResult  *result,
356  *                             GError       **error)
357  *     {
358  *       g_return_val_if_fail (g_task_is_valid (result, self), NULL);
359  *
360  *       return g_task_propagate_pointer (G_TASK (result), error);
361  *     }
362  * ]|
363  *
364  * ## Adding cancellability to uncancellable tasks
365  * 
366  * Finally, g_task_run_in_thread() and g_task_run_in_thread_sync()
367  * can be used to turn an uncancellable operation into a
368  * cancellable one. If you call g_task_set_return_on_cancel(),
369  * passing %TRUE, then if the task's #GCancellable is cancelled,
370  * it will return control back to the caller immediately, while
371  * allowing the task thread to continue running in the background
372  * (and simply discarding its result when it finally does finish).
373  * Provided that the task thread is careful about how it uses
374  * locks and other externally-visible resources, this allows you
375  * to make "GLib-friendly" asynchronous and cancellable
376  * synchronous variants of blocking APIs.
377  *
378  * Cancelling a task:
379  *   |[<!-- language="C" -->
380  *     static void
381  *     bake_cake_thread (GTask         *task,
382  *                       gpointer       source_object,
383  *                       gpointer       task_data,
384  *                       GCancellable  *cancellable)
385  *     {
386  *       Baker *self = source_object;
387  *       CakeData *cake_data = task_data;
388  *       Cake *cake;
389  *       GError *error = NULL;
390  *
391  *       cake = bake_cake (baker, cake_data->radius, cake_data->flavor,
392  *                         cake_data->frosting, cake_data->message,
393  *                         &error);
394  *       if (error)
395  *         {
396  *           g_task_return_error (task, error);
397  *           return;
398  *         }
399  *
400  *       /&ast; If the task has already been cancelled, then we don't
401  *        &ast; want to add the cake to the cake cache. Likewise, we don't
402  *        &ast; want to have the task get cancelled in the middle of
403  *        &ast; updating the cache. g_task_set_return_on_cancel() will
404  *        &ast; return %TRUE here if it managed to disable return-on-cancel,
405  *        &ast; or %FALSE if the task was cancelled before it could.
406  *        &ast;/
407  *       if (g_task_set_return_on_cancel (task, FALSE))
408  *         {
409  *           /&ast; If the caller cancels at this point, their
410  *            &ast; GAsyncReadyCallback won't be invoked until we return,
411  *            &ast; so we don't have to worry that this code will run at
412  *            &ast; the same time as that code does. But if there were
413  *            &ast; other functions that might look at the cake cache,
414  *            &ast; then we'd probably need a GMutex here as well.
415  *            &ast;/
416  *           baker_add_cake_to_cache (baker, cake);
417  *           g_task_return_pointer (task, cake, g_object_unref);
418  *         }
419  *     }
420  *
421  *     void
422  *     baker_bake_cake_async (Baker               *self,
423  *                            guint                radius,
424  *                            CakeFlavor           flavor,
425  *                            CakeFrostingType     frosting,
426  *                            const char          *message,
427  *                            GCancellable        *cancellable,
428  *                            GAsyncReadyCallback  callback,
429  *                            gpointer             user_data)
430  *     {
431  J*       CakeData *cake_data;
432  *       GTask *task;
433  *
434  *       cake_data = g_slice_new (CakeData);
435  *       /&ast; ... &ast;/
436  *
437  *       task = g_task_new (self, cancellable, callback, user_data);
438  *       g_task_set_task_data (task, cake_data, (GDestroyNotify) cake_data_free);
439  *       g_task_set_return_on_cancel (task, TRUE);
440  *       g_task_run_in_thread (task, bake_cake_thread);
441  *     }
442  *
443  *     Cake *
444  *     baker_bake_cake_sync (Baker               *self,
445  *                           guint                radius,
446  *                           CakeFlavor           flavor,
447  *                           CakeFrostingType     frosting,
448  *                           const char          *message,
449  *                           GCancellable        *cancellable,
450  *                           GError             **error)
451  *     {
452  *       CakeData *cake_data;
453  *       GTask *task;
454  *       Cake *cake;
455  *
456  *       cake_data = g_slice_new (CakeData);
457  *       /&ast; ... &ast;/
458  *
459  *       task = g_task_new (self, cancellable, NULL, NULL);
460  *       g_task_set_task_data (task, cake_data, (GDestroyNotify) cake_data_free);
461  *       g_task_set_return_on_cancel (task, TRUE);
462  *       g_task_run_in_thread_sync (task, bake_cake_thread);
463  *
464  *       cake = g_task_propagate_pointer (task, error);
465  *       g_object_unref (task);
466  *       return cake;
467  *     }
468  * ]|
469  *
470  * ## Porting from GSimpleAsyncResult
471  * 
472  * #GTask's API attempts to be simpler than #GSimpleAsyncResult's
473  * in several ways:
474  * - You can save task-specific data with g_task_set_task_data(), and
475  *   retrieve it later with g_task_get_task_data(). This replaces the
476  *   abuse of g_simple_async_result_set_op_res_gpointer() for the same
477  *   purpose with #GSimpleAsyncResult.
478  * - In addition to the task data, #GTask also keeps track of the
479  *   [priority][io-priority], #GCancellable, and
480  *   #GMainContext associated with the task, so tasks that consist of
481  *   a chain of simpler asynchronous operations will have easy access
482  *   to those values when starting each sub-task.
483  * - g_task_return_error_if_cancelled() provides simplified
484  *   handling for cancellation. In addition, cancellation
485  *   overrides any other #GTask return value by default, like
486  *   #GSimpleAsyncResult does when
487  *   g_simple_async_result_set_check_cancellable() is called.
488  *   (You can use g_task_set_check_cancellable() to turn off that
489  *   behavior.) On the other hand, g_task_run_in_thread()
490  *   guarantees that it will always run your
491  *   `task_func`, even if the task's #GCancellable
492  *   is already cancelled before the task gets a chance to run;
493  *   you can start your `task_func` with a
494  *   g_task_return_error_if_cancelled() check if you need the
495  *   old behavior.
496  * - The "return" methods (eg, g_task_return_pointer())
497  *   automatically cause the task to be "completed" as well, and
498  *   there is no need to worry about the "complete" vs "complete
499  *   in idle" distinction. (#GTask automatically figures out
500  *   whether the task's callback can be invoked directly, or
501  *   if it needs to be sent to another #GMainContext, or delayed
502  *   until the next iteration of the current #GMainContext.)
503  * - The "finish" functions for #GTask-based operations are generally
504  *   much simpler than #GSimpleAsyncResult ones, normally consisting
505  *   of only a single call to g_task_propagate_pointer() or the like.
506  *   Since g_task_propagate_pointer() "steals" the return value from
507  *   the #GTask, it is not necessary to juggle pointers around to
508  *   prevent it from being freed twice.
509  * - With #GSimpleAsyncResult, it was common to call
510  *   g_simple_async_result_propagate_error() from the
511  *   `_finish()` wrapper function, and have
512  *   virtual method implementations only deal with successful
513  *   returns. This behavior is deprecated, because it makes it
514  *   difficult for a subclass to chain to a parent class's async
515  *   methods. Instead, the wrapper function should just be a
516  *   simple wrapper, and the virtual method should call an
517  *   appropriate `g_task_propagate_` function.
518  *   Note that wrapper methods can now use
519  *   g_async_result_legacy_propagate_error() to do old-style
520  *   #GSimpleAsyncResult error-returning behavior, and
521  *   g_async_result_is_tagged() to check if a result is tagged as
522  *   having come from the `_async()` wrapper
523  *   function (for "short-circuit" results, such as when passing
524  *   0 to g_input_stream_read_async()).
525  */
526
527 /**
528  * GTask:
529  *
530  * The opaque object representing a synchronous or asynchronous task
531  * and its result.
532  */
533
534 struct _GTask {
535   GObject parent_instance;
536
537   gpointer source_object;
538   gpointer source_tag;
539
540   gpointer task_data;
541   GDestroyNotify task_data_destroy;
542
543   GMainContext *context;
544   guint64 creation_time;
545   gint priority;
546   GCancellable *cancellable;
547   gboolean check_cancellable;
548
549   GAsyncReadyCallback callback;
550   gpointer callback_data;
551
552   GTaskThreadFunc task_func;
553   GMutex lock;
554   GCond cond;
555   gboolean return_on_cancel;
556   gboolean thread_cancelled;
557   gboolean synchronous;
558   gboolean thread_complete;
559   gboolean blocking_other_task;
560
561   GError *error;
562   union {
563     gpointer pointer;
564     gssize   size;
565     gboolean boolean;
566   } result;
567   GDestroyNotify result_destroy;
568   gboolean result_set;
569 };
570
571 #define G_TASK_IS_THREADED(task) ((task)->task_func != NULL)
572
573 struct _GTaskClass
574 {
575   GObjectClass parent_class;
576 };
577
578 static void g_task_thread_pool_resort (void);
579
580 static void g_task_async_result_iface_init (GAsyncResultIface *iface);
581 static void g_task_thread_pool_init (void);
582
583 G_DEFINE_TYPE_WITH_CODE (GTask, g_task, G_TYPE_OBJECT,
584                          G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_RESULT,
585                                                 g_task_async_result_iface_init);
586                          g_task_thread_pool_init ();)
587
588 static GThreadPool *task_pool;
589 static GMutex task_pool_mutex;
590 static GPrivate task_private = G_PRIVATE_INIT (NULL);
591
592 static void
593 g_task_init (GTask *task)
594 {
595   task->check_cancellable = TRUE;
596 }
597
598 static void
599 g_task_finalize (GObject *object)
600 {
601   GTask *task = G_TASK (object);
602
603   g_clear_object (&task->source_object);
604   g_clear_object (&task->cancellable);
605
606   if (task->context)
607     g_main_context_unref (task->context);
608
609   if (task->task_data_destroy)
610     task->task_data_destroy (task->task_data);
611
612   if (task->result_destroy && task->result.pointer)
613     task->result_destroy (task->result.pointer);
614
615   if (task->error)
616       g_error_free (task->error);
617
618   if (G_TASK_IS_THREADED (task))
619     {
620       g_mutex_clear (&task->lock);
621       g_cond_clear (&task->cond);
622     }
623
624   G_OBJECT_CLASS (g_task_parent_class)->finalize (object);
625 }
626
627 /**
628  * g_task_new:
629  * @source_object: (allow-none) (type GObject): the #GObject that owns
630  *   this task, or %NULL.
631  * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore.
632  * @callback: (scope async): a #GAsyncReadyCallback.
633  * @callback_data: (closure): user data passed to @callback.
634  *
635  * Creates a #GTask acting on @source_object, which will eventually be
636  * used to invoke @callback in the current
637  * [thread-default main context][g-main-context-push-thread-default].
638  *
639  * Call this in the "start" method of your asynchronous method, and
640  * pass the #GTask around throughout the asynchronous operation. You
641  * can use g_task_set_task_data() to attach task-specific data to the
642  * object, which you can retrieve later via g_task_get_task_data().
643  *
644  * By default, if @cancellable is cancelled, then the return value of
645  * the task will always be %G_IO_ERROR_CANCELLED, even if the task had
646  * already completed before the cancellation. This allows for
647  * simplified handling in cases where cancellation may imply that
648  * other objects that the task depends on have been destroyed. If you
649  * do not want this behavior, you can use
650  * g_task_set_check_cancellable() to change it.
651  *
652  * Returns: a #GTask.
653  *
654  * Since: 2.36
655  */
656 GTask *
657 g_task_new (gpointer              source_object,
658             GCancellable         *cancellable,
659             GAsyncReadyCallback   callback,
660             gpointer              callback_data)
661 {
662   GTask *task;
663   GSource *source;
664
665   task = g_object_new (G_TYPE_TASK, NULL);
666   task->source_object = source_object ? g_object_ref (source_object) : NULL;
667   task->cancellable = cancellable ? g_object_ref (cancellable) : NULL;
668   task->callback = callback;
669   task->callback_data = callback_data;
670   task->context = g_main_context_ref_thread_default ();
671
672   source = g_main_current_source ();
673   if (source)
674     task->creation_time = g_source_get_time (source);
675
676   return task;
677 }
678
679 /**
680  * g_task_report_error:
681  * @source_object: (allow-none) (type GObject): the #GObject that owns
682  *   this task, or %NULL.
683  * @callback: (scope async): a #GAsyncReadyCallback.
684  * @callback_data: (closure): user data passed to @callback.
685  * @source_tag: an opaque pointer indicating the source of this task
686  * @error: (transfer full): error to report
687  *
688  * Creates a #GTask and then immediately calls g_task_return_error()
689  * on it. Use this in the wrapper function of an asynchronous method
690  * when you want to avoid even calling the virtual method. You can
691  * then use g_async_result_is_tagged() in the finish method wrapper to
692  * check if the result there is tagged as having been created by the
693  * wrapper method, and deal with it appropriately if so.
694  *
695  * See also g_task_report_new_error().
696  *
697  * Since: 2.36
698  */
699 void
700 g_task_report_error (gpointer             source_object,
701                      GAsyncReadyCallback  callback,
702                      gpointer             callback_data,
703                      gpointer             source_tag,
704                      GError              *error)
705 {
706   GTask *task;
707
708   task = g_task_new (source_object, NULL, callback, callback_data);
709   g_task_set_source_tag (task, source_tag);
710   g_task_return_error (task, error);
711   g_object_unref (task);
712 }
713
714 /**
715  * g_task_report_new_error:
716  * @source_object: (allow-none) (type GObject): the #GObject that owns
717  *   this task, or %NULL.
718  * @callback: (scope async): a #GAsyncReadyCallback.
719  * @callback_data: (closure): user data passed to @callback.
720  * @source_tag: an opaque pointer indicating the source of this task
721  * @domain: a #GQuark.
722  * @code: an error code.
723  * @format: a string with format characters.
724  * @...: a list of values to insert into @format.
725  *
726  * Creates a #GTask and then immediately calls
727  * g_task_return_new_error() on it. Use this in the wrapper function
728  * of an asynchronous method when you want to avoid even calling the
729  * virtual method. You can then use g_async_result_is_tagged() in the
730  * finish method wrapper to check if the result there is tagged as
731  * having been created by the wrapper method, and deal with it
732  * appropriately if so.
733  *
734  * See also g_task_report_error().
735  *
736  * Since: 2.36
737  */
738 void
739 g_task_report_new_error (gpointer             source_object,
740                          GAsyncReadyCallback  callback,
741                          gpointer             callback_data,
742                          gpointer             source_tag,
743                          GQuark               domain,
744                          gint                 code,
745                          const char          *format,
746                          ...)
747 {
748   GError *error;
749   va_list ap;
750
751   va_start (ap, format);
752   error = g_error_new_valist (domain, code, format, ap);
753   va_end (ap);
754
755   g_task_report_error (source_object, callback, callback_data,
756                        source_tag, error);
757 }
758
759 /**
760  * g_task_set_task_data:
761  * @task: the #GTask
762  * @task_data: (allow-none): task-specific data
763  * @task_data_destroy: (allow-none): #GDestroyNotify for @task_data
764  *
765  * Sets @task's task data (freeing the existing task data, if any).
766  *
767  * Since: 2.36
768  */
769 void
770 g_task_set_task_data (GTask          *task,
771                       gpointer        task_data,
772                       GDestroyNotify  task_data_destroy)
773 {
774   if (task->task_data_destroy)
775     task->task_data_destroy (task->task_data);
776
777   task->task_data = task_data;
778   task->task_data_destroy = task_data_destroy;
779 }
780
781 /**
782  * g_task_set_priority:
783  * @task: the #GTask
784  * @priority: the [priority][io-priority] of the request
785  *
786  * Sets @task's priority. If you do not call this, it will default to
787  * %G_PRIORITY_DEFAULT.
788  *
789  * This will affect the priority of #GSources created with
790  * g_task_attach_source() and the scheduling of tasks run in threads,
791  * and can also be explicitly retrieved later via
792  * g_task_get_priority().
793  *
794  * Since: 2.36
795  */
796 void
797 g_task_set_priority (GTask *task,
798                      gint   priority)
799 {
800   task->priority = priority;
801 }
802
803 /**
804  * g_task_set_check_cancellable:
805  * @task: the #GTask
806  * @check_cancellable: whether #GTask will check the state of
807  *   its #GCancellable for you.
808  *
809  * Sets or clears @task's check-cancellable flag. If this is %TRUE
810  * (the default), then g_task_propagate_pointer(), etc, and
811  * g_task_had_error() will check the task's #GCancellable first, and
812  * if it has been cancelled, then they will consider the task to have
813  * returned an "Operation was cancelled" error
814  * (%G_IO_ERROR_CANCELLED), regardless of any other error or return
815  * value the task may have had.
816  *
817  * If @check_cancellable is %FALSE, then the #GTask will not check the
818  * cancellable itself, and it is up to @task's owner to do this (eg,
819  * via g_task_return_error_if_cancelled()).
820  *
821  * If you are using g_task_set_return_on_cancel() as well, then
822  * you must leave check-cancellable set %TRUE.
823  *
824  * Since: 2.36
825  */
826 void
827 g_task_set_check_cancellable (GTask    *task,
828                               gboolean  check_cancellable)
829 {
830   g_return_if_fail (check_cancellable || !task->return_on_cancel);
831
832   task->check_cancellable = check_cancellable;
833 }
834
835 static void g_task_thread_complete (GTask *task);
836
837 /**
838  * g_task_set_return_on_cancel:
839  * @task: the #GTask
840  * @return_on_cancel: whether the task returns automatically when
841  *   it is cancelled.
842  *
843  * Sets or clears @task's return-on-cancel flag. This is only
844  * meaningful for tasks run via g_task_run_in_thread() or
845  * g_task_run_in_thread_sync().
846  *
847  * If @return_on_cancel is %TRUE, then cancelling @task's
848  * #GCancellable will immediately cause it to return, as though the
849  * task's #GTaskThreadFunc had called
850  * g_task_return_error_if_cancelled() and then returned.
851  *
852  * This allows you to create a cancellable wrapper around an
853  * uninterruptable function. The #GTaskThreadFunc just needs to be
854  * careful that it does not modify any externally-visible state after
855  * it has been cancelled. To do that, the thread should call
856  * g_task_set_return_on_cancel() again to (atomically) set
857  * return-on-cancel %FALSE before making externally-visible changes;
858  * if the task gets cancelled before the return-on-cancel flag could
859  * be changed, g_task_set_return_on_cancel() will indicate this by
860  * returning %FALSE.
861  *
862  * You can disable and re-enable this flag multiple times if you wish.
863  * If the task's #GCancellable is cancelled while return-on-cancel is
864  * %FALSE, then calling g_task_set_return_on_cancel() to set it %TRUE
865  * again will cause the task to be cancelled at that point.
866  *
867  * If the task's #GCancellable is already cancelled before you call
868  * g_task_run_in_thread()/g_task_run_in_thread_sync(), then the
869  * #GTaskThreadFunc will still be run (for consistency), but the task
870  * will also be completed right away.
871  *
872  * Returns: %TRUE if @task's return-on-cancel flag was changed to
873  *   match @return_on_cancel. %FALSE if @task has already been
874  *   cancelled.
875  *
876  * Since: 2.36
877  */
878 gboolean
879 g_task_set_return_on_cancel (GTask    *task,
880                              gboolean  return_on_cancel)
881 {
882   g_return_val_if_fail (task->check_cancellable || !return_on_cancel, FALSE);
883
884   if (!G_TASK_IS_THREADED (task))
885     {
886       task->return_on_cancel = return_on_cancel;
887       return TRUE;
888     }
889
890   g_mutex_lock (&task->lock);
891   if (task->thread_cancelled)
892     {
893       if (return_on_cancel && !task->return_on_cancel)
894         {
895           g_mutex_unlock (&task->lock);
896           g_task_thread_complete (task);
897         }
898       else
899         g_mutex_unlock (&task->lock);
900       return FALSE;
901     }
902   task->return_on_cancel = return_on_cancel;
903   g_mutex_unlock (&task->lock);
904
905   return TRUE;
906 }
907
908 /**
909  * g_task_set_source_tag:
910  * @task: the #GTask
911  * @source_tag: an opaque pointer indicating the source of this task
912  *
913  * Sets @task's source tag. You can use this to tag a task return
914  * value with a particular pointer (usually a pointer to the function
915  * doing the tagging) and then later check it using
916  * g_task_get_source_tag() (or g_async_result_is_tagged()) in the
917  * task's "finish" function, to figure out if the response came from a
918  * particular place.
919  *
920  * Since: 2.36
921  */
922 void
923 g_task_set_source_tag (GTask    *task,
924                        gpointer  source_tag)
925 {
926   task->source_tag = source_tag;
927 }
928
929 /**
930  * g_task_get_source_object:
931  * @task: a #GTask
932  *
933  * Gets the source object from @task. Like
934  * g_async_result_get_source_object(), but does not ref the object.
935  *
936  * Returns: (transfer none) (type GObject): @task's source object, or %NULL
937  *
938  * Since: 2.36
939  */
940 gpointer
941 g_task_get_source_object (GTask *task)
942 {
943   return task->source_object;
944 }
945
946 static GObject *
947 g_task_ref_source_object (GAsyncResult *res)
948 {
949   GTask *task = G_TASK (res);
950
951   if (task->source_object)
952     return g_object_ref (task->source_object);
953   else
954     return NULL;
955 }
956
957 /**
958  * g_task_get_task_data:
959  * @task: a #GTask
960  *
961  * Gets @task's `task_data`.
962  *
963  * Returns: (transfer none): @task's `task_data`.
964  *
965  * Since: 2.36
966  */
967 gpointer
968 g_task_get_task_data (GTask *task)
969 {
970   return task->task_data;
971 }
972
973 /**
974  * g_task_get_priority:
975  * @task: a #GTask
976  *
977  * Gets @task's priority
978  *
979  * Returns: @task's priority
980  *
981  * Since: 2.36
982  */
983 gint
984 g_task_get_priority (GTask *task)
985 {
986   return task->priority;
987 }
988
989 /**
990  * g_task_get_context:
991  * @task: a #GTask
992  *
993  * Gets the #GMainContext that @task will return its result in (that
994  * is, the context that was the
995  * [thread-default main context][g-main-context-push-thread-default]
996  * at the point when @task was created).
997  *
998  * This will always return a non-%NULL value, even if the task's
999  * context is the default #GMainContext.
1000  *
1001  * Returns: (transfer none): @task's #GMainContext
1002  *
1003  * Since: 2.36
1004  */
1005 GMainContext *
1006 g_task_get_context (GTask *task)
1007 {
1008   return task->context;
1009 }
1010
1011 /**
1012  * g_task_get_cancellable:
1013  * @task: a #GTask
1014  *
1015  * Gets @task's #GCancellable
1016  *
1017  * Returns: (transfer none): @task's #GCancellable
1018  *
1019  * Since: 2.36
1020  */
1021 GCancellable *
1022 g_task_get_cancellable (GTask *task)
1023 {
1024   return task->cancellable;
1025 }
1026
1027 /**
1028  * g_task_get_check_cancellable:
1029  * @task: the #GTask
1030  *
1031  * Gets @task's check-cancellable flag. See
1032  * g_task_set_check_cancellable() for more details.
1033  *
1034  * Since: 2.36
1035  */
1036 gboolean
1037 g_task_get_check_cancellable (GTask *task)
1038 {
1039   return task->check_cancellable;
1040 }
1041
1042 /**
1043  * g_task_get_return_on_cancel:
1044  * @task: the #GTask
1045  *
1046  * Gets @task's return-on-cancel flag. See
1047  * g_task_set_return_on_cancel() for more details.
1048  *
1049  * Since: 2.36
1050  */
1051 gboolean
1052 g_task_get_return_on_cancel (GTask *task)
1053 {
1054   return task->return_on_cancel;
1055 }
1056
1057 /**
1058  * g_task_get_source_tag:
1059  * @task: a #GTask
1060  *
1061  * Gets @task's source tag. See g_task_set_source_tag().
1062  *
1063  * Return value: (transfer none): @task's source tag
1064  *
1065  * Since: 2.36
1066  */
1067 gpointer
1068 g_task_get_source_tag (GTask *task)
1069 {
1070   return task->source_tag;
1071 }
1072
1073
1074 static void
1075 g_task_return_now (GTask *task)
1076 {
1077   g_main_context_push_thread_default (task->context);
1078   task->callback (task->source_object,
1079                   G_ASYNC_RESULT (task),
1080                   task->callback_data);
1081   g_main_context_pop_thread_default (task->context);
1082 }
1083
1084 static gboolean
1085 complete_in_idle_cb (gpointer task)
1086 {
1087   g_task_return_now (task);
1088   g_object_unref (task);
1089   return FALSE;
1090 }
1091
1092 typedef enum {
1093   G_TASK_RETURN_SUCCESS,
1094   G_TASK_RETURN_ERROR,
1095   G_TASK_RETURN_FROM_THREAD
1096 } GTaskReturnType;
1097
1098 static void
1099 g_task_return (GTask           *task,
1100                GTaskReturnType  type)
1101 {
1102   GSource *source;
1103
1104   if (type == G_TASK_RETURN_SUCCESS)
1105     task->result_set = TRUE;
1106
1107   if (task->synchronous || !task->callback)
1108     return;
1109
1110   /* Normally we want to invoke the task's callback when its return
1111    * value is set. But if the task is running in a thread, then we
1112    * want to wait until after the task_func returns, to simplify
1113    * locking/refcounting/etc.
1114    */
1115   if (G_TASK_IS_THREADED (task) && type != G_TASK_RETURN_FROM_THREAD)
1116     return;
1117
1118   g_object_ref (task);
1119
1120   /* See if we can complete the task immediately. First, we have to be
1121    * running inside the task's thread/GMainContext.
1122    */
1123   source = g_main_current_source ();
1124   if (source && g_source_get_context (source) == task->context)
1125     {
1126       /* Second, we can only complete immediately if this is not the
1127        * same iteration of the main loop that the task was created in.
1128        */
1129       if (g_source_get_time (source) > task->creation_time)
1130         {
1131           g_task_return_now (task);
1132           g_object_unref (task);
1133           return;
1134         }
1135     }
1136
1137   /* Otherwise, complete in the next iteration */
1138   source = g_idle_source_new ();
1139   g_task_attach_source (task, source, complete_in_idle_cb);
1140   g_source_unref (source);
1141 }
1142
1143
1144 /**
1145  * GTaskThreadFunc:
1146  * @task: the #GTask
1147  * @source_object: (type GObject): @task's source object
1148  * @task_data: @task's task data
1149  * @cancellable: @task's #GCancellable, or %NULL
1150  *
1151  * The prototype for a task function to be run in a thread via
1152  * g_task_run_in_thread() or g_task_run_in_thread_sync().
1153  *
1154  * If the return-on-cancel flag is set on @task, and @cancellable gets
1155  * cancelled, then the #GTask will be completed immediately (as though
1156  * g_task_return_error_if_cancelled() had been called), without
1157  * waiting for the task function to complete. However, the task
1158  * function will continue running in its thread in the background. The
1159  * function therefore needs to be careful about how it uses
1160  * externally-visible state in this case. See
1161  * g_task_set_return_on_cancel() for more details.
1162  *
1163  * Other than in that case, @task will be completed when the
1164  * #GTaskThreadFunc returns, not when it calls a
1165  * `g_task_return_` function.
1166  *
1167  * Since: 2.36
1168  */
1169
1170 static void task_thread_cancelled (GCancellable *cancellable,
1171                                    gpointer      user_data);
1172
1173 static void
1174 g_task_thread_complete (GTask *task)
1175 {
1176   g_mutex_lock (&task->lock);
1177   if (task->thread_complete)
1178     {
1179       /* The task belatedly completed after having been cancelled
1180        * (or was cancelled in the midst of being completed).
1181        */
1182       g_mutex_unlock (&task->lock);
1183       return;
1184     }
1185
1186   task->thread_complete = TRUE;
1187
1188   if (task->blocking_other_task)
1189     {
1190       g_mutex_lock (&task_pool_mutex);
1191       g_thread_pool_set_max_threads (task_pool,
1192                                      g_thread_pool_get_max_threads (task_pool) - 1,
1193                                      NULL);
1194       g_mutex_unlock (&task_pool_mutex);
1195     }
1196   g_mutex_unlock (&task->lock);
1197
1198   if (task->cancellable)
1199     g_signal_handlers_disconnect_by_func (task->cancellable, task_thread_cancelled, task);
1200
1201   if (task->synchronous)
1202     g_cond_signal (&task->cond);
1203   else
1204     g_task_return (task, G_TASK_RETURN_FROM_THREAD);
1205 }
1206
1207 static void
1208 g_task_thread_pool_thread (gpointer thread_data,
1209                            gpointer pool_data)
1210 {
1211   GTask *task = thread_data;
1212
1213   g_private_set (&task_private, task);
1214
1215   task->task_func (task, task->source_object, task->task_data,
1216                    task->cancellable);
1217   g_task_thread_complete (task);
1218
1219   g_private_set (&task_private, NULL);
1220   g_object_unref (task);
1221 }
1222
1223 static void
1224 task_thread_cancelled (GCancellable *cancellable,
1225                        gpointer      user_data)
1226 {
1227   GTask *task = user_data;
1228
1229   g_task_thread_pool_resort ();
1230
1231   g_mutex_lock (&task->lock);
1232   task->thread_cancelled = TRUE;
1233
1234   if (!task->return_on_cancel)
1235     {
1236       g_mutex_unlock (&task->lock);
1237       return;
1238     }
1239
1240   /* We don't actually set task->error; g_task_return_error() doesn't
1241    * use a lock, and g_task_propagate_error() will call
1242    * g_cancellable_set_error_if_cancelled() anyway.
1243    */
1244   g_mutex_unlock (&task->lock);
1245   g_task_thread_complete (task);
1246 }
1247
1248 static void
1249 task_thread_cancelled_disconnect_notify (gpointer  task,
1250                                          GClosure *closure)
1251 {
1252   g_object_unref (task);
1253 }
1254
1255 static void
1256 g_task_start_task_thread (GTask           *task,
1257                           GTaskThreadFunc  task_func)
1258 {
1259   g_mutex_init (&task->lock);
1260   g_cond_init (&task->cond);
1261
1262   g_mutex_lock (&task->lock);
1263
1264   task->task_func = task_func;
1265
1266   if (task->cancellable)
1267     {
1268       if (task->return_on_cancel &&
1269           g_cancellable_set_error_if_cancelled (task->cancellable,
1270                                                 &task->error))
1271         {
1272           task->thread_cancelled = task->thread_complete = TRUE;
1273           g_thread_pool_push (task_pool, g_object_ref (task), NULL);
1274           return;
1275         }
1276
1277       g_signal_connect_data (task->cancellable, "cancelled",
1278                              G_CALLBACK (task_thread_cancelled),
1279                              g_object_ref (task),
1280                              task_thread_cancelled_disconnect_notify, 0);
1281     }
1282
1283   g_thread_pool_push (task_pool, g_object_ref (task), &task->error);
1284   if (task->error)
1285     task->thread_complete = TRUE;
1286   else if (g_private_get (&task_private))
1287     {
1288       /* This thread is being spawned from another GTask thread, so
1289        * bump up max-threads so we don't starve.
1290        */
1291       g_mutex_lock (&task_pool_mutex);
1292       if (g_thread_pool_set_max_threads (task_pool,
1293                                          g_thread_pool_get_max_threads (task_pool) + 1,
1294                                          NULL))
1295         task->blocking_other_task = TRUE;
1296       g_mutex_unlock (&task_pool_mutex);
1297     }
1298 }
1299
1300 /**
1301  * g_task_run_in_thread:
1302  * @task: a #GTask
1303  * @task_func: a #GTaskThreadFunc
1304  *
1305  * Runs @task_func in another thread. When @task_func returns, @task's
1306  * #GAsyncReadyCallback will be invoked in @task's #GMainContext.
1307  *
1308  * This takes a ref on @task until the task completes.
1309  *
1310  * See #GTaskThreadFunc for more details about how @task_func is handled.
1311  *
1312  * Since: 2.36
1313  */
1314 void
1315 g_task_run_in_thread (GTask           *task,
1316                       GTaskThreadFunc  task_func)
1317 {
1318   g_return_if_fail (G_IS_TASK (task));
1319
1320   g_object_ref (task);
1321   g_task_start_task_thread (task, task_func);
1322
1323   /* The task may already be cancelled, or g_thread_pool_push() may
1324    * have failed.
1325    */
1326   if (task->thread_complete)
1327     {
1328       g_mutex_unlock (&task->lock);
1329       g_task_return (task, G_TASK_RETURN_FROM_THREAD);
1330     }
1331   else
1332     g_mutex_unlock (&task->lock);
1333
1334   g_object_unref (task);
1335 }
1336
1337 /**
1338  * g_task_run_in_thread_sync:
1339  * @task: a #GTask
1340  * @task_func: a #GTaskThreadFunc
1341  *
1342  * Runs @task_func in another thread, and waits for it to return or be
1343  * cancelled. You can use g_task_propagate_pointer(), etc, afterward
1344  * to get the result of @task_func.
1345  *
1346  * See #GTaskThreadFunc for more details about how @task_func is handled.
1347  *
1348  * Normally this is used with tasks created with a %NULL
1349  * `callback`, but note that even if the task does
1350  * have a callback, it will not be invoked when @task_func returns.
1351  *
1352  * Since: 2.36
1353  */
1354 void
1355 g_task_run_in_thread_sync (GTask           *task,
1356                            GTaskThreadFunc  task_func)
1357 {
1358   g_return_if_fail (G_IS_TASK (task));
1359
1360   g_object_ref (task);
1361
1362   task->synchronous = TRUE;
1363   g_task_start_task_thread (task, task_func);
1364
1365   while (!task->thread_complete)
1366     g_cond_wait (&task->cond, &task->lock);
1367
1368   g_mutex_unlock (&task->lock);
1369   g_object_unref (task);
1370 }
1371
1372 /**
1373  * g_task_attach_source:
1374  * @task: a #GTask
1375  * @source: the source to attach
1376  * @callback: the callback to invoke when @source triggers
1377  *
1378  * A utility function for dealing with async operations where you need
1379  * to wait for a #GSource to trigger. Attaches @source to @task's
1380  * #GMainContext with @task's [priority][io-priority], and sets @source's
1381  * callback to @callback, with @task as the callback's `user_data`.
1382  *
1383  * This takes a reference on @task until @source is destroyed.
1384  *
1385  * Since: 2.36
1386  */
1387 void
1388 g_task_attach_source (GTask       *task,
1389                       GSource     *source,
1390                       GSourceFunc  callback)
1391 {
1392   g_source_set_callback (source, callback,
1393                          g_object_ref (task), g_object_unref);
1394   g_source_set_priority (source, task->priority);
1395   g_source_attach (source, task->context);
1396 }
1397
1398
1399 static gboolean
1400 g_task_propagate_error (GTask   *task,
1401                         GError **error)
1402 {
1403   if (task->check_cancellable &&
1404       g_cancellable_set_error_if_cancelled (task->cancellable, error))
1405     return TRUE;
1406   else if (task->error)
1407     {
1408       g_propagate_error (error, task->error);
1409       task->error = NULL;
1410       return TRUE;
1411     }
1412   else
1413     return FALSE;
1414 }
1415
1416 /**
1417  * g_task_return_pointer:
1418  * @task: a #GTask
1419  * @result: (allow-none) (transfer full): the pointer result of a task
1420  *     function
1421  * @result_destroy: (allow-none): a #GDestroyNotify function.
1422  *
1423  * Sets @task's result to @result and completes the task. If @result
1424  * is not %NULL, then @result_destroy will be used to free @result if
1425  * the caller does not take ownership of it with
1426  * g_task_propagate_pointer().
1427  *
1428  * "Completes the task" means that for an ordinary asynchronous task
1429  * it will either invoke the task's callback, or else queue that
1430  * callback to be invoked in the proper #GMainContext, or in the next
1431  * iteration of the current #GMainContext. For a task run via
1432  * g_task_run_in_thread() or g_task_run_in_thread_sync(), calling this
1433  * method will save @result to be returned to the caller later, but
1434  * the task will not actually be completed until the #GTaskThreadFunc
1435  * exits.
1436  *
1437  * Note that since the task may be completed before returning from
1438  * g_task_return_pointer(), you cannot assume that @result is still
1439  * valid after calling this, unless you are still holding another
1440  * reference on it.
1441  *
1442  * Since: 2.36
1443  */
1444 void
1445 g_task_return_pointer (GTask          *task,
1446                        gpointer        result,
1447                        GDestroyNotify  result_destroy)
1448 {
1449   g_return_if_fail (task->result_set == FALSE);
1450
1451   task->result.pointer = result;
1452   task->result_destroy = result_destroy;
1453
1454   g_task_return (task, G_TASK_RETURN_SUCCESS);
1455 }
1456
1457 /**
1458  * g_task_propagate_pointer:
1459  * @task: a #GTask
1460  * @error: return location for a #GError
1461  *
1462  * Gets the result of @task as a pointer, and transfers ownership
1463  * of that value to the caller.
1464  *
1465  * If the task resulted in an error, or was cancelled, then this will
1466  * instead return %NULL and set @error.
1467  *
1468  * Since this method transfers ownership of the return value (or
1469  * error) to the caller, you may only call it once.
1470  *
1471  * Returns: (transfer full): the task result, or %NULL on error
1472  *
1473  * Since: 2.36
1474  */
1475 gpointer
1476 g_task_propagate_pointer (GTask   *task,
1477                           GError **error)
1478 {
1479   if (g_task_propagate_error (task, error))
1480     return NULL;
1481
1482   g_return_val_if_fail (task->result_set == TRUE, NULL);
1483
1484   task->result_destroy = NULL;
1485   task->result_set = FALSE;
1486   return task->result.pointer;
1487 }
1488
1489 /**
1490  * g_task_return_int:
1491  * @task: a #GTask.
1492  * @result: the integer (#gssize) result of a task function.
1493  *
1494  * Sets @task's result to @result and completes the task (see
1495  * g_task_return_pointer() for more discussion of exactly what this
1496  * means).
1497  *
1498  * Since: 2.36
1499  */
1500 void
1501 g_task_return_int (GTask  *task,
1502                    gssize  result)
1503 {
1504   g_return_if_fail (task->result_set == FALSE);
1505
1506   task->result.size = result;
1507
1508   g_task_return (task, G_TASK_RETURN_SUCCESS);
1509 }
1510
1511 /**
1512  * g_task_propagate_int:
1513  * @task: a #GTask.
1514  * @error: return location for a #GError
1515  *
1516  * Gets the result of @task as an integer (#gssize).
1517  *
1518  * If the task resulted in an error, or was cancelled, then this will
1519  * instead return -1 and set @error.
1520  *
1521  * Since this method transfers ownership of the return value (or
1522  * error) to the caller, you may only call it once.
1523  *
1524  * Returns: the task result, or -1 on error
1525  *
1526  * Since: 2.36
1527  */
1528 gssize
1529 g_task_propagate_int (GTask   *task,
1530                       GError **error)
1531 {
1532   if (g_task_propagate_error (task, error))
1533     return -1;
1534
1535   g_return_val_if_fail (task->result_set == TRUE, -1);
1536
1537   task->result_set = FALSE;
1538   return task->result.size;
1539 }
1540
1541 /**
1542  * g_task_return_boolean:
1543  * @task: a #GTask.
1544  * @result: the #gboolean result of a task function.
1545  *
1546  * Sets @task's result to @result and completes the task (see
1547  * g_task_return_pointer() for more discussion of exactly what this
1548  * means).
1549  *
1550  * Since: 2.36
1551  */
1552 void
1553 g_task_return_boolean (GTask    *task,
1554                        gboolean  result)
1555 {
1556   g_return_if_fail (task->result_set == FALSE);
1557
1558   task->result.boolean = result;
1559
1560   g_task_return (task, G_TASK_RETURN_SUCCESS);
1561 }
1562
1563 /**
1564  * g_task_propagate_boolean:
1565  * @task: a #GTask.
1566  * @error: return location for a #GError
1567  *
1568  * Gets the result of @task as a #gboolean.
1569  *
1570  * If the task resulted in an error, or was cancelled, then this will
1571  * instead return %FALSE and set @error.
1572  *
1573  * Since this method transfers ownership of the return value (or
1574  * error) to the caller, you may only call it once.
1575  *
1576  * Returns: the task result, or %FALSE on error
1577  *
1578  * Since: 2.36
1579  */
1580 gboolean
1581 g_task_propagate_boolean (GTask   *task,
1582                           GError **error)
1583 {
1584   if (g_task_propagate_error (task, error))
1585     return FALSE;
1586
1587   g_return_val_if_fail (task->result_set == TRUE, FALSE);
1588
1589   task->result_set = FALSE;
1590   return task->result.boolean;
1591 }
1592
1593 /**
1594  * g_task_return_error:
1595  * @task: a #GTask.
1596  * @error: (transfer full): the #GError result of a task function.
1597  *
1598  * Sets @task's result to @error (which @task assumes ownership of)
1599  * and completes the task (see g_task_return_pointer() for more
1600  * discussion of exactly what this means).
1601  *
1602  * Note that since the task takes ownership of @error, and since the
1603  * task may be completed before returning from g_task_return_error(),
1604  * you cannot assume that @error is still valid after calling this.
1605  * Call g_error_copy() on the error if you need to keep a local copy
1606  * as well.
1607  *
1608  * See also g_task_return_new_error().
1609  *
1610  * Since: 2.36
1611  */
1612 void
1613 g_task_return_error (GTask  *task,
1614                      GError *error)
1615 {
1616   g_return_if_fail (task->result_set == FALSE);
1617   g_return_if_fail (error != NULL);
1618
1619   task->error = error;
1620
1621   g_task_return (task, G_TASK_RETURN_ERROR);
1622 }
1623
1624 /**
1625  * g_task_return_new_error:
1626  * @task: a #GTask.
1627  * @domain: a #GQuark.
1628  * @code: an error code.
1629  * @format: a string with format characters.
1630  * @...: a list of values to insert into @format.
1631  *
1632  * Sets @task's result to a new #GError created from @domain, @code,
1633  * @format, and the remaining arguments, and completes the task (see
1634  * g_task_return_pointer() for more discussion of exactly what this
1635  * means).
1636  *
1637  * See also g_task_return_error().
1638  *
1639  * Since: 2.36
1640  */
1641 void
1642 g_task_return_new_error (GTask           *task,
1643                          GQuark           domain,
1644                          gint             code,
1645                          const char      *format,
1646                          ...)
1647 {
1648   GError *error;
1649   va_list args;
1650
1651   va_start (args, format);
1652   error = g_error_new_valist (domain, code, format, args);
1653   va_end (args);
1654
1655   g_task_return_error (task, error);
1656 }
1657
1658 /**
1659  * g_task_return_error_if_cancelled:
1660  * @task: a #GTask
1661  *
1662  * Checks if @task's #GCancellable has been cancelled, and if so, sets
1663  * @task's error accordingly and completes the task (see
1664  * g_task_return_pointer() for more discussion of exactly what this
1665  * means).
1666  *
1667  * Return value: %TRUE if @task has been cancelled, %FALSE if not
1668  *
1669  * Since: 2.36
1670  */
1671 gboolean
1672 g_task_return_error_if_cancelled (GTask *task)
1673 {
1674   GError *error = NULL;
1675
1676   g_return_val_if_fail (task->result_set == FALSE, FALSE);
1677
1678   if (g_cancellable_set_error_if_cancelled (task->cancellable, &error))
1679     {
1680       /* We explicitly set task->error so this works even when
1681        * check-cancellable is not set.
1682        */
1683       g_clear_error (&task->error);
1684       task->error = error;
1685
1686       g_task_return (task, G_TASK_RETURN_ERROR);
1687       return TRUE;
1688     }
1689   else
1690     return FALSE;
1691 }
1692
1693 /**
1694  * g_task_had_error:
1695  * @task: a #GTask.
1696  *
1697  * Tests if @task resulted in an error.
1698  *
1699  * Returns: %TRUE if the task resulted in an error, %FALSE otherwise.
1700  *
1701  * Since: 2.36
1702  */
1703 gboolean
1704 g_task_had_error (GTask *task)
1705 {
1706   if (task->error != NULL)
1707     return TRUE;
1708
1709   if (task->check_cancellable && g_cancellable_is_cancelled (task->cancellable))
1710     return TRUE;
1711
1712   return FALSE;
1713 }
1714
1715 /**
1716  * g_task_is_valid:
1717  * @result: (type Gio.AsyncResult): A #GAsyncResult
1718  * @source_object: (allow-none) (type GObject): the source object
1719  *   expected to be associated with the task
1720  *
1721  * Checks that @result is a #GTask, and that @source_object is its
1722  * source object (or that @source_object is %NULL and @result has no
1723  * source object). This can be used in g_return_if_fail() checks.
1724  *
1725  * Return value: %TRUE if @result and @source_object are valid, %FALSE
1726  * if not
1727  *
1728  * Since: 2.36
1729  */
1730 gboolean
1731 g_task_is_valid (gpointer result,
1732                  gpointer source_object)
1733 {
1734   if (!G_IS_TASK (result))
1735     return FALSE;
1736
1737   return G_TASK (result)->source_object == source_object;
1738 }
1739
1740 static gint
1741 g_task_compare_priority (gconstpointer a,
1742                          gconstpointer b,
1743                          gpointer      user_data)
1744 {
1745   const GTask *ta = a;
1746   const GTask *tb = b;
1747   gboolean a_cancelled, b_cancelled;
1748
1749   /* Tasks that are causing other tasks to block have higher
1750    * priority.
1751    */
1752   if (ta->blocking_other_task && !tb->blocking_other_task)
1753     return -1;
1754   else if (tb->blocking_other_task && !ta->blocking_other_task)
1755     return 1;
1756
1757   /* Let already-cancelled tasks finish right away */
1758   a_cancelled = (ta->check_cancellable &&
1759                  g_cancellable_is_cancelled (ta->cancellable));
1760   b_cancelled = (tb->check_cancellable &&
1761                  g_cancellable_is_cancelled (tb->cancellable));
1762   if (a_cancelled && !b_cancelled)
1763     return -1;
1764   else if (b_cancelled && !a_cancelled)
1765     return 1;
1766
1767   /* Lower priority == run sooner == negative return value */
1768   return ta->priority - tb->priority;
1769 }
1770
1771 static void
1772 g_task_thread_pool_init (void)
1773 {
1774   task_pool = g_thread_pool_new (g_task_thread_pool_thread, NULL,
1775                                  10, FALSE, NULL);
1776   g_assert (task_pool != NULL);
1777
1778   g_thread_pool_set_sort_function (task_pool, g_task_compare_priority, NULL);
1779 }
1780
1781 static void
1782 g_task_thread_pool_resort (void)
1783 {
1784   g_thread_pool_set_sort_function (task_pool, g_task_compare_priority, NULL);
1785 }
1786
1787 static void
1788 g_task_class_init (GTaskClass *klass)
1789 {
1790   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
1791
1792   gobject_class->finalize = g_task_finalize;
1793 }
1794
1795 static gpointer
1796 g_task_get_user_data (GAsyncResult *res)
1797 {
1798   return G_TASK (res)->callback_data;
1799 }
1800
1801 static gboolean
1802 g_task_is_tagged (GAsyncResult *res,
1803                   gpointer      source_tag)
1804 {
1805   return G_TASK (res)->source_tag == source_tag;
1806 }
1807
1808 static void
1809 g_task_async_result_iface_init (GAsyncResultIface *iface)
1810 {
1811   iface->get_user_data = g_task_get_user_data;
1812   iface->get_source_object = g_task_ref_source_object;
1813   iface->is_tagged = g_task_is_tagged;
1814 }