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