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