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