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