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