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