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