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