Add Friulian translation
[glib.git] / gio / gtask.c
blob5a27674738cc65d3485f64102d48af1bd66c13da
1 /* GIO - GLib Input, Output and Streaming Library
3 * Copyright 2011 Red Hat, Inc.
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.
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.
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/>.
19 #include "config.h"
20 #include "gio_trace.h"
22 #include "gtask.h"
24 #include "gasyncresult.h"
25 #include "gcancellable.h"
26 #include "glib-private.h"
28 #include "glibintl.h"
30 /**
31 * SECTION:gtask
32 * @short_description: Cancellable synchronous or asynchronous task
33 * and result
34 * @include: gio/gio.h
35 * @see_also: #GAsyncResult
37 * A #GTask represents and manages a cancellable "task".
39 * ## Asynchronous operations
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.
56 * Here is an example for using GTask as a GAsyncResult:
57 * |[<!-- language="C" -->
58 * typedef struct {
59 * CakeFrostingType frosting;
60 * char *message;
61 * } DecorationData;
63 * static void
64 * decoration_data_free (DecorationData *decoration)
65 * {
66 * g_free (decoration->message);
67 * g_slice_free (DecorationData, decoration);
68 * }
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;
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 * }
86 * if (!cake_decorate (cake, decoration->frosting, decoration->message, &error))
87 * {
88 * g_object_unref (cake);
89 * // g_task_return_error() takes ownership of error
90 * g_task_return_error (task, error);
91 * g_object_unref (task);
92 * return;
93 * }
95 * g_task_return_pointer (task, cake, g_object_unref);
96 * g_object_unref (task);
97 * }
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)
109 * GTask *task;
110 * DecorationData *decoration;
111 * Cake *cake;
113 * task = g_task_new (self, cancellable, callback, user_data);
114 * if (radius < 3)
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;
123 * cake = _baker_get_cached_cake (self, radius, flavor, frosting, message);
124 * if (cake != NULL)
126 * // _baker_get_cached_cake() returns a reffed cake
127 * g_task_return_pointer (task, cake, g_object_unref);
128 * g_object_unref (task);
129 * return;
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);
137 * _baker_begin_cake (self, radius, flavor, cancellable, baked_cb, task);
140 * Cake *
141 * baker_bake_cake_finish (Baker *self,
142 * GAsyncResult *result,
143 * GError **error)
145 * g_return_val_if_fail (g_task_is_valid (result, self), NULL);
147 * return g_task_propagate_pointer (G_TASK (result), error);
149 * ]|
151 * ## Chained asynchronous operations
153 * #GTask also tries to simplify asynchronous operations that
154 * internally chain together several smaller asynchronous
155 * operations. g_task_get_cancellable(), g_task_get_context(),
156 * and g_task_get_priority() allow you to get back the task's
157 * #GCancellable, #GMainContext, and [I/O priority][io-priority]
158 * when starting a new subtask, so you don't have to keep track
159 * of them yourself. g_task_attach_source() simplifies the case
160 * of waiting for a source to fire (automatically using the correct
161 * #GMainContext and priority).
163 * Here is an example for chained asynchronous operations:
164 * |[<!-- language="C" -->
165 * typedef struct {
166 * Cake *cake;
167 * CakeFrostingType frosting;
168 * char *message;
169 * } BakingData;
171 * static void
172 * decoration_data_free (BakingData *bd)
174 * if (bd->cake)
175 * g_object_unref (bd->cake);
176 * g_free (bd->message);
177 * g_slice_free (BakingData, bd);
180 * static void
181 * decorated_cb (Cake *cake,
182 * GAsyncResult *result,
183 * gpointer user_data)
185 * GTask *task = user_data;
186 * GError *error = NULL;
188 * if (!cake_decorate_finish (cake, result, &error))
190 * g_object_unref (cake);
191 * g_task_return_error (task, error);
192 * g_object_unref (task);
193 * return;
196 * // baking_data_free() will drop its ref on the cake, so we have to
197 * // take another here to give to the caller.
198 * g_task_return_pointer (task, g_object_ref (cake), g_object_unref);
199 * g_object_unref (task);
202 * static gboolean
203 * decorator_ready (gpointer user_data)
205 * GTask *task = user_data;
206 * BakingData *bd = g_task_get_task_data (task);
208 * cake_decorate_async (bd->cake, bd->frosting, bd->message,
209 * g_task_get_cancellable (task),
210 * decorated_cb, task);
212 * return G_SOURCE_REMOVE;
215 * static void
216 * baked_cb (Cake *cake,
217 * gpointer user_data)
219 * GTask *task = user_data;
220 * BakingData *bd = g_task_get_task_data (task);
221 * GError *error = NULL;
223 * if (cake == NULL)
225 * g_task_return_new_error (task, BAKER_ERROR, BAKER_ERROR_NO_FLOUR,
226 * "Go to the supermarket");
227 * g_object_unref (task);
228 * return;
231 * bd->cake = cake;
233 * // Bail out now if the user has already cancelled
234 * if (g_task_return_error_if_cancelled (task))
236 * g_object_unref (task);
237 * return;
240 * if (cake_decorator_available (cake))
241 * decorator_ready (task);
242 * else
244 * GSource *source;
246 * source = cake_decorator_wait_source_new (cake);
247 * // Attach @source to @task's GMainContext and have it call
248 * // decorator_ready() when it is ready.
249 * g_task_attach_source (task, source, decorator_ready);
250 * g_source_unref (source);
254 * void
255 * baker_bake_cake_async (Baker *self,
256 * guint radius,
257 * CakeFlavor flavor,
258 * CakeFrostingType frosting,
259 * const char *message,
260 * gint priority,
261 * GCancellable *cancellable,
262 * GAsyncReadyCallback callback,
263 * gpointer user_data)
265 * GTask *task;
266 * BakingData *bd;
268 * task = g_task_new (self, cancellable, callback, user_data);
269 * g_task_set_priority (task, priority);
271 * bd = g_slice_new0 (BakingData);
272 * bd->frosting = frosting;
273 * bd->message = g_strdup (message);
274 * g_task_set_task_data (task, bd, (GDestroyNotify) baking_data_free);
276 * _baker_begin_cake (self, radius, flavor, cancellable, baked_cb, task);
279 * Cake *
280 * baker_bake_cake_finish (Baker *self,
281 * GAsyncResult *result,
282 * GError **error)
284 * g_return_val_if_fail (g_task_is_valid (result, self), NULL);
286 * return g_task_propagate_pointer (G_TASK (result), error);
288 * ]|
290 * ## Asynchronous operations from synchronous ones
292 * You can use g_task_run_in_thread() to turn a synchronous
293 * operation into an asynchronous one, by running it in a thread
294 * which will then dispatch the result back to the caller's
295 * #GMainContext when it completes.
297 * Running a task in a thread:
298 * |[<!-- language="C" -->
299 * typedef struct {
300 * guint radius;
301 * CakeFlavor flavor;
302 * CakeFrostingType frosting;
303 * char *message;
304 * } CakeData;
306 * static void
307 * cake_data_free (CakeData *cake_data)
309 * g_free (cake_data->message);
310 * g_slice_free (CakeData, cake_data);
313 * static void
314 * bake_cake_thread (GTask *task,
315 * gpointer source_object,
316 * gpointer task_data,
317 * GCancellable *cancellable)
319 * Baker *self = source_object;
320 * CakeData *cake_data = task_data;
321 * Cake *cake;
322 * GError *error = NULL;
324 * cake = bake_cake (baker, cake_data->radius, cake_data->flavor,
325 * cake_data->frosting, cake_data->message,
326 * cancellable, &error);
327 * if (cake)
328 * g_task_return_pointer (task, cake, g_object_unref);
329 * else
330 * g_task_return_error (task, error);
333 * void
334 * baker_bake_cake_async (Baker *self,
335 * guint radius,
336 * CakeFlavor flavor,
337 * CakeFrostingType frosting,
338 * const char *message,
339 * GCancellable *cancellable,
340 * GAsyncReadyCallback callback,
341 * gpointer user_data)
343 * CakeData *cake_data;
344 * GTask *task;
346 * cake_data = g_slice_new (CakeData);
347 * cake_data->radius = radius;
348 * cake_data->flavor = flavor;
349 * cake_data->frosting = frosting;
350 * cake_data->message = g_strdup (message);
351 * task = g_task_new (self, cancellable, callback, user_data);
352 * g_task_set_task_data (task, cake_data, (GDestroyNotify) cake_data_free);
353 * g_task_run_in_thread (task, bake_cake_thread);
354 * g_object_unref (task);
357 * Cake *
358 * baker_bake_cake_finish (Baker *self,
359 * GAsyncResult *result,
360 * GError **error)
362 * g_return_val_if_fail (g_task_is_valid (result, self), NULL);
364 * return g_task_propagate_pointer (G_TASK (result), error);
366 * ]|
368 * ## Adding cancellability to uncancellable tasks
370 * Finally, g_task_run_in_thread() and g_task_run_in_thread_sync()
371 * can be used to turn an uncancellable operation into a
372 * cancellable one. If you call g_task_set_return_on_cancel(),
373 * passing %TRUE, then if the task's #GCancellable is cancelled,
374 * it will return control back to the caller immediately, while
375 * allowing the task thread to continue running in the background
376 * (and simply discarding its result when it finally does finish).
377 * Provided that the task thread is careful about how it uses
378 * locks and other externally-visible resources, this allows you
379 * to make "GLib-friendly" asynchronous and cancellable
380 * synchronous variants of blocking APIs.
382 * Cancelling a task:
383 * |[<!-- language="C" -->
384 * static void
385 * bake_cake_thread (GTask *task,
386 * gpointer source_object,
387 * gpointer task_data,
388 * GCancellable *cancellable)
390 * Baker *self = source_object;
391 * CakeData *cake_data = task_data;
392 * Cake *cake;
393 * GError *error = NULL;
395 * cake = bake_cake (baker, cake_data->radius, cake_data->flavor,
396 * cake_data->frosting, cake_data->message,
397 * &error);
398 * if (error)
400 * g_task_return_error (task, error);
401 * return;
404 * // If the task has already been cancelled, then we don't want to add
405 * // the cake to the cake cache. Likewise, we don't want to have the
406 * // task get cancelled in the middle of updating the cache.
407 * // g_task_set_return_on_cancel() will return %TRUE here if it managed
408 * // to disable return-on-cancel, or %FALSE if the task was cancelled
409 * // before it could.
410 * if (g_task_set_return_on_cancel (task, FALSE))
412 * // If the caller cancels at this point, their
413 * // GAsyncReadyCallback won't be invoked until we return,
414 * // so we don't have to worry that this code will run at
415 * // the same time as that code does. But if there were
416 * // other functions that might look at the cake cache,
417 * // then we'd probably need a GMutex here as well.
418 * baker_add_cake_to_cache (baker, cake);
419 * g_task_return_pointer (task, cake, g_object_unref);
423 * void
424 * baker_bake_cake_async (Baker *self,
425 * guint radius,
426 * CakeFlavor flavor,
427 * CakeFrostingType frosting,
428 * const char *message,
429 * GCancellable *cancellable,
430 * GAsyncReadyCallback callback,
431 * gpointer user_data)
433 * CakeData *cake_data;
434 * GTask *task;
436 * cake_data = g_slice_new (CakeData);
438 * ...
440 * task = g_task_new (self, cancellable, callback, user_data);
441 * g_task_set_task_data (task, cake_data, (GDestroyNotify) cake_data_free);
442 * g_task_set_return_on_cancel (task, TRUE);
443 * g_task_run_in_thread (task, bake_cake_thread);
446 * Cake *
447 * baker_bake_cake_sync (Baker *self,
448 * guint radius,
449 * CakeFlavor flavor,
450 * CakeFrostingType frosting,
451 * const char *message,
452 * GCancellable *cancellable,
453 * GError **error)
455 * CakeData *cake_data;
456 * GTask *task;
457 * Cake *cake;
459 * cake_data = g_slice_new (CakeData);
461 * ...
463 * task = g_task_new (self, cancellable, NULL, NULL);
464 * g_task_set_task_data (task, cake_data, (GDestroyNotify) cake_data_free);
465 * g_task_set_return_on_cancel (task, TRUE);
466 * g_task_run_in_thread_sync (task, bake_cake_thread);
468 * cake = g_task_propagate_pointer (task, error);
469 * g_object_unref (task);
470 * return cake;
472 * ]|
474 * ## Porting from GSimpleAsyncResult
476 * #GTask's API attempts to be simpler than #GSimpleAsyncResult's
477 * in several ways:
478 * - You can save task-specific data with g_task_set_task_data(), and
479 * retrieve it later with g_task_get_task_data(). This replaces the
480 * abuse of g_simple_async_result_set_op_res_gpointer() for the same
481 * purpose with #GSimpleAsyncResult.
482 * - In addition to the task data, #GTask also keeps track of the
483 * [priority][io-priority], #GCancellable, and
484 * #GMainContext associated with the task, so tasks that consist of
485 * a chain of simpler asynchronous operations will have easy access
486 * to those values when starting each sub-task.
487 * - g_task_return_error_if_cancelled() provides simplified
488 * handling for cancellation. In addition, cancellation
489 * overrides any other #GTask return value by default, like
490 * #GSimpleAsyncResult does when
491 * g_simple_async_result_set_check_cancellable() is called.
492 * (You can use g_task_set_check_cancellable() to turn off that
493 * behavior.) On the other hand, g_task_run_in_thread()
494 * guarantees that it will always run your
495 * `task_func`, even if the task's #GCancellable
496 * is already cancelled before the task gets a chance to run;
497 * you can start your `task_func` with a
498 * g_task_return_error_if_cancelled() check if you need the
499 * old behavior.
500 * - The "return" methods (eg, g_task_return_pointer())
501 * automatically cause the task to be "completed" as well, and
502 * there is no need to worry about the "complete" vs "complete
503 * in idle" distinction. (#GTask automatically figures out
504 * whether the task's callback can be invoked directly, or
505 * if it needs to be sent to another #GMainContext, or delayed
506 * until the next iteration of the current #GMainContext.)
507 * - The "finish" functions for #GTask-based operations are generally
508 * much simpler than #GSimpleAsyncResult ones, normally consisting
509 * of only a single call to g_task_propagate_pointer() or the like.
510 * Since g_task_propagate_pointer() "steals" the return value from
511 * the #GTask, it is not necessary to juggle pointers around to
512 * prevent it from being freed twice.
513 * - With #GSimpleAsyncResult, it was common to call
514 * g_simple_async_result_propagate_error() from the
515 * `_finish()` wrapper function, and have
516 * virtual method implementations only deal with successful
517 * returns. This behavior is deprecated, because it makes it
518 * difficult for a subclass to chain to a parent class's async
519 * methods. Instead, the wrapper function should just be a
520 * simple wrapper, and the virtual method should call an
521 * appropriate `g_task_propagate_` function.
522 * Note that wrapper methods can now use
523 * g_async_result_legacy_propagate_error() to do old-style
524 * #GSimpleAsyncResult error-returning behavior, and
525 * g_async_result_is_tagged() to check if a result is tagged as
526 * having come from the `_async()` wrapper
527 * function (for "short-circuit" results, such as when passing
528 * 0 to g_input_stream_read_async()).
532 * GTask:
534 * The opaque object representing a synchronous or asynchronous task
535 * and its result.
538 struct _GTask {
539 GObject parent_instance;
541 gpointer source_object;
542 gpointer source_tag;
544 gpointer task_data;
545 GDestroyNotify task_data_destroy;
547 GMainContext *context;
548 gint64 creation_time;
549 gint priority;
550 GCancellable *cancellable;
551 gboolean check_cancellable;
553 GAsyncReadyCallback callback;
554 gpointer callback_data;
555 gboolean completed;
557 GTaskThreadFunc task_func;
558 GMutex lock;
559 GCond cond;
560 gboolean return_on_cancel;
561 gboolean thread_cancelled;
562 gboolean synchronous;
563 gboolean thread_complete;
564 gboolean blocking_other_task;
566 GError *error;
567 union {
568 gpointer pointer;
569 gssize size;
570 gboolean boolean;
571 } result;
572 GDestroyNotify result_destroy;
573 gboolean had_error;
574 gboolean result_set;
577 #define G_TASK_IS_THREADED(task) ((task)->task_func != NULL)
579 struct _GTaskClass
581 GObjectClass parent_class;
584 typedef enum
586 PROP_COMPLETED = 1,
587 } GTaskProperty;
589 static void g_task_async_result_iface_init (GAsyncResultIface *iface);
590 static void g_task_thread_pool_init (void);
592 G_DEFINE_TYPE_WITH_CODE (GTask, g_task, G_TYPE_OBJECT,
593 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_RESULT,
594 g_task_async_result_iface_init);
595 g_task_thread_pool_init ();)
597 static GThreadPool *task_pool;
598 static GMutex task_pool_mutex;
599 static GPrivate task_private = G_PRIVATE_INIT (NULL);
600 static GSource *task_pool_manager;
601 static guint64 task_wait_time;
602 static gint tasks_running;
604 /* When the task pool fills up and blocks, and the program keeps
605 * queueing more tasks, we will slowly add more threads to the pool
606 * (in case the existing tasks are trying to queue subtasks of their
607 * own) until tasks start completing again. These "overflow" threads
608 * will only run one task apiece, and then exit, so the pool will
609 * eventually get back down to its base size.
611 * The base and multiplier below gives us 10 extra threads after about
612 * a second of blocking, 30 after 5 seconds, 100 after a minute, and
613 * 200 after 20 minutes.
615 #define G_TASK_POOL_SIZE 10
616 #define G_TASK_WAIT_TIME_BASE 100000
617 #define G_TASK_WAIT_TIME_MULTIPLIER 1.03
618 #define G_TASK_WAIT_TIME_MAX (30 * 60 * 1000000)
620 static void
621 g_task_init (GTask *task)
623 task->check_cancellable = TRUE;
626 static void
627 g_task_finalize (GObject *object)
629 GTask *task = G_TASK (object);
631 g_clear_object (&task->source_object);
632 g_clear_object (&task->cancellable);
634 if (task->context)
635 g_main_context_unref (task->context);
637 if (task->task_data_destroy)
638 task->task_data_destroy (task->task_data);
640 if (task->result_destroy && task->result.pointer)
641 task->result_destroy (task->result.pointer);
643 if (task->error)
644 g_error_free (task->error);
646 if (G_TASK_IS_THREADED (task))
648 g_mutex_clear (&task->lock);
649 g_cond_clear (&task->cond);
652 G_OBJECT_CLASS (g_task_parent_class)->finalize (object);
656 * g_task_new:
657 * @source_object: (nullable) (type GObject): the #GObject that owns
658 * this task, or %NULL.
659 * @cancellable: (nullable): optional #GCancellable object, %NULL to ignore.
660 * @callback: (scope async): a #GAsyncReadyCallback.
661 * @callback_data: (closure): user data passed to @callback.
663 * Creates a #GTask acting on @source_object, which will eventually be
664 * used to invoke @callback in the current
665 * [thread-default main context][g-main-context-push-thread-default].
667 * Call this in the "start" method of your asynchronous method, and
668 * pass the #GTask around throughout the asynchronous operation. You
669 * can use g_task_set_task_data() to attach task-specific data to the
670 * object, which you can retrieve later via g_task_get_task_data().
672 * By default, if @cancellable is cancelled, then the return value of
673 * the task will always be %G_IO_ERROR_CANCELLED, even if the task had
674 * already completed before the cancellation. This allows for
675 * simplified handling in cases where cancellation may imply that
676 * other objects that the task depends on have been destroyed. If you
677 * do not want this behavior, you can use
678 * g_task_set_check_cancellable() to change it.
680 * Returns: a #GTask.
682 * Since: 2.36
684 GTask *
685 g_task_new (gpointer source_object,
686 GCancellable *cancellable,
687 GAsyncReadyCallback callback,
688 gpointer callback_data)
690 GTask *task;
691 GSource *source;
693 task = g_object_new (G_TYPE_TASK, NULL);
694 task->source_object = source_object ? g_object_ref (source_object) : NULL;
695 task->cancellable = cancellable ? g_object_ref (cancellable) : NULL;
696 task->callback = callback;
697 task->callback_data = callback_data;
698 task->context = g_main_context_ref_thread_default ();
700 source = g_main_current_source ();
701 if (source)
702 task->creation_time = g_source_get_time (source);
704 TRACE (GIO_TASK_NEW (task, source_object, cancellable,
705 callback, callback_data));
707 return task;
711 * g_task_report_error:
712 * @source_object: (nullable) (type GObject): the #GObject that owns
713 * this task, or %NULL.
714 * @callback: (scope async): a #GAsyncReadyCallback.
715 * @callback_data: (closure): user data passed to @callback.
716 * @source_tag: an opaque pointer indicating the source of this task
717 * @error: (transfer full): error to report
719 * Creates a #GTask and then immediately calls g_task_return_error()
720 * on it. Use this in the wrapper function of an asynchronous method
721 * when you want to avoid even calling the virtual method. You can
722 * then use g_async_result_is_tagged() in the finish method wrapper to
723 * check if the result there is tagged as having been created by the
724 * wrapper method, and deal with it appropriately if so.
726 * See also g_task_report_new_error().
728 * Since: 2.36
730 void
731 g_task_report_error (gpointer source_object,
732 GAsyncReadyCallback callback,
733 gpointer callback_data,
734 gpointer source_tag,
735 GError *error)
737 GTask *task;
739 task = g_task_new (source_object, NULL, callback, callback_data);
740 g_task_set_source_tag (task, source_tag);
741 g_task_return_error (task, error);
742 g_object_unref (task);
746 * g_task_report_new_error:
747 * @source_object: (nullable) (type GObject): the #GObject that owns
748 * this task, or %NULL.
749 * @callback: (scope async): a #GAsyncReadyCallback.
750 * @callback_data: (closure): user data passed to @callback.
751 * @source_tag: an opaque pointer indicating the source of this task
752 * @domain: a #GQuark.
753 * @code: an error code.
754 * @format: a string with format characters.
755 * @...: a list of values to insert into @format.
757 * Creates a #GTask and then immediately calls
758 * g_task_return_new_error() on it. Use this in the wrapper function
759 * of an asynchronous method when you want to avoid even calling the
760 * virtual method. You can then use g_async_result_is_tagged() in the
761 * finish method wrapper to check if the result there is tagged as
762 * having been created by the wrapper method, and deal with it
763 * appropriately if so.
765 * See also g_task_report_error().
767 * Since: 2.36
769 void
770 g_task_report_new_error (gpointer source_object,
771 GAsyncReadyCallback callback,
772 gpointer callback_data,
773 gpointer source_tag,
774 GQuark domain,
775 gint code,
776 const char *format,
777 ...)
779 GError *error;
780 va_list ap;
782 va_start (ap, format);
783 error = g_error_new_valist (domain, code, format, ap);
784 va_end (ap);
786 g_task_report_error (source_object, callback, callback_data,
787 source_tag, error);
791 * g_task_set_task_data:
792 * @task: the #GTask
793 * @task_data: (nullable): task-specific data
794 * @task_data_destroy: (nullable): #GDestroyNotify for @task_data
796 * Sets @task's task data (freeing the existing task data, if any).
798 * Since: 2.36
800 void
801 g_task_set_task_data (GTask *task,
802 gpointer task_data,
803 GDestroyNotify task_data_destroy)
805 g_return_if_fail (G_IS_TASK (task));
807 if (task->task_data_destroy)
808 task->task_data_destroy (task->task_data);
810 task->task_data = task_data;
811 task->task_data_destroy = task_data_destroy;
813 TRACE (GIO_TASK_SET_TASK_DATA (task, task_data, task_data_destroy));
817 * g_task_set_priority:
818 * @task: the #GTask
819 * @priority: the [priority][io-priority] of the request
821 * Sets @task's priority. If you do not call this, it will default to
822 * %G_PRIORITY_DEFAULT.
824 * This will affect the priority of #GSources created with
825 * g_task_attach_source() and the scheduling of tasks run in threads,
826 * and can also be explicitly retrieved later via
827 * g_task_get_priority().
829 * Since: 2.36
831 void
832 g_task_set_priority (GTask *task,
833 gint priority)
835 g_return_if_fail (G_IS_TASK (task));
837 task->priority = priority;
839 TRACE (GIO_TASK_SET_PRIORITY (task, priority));
843 * g_task_set_check_cancellable:
844 * @task: the #GTask
845 * @check_cancellable: whether #GTask will check the state of
846 * its #GCancellable for you.
848 * Sets or clears @task's check-cancellable flag. If this is %TRUE
849 * (the default), then g_task_propagate_pointer(), etc, and
850 * g_task_had_error() will check the task's #GCancellable first, and
851 * if it has been cancelled, then they will consider the task to have
852 * returned an "Operation was cancelled" error
853 * (%G_IO_ERROR_CANCELLED), regardless of any other error or return
854 * value the task may have had.
856 * If @check_cancellable is %FALSE, then the #GTask will not check the
857 * cancellable itself, and it is up to @task's owner to do this (eg,
858 * via g_task_return_error_if_cancelled()).
860 * If you are using g_task_set_return_on_cancel() as well, then
861 * you must leave check-cancellable set %TRUE.
863 * Since: 2.36
865 void
866 g_task_set_check_cancellable (GTask *task,
867 gboolean check_cancellable)
869 g_return_if_fail (G_IS_TASK (task));
870 g_return_if_fail (check_cancellable || !task->return_on_cancel);
872 task->check_cancellable = check_cancellable;
875 static void g_task_thread_complete (GTask *task);
878 * g_task_set_return_on_cancel:
879 * @task: the #GTask
880 * @return_on_cancel: whether the task returns automatically when
881 * it is cancelled.
883 * Sets or clears @task's return-on-cancel flag. This is only
884 * meaningful for tasks run via g_task_run_in_thread() or
885 * g_task_run_in_thread_sync().
887 * If @return_on_cancel is %TRUE, then cancelling @task's
888 * #GCancellable will immediately cause it to return, as though the
889 * task's #GTaskThreadFunc had called
890 * g_task_return_error_if_cancelled() and then returned.
892 * This allows you to create a cancellable wrapper around an
893 * uninterruptable function. The #GTaskThreadFunc just needs to be
894 * careful that it does not modify any externally-visible state after
895 * it has been cancelled. To do that, the thread should call
896 * g_task_set_return_on_cancel() again to (atomically) set
897 * return-on-cancel %FALSE before making externally-visible changes;
898 * if the task gets cancelled before the return-on-cancel flag could
899 * be changed, g_task_set_return_on_cancel() will indicate this by
900 * returning %FALSE.
902 * You can disable and re-enable this flag multiple times if you wish.
903 * If the task's #GCancellable is cancelled while return-on-cancel is
904 * %FALSE, then calling g_task_set_return_on_cancel() to set it %TRUE
905 * again will cause the task to be cancelled at that point.
907 * If the task's #GCancellable is already cancelled before you call
908 * g_task_run_in_thread()/g_task_run_in_thread_sync(), then the
909 * #GTaskThreadFunc will still be run (for consistency), but the task
910 * will also be completed right away.
912 * Returns: %TRUE if @task's return-on-cancel flag was changed to
913 * match @return_on_cancel. %FALSE if @task has already been
914 * cancelled.
916 * Since: 2.36
918 gboolean
919 g_task_set_return_on_cancel (GTask *task,
920 gboolean return_on_cancel)
922 g_return_val_if_fail (G_IS_TASK (task), FALSE);
923 g_return_val_if_fail (task->check_cancellable || !return_on_cancel, FALSE);
925 if (!G_TASK_IS_THREADED (task))
927 task->return_on_cancel = return_on_cancel;
928 return TRUE;
931 g_mutex_lock (&task->lock);
932 if (task->thread_cancelled)
934 if (return_on_cancel && !task->return_on_cancel)
936 g_mutex_unlock (&task->lock);
937 g_task_thread_complete (task);
939 else
940 g_mutex_unlock (&task->lock);
941 return FALSE;
943 task->return_on_cancel = return_on_cancel;
944 g_mutex_unlock (&task->lock);
946 return TRUE;
950 * g_task_set_source_tag:
951 * @task: the #GTask
952 * @source_tag: an opaque pointer indicating the source of this task
954 * Sets @task's source tag. You can use this to tag a task return
955 * value with a particular pointer (usually a pointer to the function
956 * doing the tagging) and then later check it using
957 * g_task_get_source_tag() (or g_async_result_is_tagged()) in the
958 * task's "finish" function, to figure out if the response came from a
959 * particular place.
961 * Since: 2.36
963 void
964 g_task_set_source_tag (GTask *task,
965 gpointer source_tag)
967 g_return_if_fail (G_IS_TASK (task));
969 task->source_tag = source_tag;
971 TRACE (GIO_TASK_SET_SOURCE_TAG (task, source_tag));
975 * g_task_get_source_object:
976 * @task: a #GTask
978 * Gets the source object from @task. Like
979 * g_async_result_get_source_object(), but does not ref the object.
981 * Returns: (transfer none) (type GObject): @task's source object, or %NULL
983 * Since: 2.36
985 gpointer
986 g_task_get_source_object (GTask *task)
988 g_return_val_if_fail (G_IS_TASK (task), NULL);
990 return task->source_object;
993 static GObject *
994 g_task_ref_source_object (GAsyncResult *res)
996 GTask *task = G_TASK (res);
998 if (task->source_object)
999 return g_object_ref (task->source_object);
1000 else
1001 return NULL;
1005 * g_task_get_task_data:
1006 * @task: a #GTask
1008 * Gets @task's `task_data`.
1010 * Returns: (transfer none): @task's `task_data`.
1012 * Since: 2.36
1014 gpointer
1015 g_task_get_task_data (GTask *task)
1017 g_return_val_if_fail (G_IS_TASK (task), NULL);
1019 return task->task_data;
1023 * g_task_get_priority:
1024 * @task: a #GTask
1026 * Gets @task's priority
1028 * Returns: @task's priority
1030 * Since: 2.36
1032 gint
1033 g_task_get_priority (GTask *task)
1035 g_return_val_if_fail (G_IS_TASK (task), G_PRIORITY_DEFAULT);
1037 return task->priority;
1041 * g_task_get_context:
1042 * @task: a #GTask
1044 * Gets the #GMainContext that @task will return its result in (that
1045 * is, the context that was the
1046 * [thread-default main context][g-main-context-push-thread-default]
1047 * at the point when @task was created).
1049 * This will always return a non-%NULL value, even if the task's
1050 * context is the default #GMainContext.
1052 * Returns: (transfer none): @task's #GMainContext
1054 * Since: 2.36
1056 GMainContext *
1057 g_task_get_context (GTask *task)
1059 g_return_val_if_fail (G_IS_TASK (task), NULL);
1061 return task->context;
1065 * g_task_get_cancellable:
1066 * @task: a #GTask
1068 * Gets @task's #GCancellable
1070 * Returns: (transfer none): @task's #GCancellable
1072 * Since: 2.36
1074 GCancellable *
1075 g_task_get_cancellable (GTask *task)
1077 g_return_val_if_fail (G_IS_TASK (task), NULL);
1079 return task->cancellable;
1083 * g_task_get_check_cancellable:
1084 * @task: the #GTask
1086 * Gets @task's check-cancellable flag. See
1087 * g_task_set_check_cancellable() for more details.
1089 * Since: 2.36
1091 gboolean
1092 g_task_get_check_cancellable (GTask *task)
1094 g_return_val_if_fail (G_IS_TASK (task), FALSE);
1096 return task->check_cancellable;
1100 * g_task_get_return_on_cancel:
1101 * @task: the #GTask
1103 * Gets @task's return-on-cancel flag. See
1104 * g_task_set_return_on_cancel() for more details.
1106 * Since: 2.36
1108 gboolean
1109 g_task_get_return_on_cancel (GTask *task)
1111 g_return_val_if_fail (G_IS_TASK (task), FALSE);
1113 return task->return_on_cancel;
1117 * g_task_get_source_tag:
1118 * @task: a #GTask
1120 * Gets @task's source tag. See g_task_set_source_tag().
1122 * Returns: (transfer none): @task's source tag
1124 * Since: 2.36
1126 gpointer
1127 g_task_get_source_tag (GTask *task)
1129 g_return_val_if_fail (G_IS_TASK (task), NULL);
1131 return task->source_tag;
1135 static void
1136 g_task_return_now (GTask *task)
1138 TRACE (GIO_TASK_BEFORE_RETURN (task, task->source_object, task->callback,
1139 task->callback_data));
1141 g_main_context_push_thread_default (task->context);
1143 if (task->callback != NULL)
1145 task->callback (task->source_object,
1146 G_ASYNC_RESULT (task),
1147 task->callback_data);
1150 task->completed = TRUE;
1151 g_object_notify (G_OBJECT (task), "completed");
1153 g_main_context_pop_thread_default (task->context);
1156 static gboolean
1157 complete_in_idle_cb (gpointer task)
1159 g_task_return_now (task);
1160 g_object_unref (task);
1161 return FALSE;
1164 typedef enum {
1165 G_TASK_RETURN_SUCCESS,
1166 G_TASK_RETURN_ERROR,
1167 G_TASK_RETURN_FROM_THREAD
1168 } GTaskReturnType;
1170 static void
1171 g_task_return (GTask *task,
1172 GTaskReturnType type)
1174 GSource *source;
1176 if (type == G_TASK_RETURN_SUCCESS)
1177 task->result_set = TRUE;
1179 if (task->synchronous)
1180 return;
1182 /* Normally we want to invoke the task's callback when its return
1183 * value is set. But if the task is running in a thread, then we
1184 * want to wait until after the task_func returns, to simplify
1185 * locking/refcounting/etc.
1187 if (G_TASK_IS_THREADED (task) && type != G_TASK_RETURN_FROM_THREAD)
1188 return;
1190 g_object_ref (task);
1192 /* See if we can complete the task immediately. First, we have to be
1193 * running inside the task's thread/GMainContext.
1195 source = g_main_current_source ();
1196 if (source && g_source_get_context (source) == task->context)
1198 /* Second, we can only complete immediately if this is not the
1199 * same iteration of the main loop that the task was created in.
1201 if (g_source_get_time (source) > task->creation_time)
1203 g_task_return_now (task);
1204 g_object_unref (task);
1205 return;
1209 /* Otherwise, complete in the next iteration */
1210 source = g_idle_source_new ();
1211 g_source_set_name (source, "[gio] complete_in_idle_cb");
1212 g_task_attach_source (task, source, complete_in_idle_cb);
1213 g_source_unref (source);
1218 * GTaskThreadFunc:
1219 * @task: the #GTask
1220 * @source_object: (type GObject): @task's source object
1221 * @task_data: @task's task data
1222 * @cancellable: @task's #GCancellable, or %NULL
1224 * The prototype for a task function to be run in a thread via
1225 * g_task_run_in_thread() or g_task_run_in_thread_sync().
1227 * If the return-on-cancel flag is set on @task, and @cancellable gets
1228 * cancelled, then the #GTask will be completed immediately (as though
1229 * g_task_return_error_if_cancelled() had been called), without
1230 * waiting for the task function to complete. However, the task
1231 * function will continue running in its thread in the background. The
1232 * function therefore needs to be careful about how it uses
1233 * externally-visible state in this case. See
1234 * g_task_set_return_on_cancel() for more details.
1236 * Other than in that case, @task will be completed when the
1237 * #GTaskThreadFunc returns, not when it calls a
1238 * `g_task_return_` function.
1240 * Since: 2.36
1243 static void task_thread_cancelled (GCancellable *cancellable,
1244 gpointer user_data);
1246 static void
1247 g_task_thread_complete (GTask *task)
1249 g_mutex_lock (&task->lock);
1250 if (task->thread_complete)
1252 /* The task belatedly completed after having been cancelled
1253 * (or was cancelled in the midst of being completed).
1255 g_mutex_unlock (&task->lock);
1256 return;
1259 TRACE (GIO_TASK_AFTER_RUN_IN_THREAD (task, task->thread_cancelled));
1261 task->thread_complete = TRUE;
1262 g_mutex_unlock (&task->lock);
1264 if (task->cancellable)
1265 g_signal_handlers_disconnect_by_func (task->cancellable, task_thread_cancelled, task);
1267 if (task->synchronous)
1268 g_cond_signal (&task->cond);
1269 else
1270 g_task_return (task, G_TASK_RETURN_FROM_THREAD);
1273 static gboolean
1274 task_pool_manager_timeout (gpointer user_data)
1276 g_mutex_lock (&task_pool_mutex);
1277 g_thread_pool_set_max_threads (task_pool, tasks_running + 1, NULL);
1278 g_source_set_ready_time (task_pool_manager, -1);
1279 g_mutex_unlock (&task_pool_mutex);
1281 return TRUE;
1284 static void
1285 g_task_thread_setup (void)
1287 g_private_set (&task_private, GUINT_TO_POINTER (TRUE));
1288 g_mutex_lock (&task_pool_mutex);
1289 tasks_running++;
1291 if (tasks_running == G_TASK_POOL_SIZE)
1292 task_wait_time = G_TASK_WAIT_TIME_BASE;
1293 else if (tasks_running > G_TASK_POOL_SIZE && task_wait_time < G_TASK_WAIT_TIME_MAX)
1294 task_wait_time *= G_TASK_WAIT_TIME_MULTIPLIER;
1296 if (tasks_running >= G_TASK_POOL_SIZE)
1297 g_source_set_ready_time (task_pool_manager, g_get_monotonic_time () + task_wait_time);
1299 g_mutex_unlock (&task_pool_mutex);
1302 static void
1303 g_task_thread_cleanup (void)
1305 gint tasks_pending;
1307 g_mutex_lock (&task_pool_mutex);
1308 tasks_pending = g_thread_pool_unprocessed (task_pool);
1310 if (tasks_running > G_TASK_POOL_SIZE)
1311 g_thread_pool_set_max_threads (task_pool, tasks_running - 1, NULL);
1312 else if (tasks_running + tasks_pending < G_TASK_POOL_SIZE)
1313 g_source_set_ready_time (task_pool_manager, -1);
1315 tasks_running--;
1316 g_mutex_unlock (&task_pool_mutex);
1317 g_private_set (&task_private, GUINT_TO_POINTER (FALSE));
1320 static void
1321 g_task_thread_pool_thread (gpointer thread_data,
1322 gpointer pool_data)
1324 GTask *task = thread_data;
1326 g_task_thread_setup ();
1328 task->task_func (task, task->source_object, task->task_data,
1329 task->cancellable);
1330 g_task_thread_complete (task);
1331 g_object_unref (task);
1333 g_task_thread_cleanup ();
1336 static void
1337 task_thread_cancelled (GCancellable *cancellable,
1338 gpointer user_data)
1340 GTask *task = user_data;
1342 /* Move this task to the front of the queue - no need for
1343 * a complete resorting of the queue.
1345 g_thread_pool_move_to_front (task_pool, task);
1347 g_mutex_lock (&task->lock);
1348 task->thread_cancelled = TRUE;
1350 if (!task->return_on_cancel)
1352 g_mutex_unlock (&task->lock);
1353 return;
1356 /* We don't actually set task->error; g_task_return_error() doesn't
1357 * use a lock, and g_task_propagate_error() will call
1358 * g_cancellable_set_error_if_cancelled() anyway.
1360 g_mutex_unlock (&task->lock);
1361 g_task_thread_complete (task);
1364 static void
1365 task_thread_cancelled_disconnect_notify (gpointer task,
1366 GClosure *closure)
1368 g_object_unref (task);
1371 static void
1372 g_task_start_task_thread (GTask *task,
1373 GTaskThreadFunc task_func)
1375 g_mutex_init (&task->lock);
1376 g_cond_init (&task->cond);
1378 g_mutex_lock (&task->lock);
1380 TRACE (GIO_TASK_BEFORE_RUN_IN_THREAD (task, task_func));
1382 task->task_func = task_func;
1384 if (task->cancellable)
1386 if (task->return_on_cancel &&
1387 g_cancellable_set_error_if_cancelled (task->cancellable,
1388 &task->error))
1390 task->thread_cancelled = task->thread_complete = TRUE;
1391 TRACE (GIO_TASK_AFTER_RUN_IN_THREAD (task, task->thread_cancelled));
1392 g_thread_pool_push (task_pool, g_object_ref (task), NULL);
1393 return;
1396 /* This introduces a reference count loop between the GTask and
1397 * GCancellable, but is necessary to avoid a race on finalising the GTask
1398 * between task_thread_cancelled() (in one thread) and
1399 * g_task_thread_complete() (in another).
1401 * Accordingly, the signal handler *must* be removed once the task has
1402 * completed.
1404 g_signal_connect_data (task->cancellable, "cancelled",
1405 G_CALLBACK (task_thread_cancelled),
1406 g_object_ref (task),
1407 task_thread_cancelled_disconnect_notify, 0);
1410 if (g_private_get (&task_private))
1411 task->blocking_other_task = TRUE;
1412 g_thread_pool_push (task_pool, g_object_ref (task), NULL);
1416 * g_task_run_in_thread:
1417 * @task: a #GTask
1418 * @task_func: a #GTaskThreadFunc
1420 * Runs @task_func in another thread. When @task_func returns, @task's
1421 * #GAsyncReadyCallback will be invoked in @task's #GMainContext.
1423 * This takes a ref on @task until the task completes.
1425 * See #GTaskThreadFunc for more details about how @task_func is handled.
1427 * Although GLib currently rate-limits the tasks queued via
1428 * g_task_run_in_thread(), you should not assume that it will always
1429 * do this. If you have a very large number of tasks to run, but don't
1430 * want them to all run at once, you should only queue a limited
1431 * number of them at a time.
1433 * Since: 2.36
1435 void
1436 g_task_run_in_thread (GTask *task,
1437 GTaskThreadFunc task_func)
1439 g_return_if_fail (G_IS_TASK (task));
1441 g_object_ref (task);
1442 g_task_start_task_thread (task, task_func);
1444 /* The task may already be cancelled, or g_thread_pool_push() may
1445 * have failed.
1447 if (task->thread_complete)
1449 g_mutex_unlock (&task->lock);
1450 g_task_return (task, G_TASK_RETURN_FROM_THREAD);
1452 else
1453 g_mutex_unlock (&task->lock);
1455 g_object_unref (task);
1459 * g_task_run_in_thread_sync:
1460 * @task: a #GTask
1461 * @task_func: a #GTaskThreadFunc
1463 * Runs @task_func in another thread, and waits for it to return or be
1464 * cancelled. You can use g_task_propagate_pointer(), etc, afterward
1465 * to get the result of @task_func.
1467 * See #GTaskThreadFunc for more details about how @task_func is handled.
1469 * Normally this is used with tasks created with a %NULL
1470 * `callback`, but note that even if the task does
1471 * have a callback, it will not be invoked when @task_func returns.
1472 * #GTask:completed will be set to %TRUE just before this function returns.
1474 * Although GLib currently rate-limits the tasks queued via
1475 * g_task_run_in_thread_sync(), you should not assume that it will
1476 * always do this. If you have a very large number of tasks to run,
1477 * but don't want them to all run at once, you should only queue a
1478 * limited number of them at a time.
1480 * Since: 2.36
1482 void
1483 g_task_run_in_thread_sync (GTask *task,
1484 GTaskThreadFunc task_func)
1486 g_return_if_fail (G_IS_TASK (task));
1488 g_object_ref (task);
1490 task->synchronous = TRUE;
1491 g_task_start_task_thread (task, task_func);
1493 while (!task->thread_complete)
1494 g_cond_wait (&task->cond, &task->lock);
1496 g_mutex_unlock (&task->lock);
1498 TRACE (GIO_TASK_BEFORE_RETURN (task, task->source_object,
1499 NULL /* callback */,
1500 NULL /* callback data */));
1502 /* Notify of completion in this thread. */
1503 task->completed = TRUE;
1504 g_object_notify (G_OBJECT (task), "completed");
1506 g_object_unref (task);
1510 * g_task_attach_source:
1511 * @task: a #GTask
1512 * @source: the source to attach
1513 * @callback: the callback to invoke when @source triggers
1515 * A utility function for dealing with async operations where you need
1516 * to wait for a #GSource to trigger. Attaches @source to @task's
1517 * #GMainContext with @task's [priority][io-priority], and sets @source's
1518 * callback to @callback, with @task as the callback's `user_data`.
1520 * This takes a reference on @task until @source is destroyed.
1522 * Since: 2.36
1524 void
1525 g_task_attach_source (GTask *task,
1526 GSource *source,
1527 GSourceFunc callback)
1529 g_return_if_fail (G_IS_TASK (task));
1531 g_source_set_callback (source, callback,
1532 g_object_ref (task), g_object_unref);
1533 g_source_set_priority (source, task->priority);
1534 g_source_attach (source, task->context);
1538 static gboolean
1539 g_task_propagate_error (GTask *task,
1540 GError **error)
1542 gboolean error_set;
1544 if (task->check_cancellable &&
1545 g_cancellable_set_error_if_cancelled (task->cancellable, error))
1546 error_set = TRUE;
1547 else if (task->error)
1549 g_propagate_error (error, task->error);
1550 task->error = NULL;
1551 task->had_error = TRUE;
1552 error_set = TRUE;
1554 else
1555 error_set = FALSE;
1557 TRACE (GIO_TASK_PROPAGATE (task, error_set));
1559 return error_set;
1563 * g_task_return_pointer:
1564 * @task: a #GTask
1565 * @result: (nullable) (transfer full): the pointer result of a task
1566 * function
1567 * @result_destroy: (nullable): a #GDestroyNotify function.
1569 * Sets @task's result to @result and completes the task. If @result
1570 * is not %NULL, then @result_destroy will be used to free @result if
1571 * the caller does not take ownership of it with
1572 * g_task_propagate_pointer().
1574 * "Completes the task" means that for an ordinary asynchronous task
1575 * it will either invoke the task's callback, or else queue that
1576 * callback to be invoked in the proper #GMainContext, or in the next
1577 * iteration of the current #GMainContext. For a task run via
1578 * g_task_run_in_thread() or g_task_run_in_thread_sync(), calling this
1579 * method will save @result to be returned to the caller later, but
1580 * the task will not actually be completed until the #GTaskThreadFunc
1581 * exits.
1583 * Note that since the task may be completed before returning from
1584 * g_task_return_pointer(), you cannot assume that @result is still
1585 * valid after calling this, unless you are still holding another
1586 * reference on it.
1588 * Since: 2.36
1590 void
1591 g_task_return_pointer (GTask *task,
1592 gpointer result,
1593 GDestroyNotify result_destroy)
1595 g_return_if_fail (G_IS_TASK (task));
1596 g_return_if_fail (task->result_set == FALSE);
1598 task->result.pointer = result;
1599 task->result_destroy = result_destroy;
1601 g_task_return (task, G_TASK_RETURN_SUCCESS);
1605 * g_task_propagate_pointer:
1606 * @task: a #GTask
1607 * @error: return location for a #GError
1609 * Gets the result of @task as a pointer, and transfers ownership
1610 * of that value to the caller.
1612 * If the task resulted in an error, or was cancelled, then this will
1613 * instead return %NULL and set @error.
1615 * Since this method transfers ownership of the return value (or
1616 * error) to the caller, you may only call it once.
1618 * Returns: (transfer full): the task result, or %NULL on error
1620 * Since: 2.36
1622 gpointer
1623 g_task_propagate_pointer (GTask *task,
1624 GError **error)
1626 g_return_val_if_fail (G_IS_TASK (task), NULL);
1628 if (g_task_propagate_error (task, error))
1629 return NULL;
1631 g_return_val_if_fail (task->result_set == TRUE, NULL);
1633 task->result_destroy = NULL;
1634 task->result_set = FALSE;
1635 return task->result.pointer;
1639 * g_task_return_int:
1640 * @task: a #GTask.
1641 * @result: the integer (#gssize) result of a task function.
1643 * Sets @task's result to @result and completes the task (see
1644 * g_task_return_pointer() for more discussion of exactly what this
1645 * means).
1647 * Since: 2.36
1649 void
1650 g_task_return_int (GTask *task,
1651 gssize result)
1653 g_return_if_fail (G_IS_TASK (task));
1654 g_return_if_fail (task->result_set == FALSE);
1656 task->result.size = result;
1658 g_task_return (task, G_TASK_RETURN_SUCCESS);
1662 * g_task_propagate_int:
1663 * @task: a #GTask.
1664 * @error: return location for a #GError
1666 * Gets the result of @task as an integer (#gssize).
1668 * If the task resulted in an error, or was cancelled, then this will
1669 * instead return -1 and set @error.
1671 * Since this method transfers ownership of the return value (or
1672 * error) to the caller, you may only call it once.
1674 * Returns: the task result, or -1 on error
1676 * Since: 2.36
1678 gssize
1679 g_task_propagate_int (GTask *task,
1680 GError **error)
1682 g_return_val_if_fail (G_IS_TASK (task), -1);
1684 if (g_task_propagate_error (task, error))
1685 return -1;
1687 g_return_val_if_fail (task->result_set == TRUE, -1);
1689 task->result_set = FALSE;
1690 return task->result.size;
1694 * g_task_return_boolean:
1695 * @task: a #GTask.
1696 * @result: the #gboolean result of a task function.
1698 * Sets @task's result to @result and completes the task (see
1699 * g_task_return_pointer() for more discussion of exactly what this
1700 * means).
1702 * Since: 2.36
1704 void
1705 g_task_return_boolean (GTask *task,
1706 gboolean result)
1708 g_return_if_fail (G_IS_TASK (task));
1709 g_return_if_fail (task->result_set == FALSE);
1711 task->result.boolean = result;
1713 g_task_return (task, G_TASK_RETURN_SUCCESS);
1717 * g_task_propagate_boolean:
1718 * @task: a #GTask.
1719 * @error: return location for a #GError
1721 * Gets the result of @task as a #gboolean.
1723 * If the task resulted in an error, or was cancelled, then this will
1724 * instead return %FALSE and set @error.
1726 * Since this method transfers ownership of the return value (or
1727 * error) to the caller, you may only call it once.
1729 * Returns: the task result, or %FALSE on error
1731 * Since: 2.36
1733 gboolean
1734 g_task_propagate_boolean (GTask *task,
1735 GError **error)
1737 g_return_val_if_fail (G_IS_TASK (task), FALSE);
1739 if (g_task_propagate_error (task, error))
1740 return FALSE;
1742 g_return_val_if_fail (task->result_set == TRUE, FALSE);
1744 task->result_set = FALSE;
1745 return task->result.boolean;
1749 * g_task_return_error:
1750 * @task: a #GTask.
1751 * @error: (transfer full): the #GError result of a task function.
1753 * Sets @task's result to @error (which @task assumes ownership of)
1754 * and completes the task (see g_task_return_pointer() for more
1755 * discussion of exactly what this means).
1757 * Note that since the task takes ownership of @error, and since the
1758 * task may be completed before returning from g_task_return_error(),
1759 * you cannot assume that @error is still valid after calling this.
1760 * Call g_error_copy() on the error if you need to keep a local copy
1761 * as well.
1763 * See also g_task_return_new_error().
1765 * Since: 2.36
1767 void
1768 g_task_return_error (GTask *task,
1769 GError *error)
1771 g_return_if_fail (G_IS_TASK (task));
1772 g_return_if_fail (task->result_set == FALSE);
1773 g_return_if_fail (error != NULL);
1775 task->error = error;
1777 g_task_return (task, G_TASK_RETURN_ERROR);
1781 * g_task_return_new_error:
1782 * @task: a #GTask.
1783 * @domain: a #GQuark.
1784 * @code: an error code.
1785 * @format: a string with format characters.
1786 * @...: a list of values to insert into @format.
1788 * Sets @task's result to a new #GError created from @domain, @code,
1789 * @format, and the remaining arguments, and completes the task (see
1790 * g_task_return_pointer() for more discussion of exactly what this
1791 * means).
1793 * See also g_task_return_error().
1795 * Since: 2.36
1797 void
1798 g_task_return_new_error (GTask *task,
1799 GQuark domain,
1800 gint code,
1801 const char *format,
1802 ...)
1804 GError *error;
1805 va_list args;
1807 va_start (args, format);
1808 error = g_error_new_valist (domain, code, format, args);
1809 va_end (args);
1811 g_task_return_error (task, error);
1815 * g_task_return_error_if_cancelled:
1816 * @task: a #GTask
1818 * Checks if @task's #GCancellable has been cancelled, and if so, sets
1819 * @task's error accordingly and completes the task (see
1820 * g_task_return_pointer() for more discussion of exactly what this
1821 * means).
1823 * Returns: %TRUE if @task has been cancelled, %FALSE if not
1825 * Since: 2.36
1827 gboolean
1828 g_task_return_error_if_cancelled (GTask *task)
1830 GError *error = NULL;
1832 g_return_val_if_fail (G_IS_TASK (task), FALSE);
1833 g_return_val_if_fail (task->result_set == FALSE, FALSE);
1835 if (g_cancellable_set_error_if_cancelled (task->cancellable, &error))
1837 /* We explicitly set task->error so this works even when
1838 * check-cancellable is not set.
1840 g_clear_error (&task->error);
1841 task->error = error;
1843 g_task_return (task, G_TASK_RETURN_ERROR);
1844 return TRUE;
1846 else
1847 return FALSE;
1851 * g_task_had_error:
1852 * @task: a #GTask.
1854 * Tests if @task resulted in an error.
1856 * Returns: %TRUE if the task resulted in an error, %FALSE otherwise.
1858 * Since: 2.36
1860 gboolean
1861 g_task_had_error (GTask *task)
1863 g_return_val_if_fail (G_IS_TASK (task), FALSE);
1865 if (task->error != NULL || task->had_error)
1866 return TRUE;
1868 if (task->check_cancellable && g_cancellable_is_cancelled (task->cancellable))
1869 return TRUE;
1871 return FALSE;
1875 * g_task_get_completed:
1876 * @task: a #GTask.
1878 * Gets the value of #GTask:completed. This changes from %FALSE to %TRUE after
1879 * the task’s callback is invoked, and will return %FALSE if called from inside
1880 * the callback.
1882 * Returns: %TRUE if the task has completed, %FALSE otherwise.
1884 * Since: 2.44
1886 gboolean
1887 g_task_get_completed (GTask *task)
1889 g_return_val_if_fail (G_IS_TASK (task), FALSE);
1891 return task->completed;
1895 * g_task_is_valid:
1896 * @result: (type Gio.AsyncResult): A #GAsyncResult
1897 * @source_object: (nullable) (type GObject): the source object
1898 * expected to be associated with the task
1900 * Checks that @result is a #GTask, and that @source_object is its
1901 * source object (or that @source_object is %NULL and @result has no
1902 * source object). This can be used in g_return_if_fail() checks.
1904 * Returns: %TRUE if @result and @source_object are valid, %FALSE
1905 * if not
1907 * Since: 2.36
1909 gboolean
1910 g_task_is_valid (gpointer result,
1911 gpointer source_object)
1913 if (!G_IS_TASK (result))
1914 return FALSE;
1916 return G_TASK (result)->source_object == source_object;
1919 static gint
1920 g_task_compare_priority (gconstpointer a,
1921 gconstpointer b,
1922 gpointer user_data)
1924 const GTask *ta = a;
1925 const GTask *tb = b;
1926 gboolean a_cancelled, b_cancelled;
1928 /* Tasks that are causing other tasks to block have higher
1929 * priority.
1931 if (ta->blocking_other_task && !tb->blocking_other_task)
1932 return -1;
1933 else if (tb->blocking_other_task && !ta->blocking_other_task)
1934 return 1;
1936 /* Let already-cancelled tasks finish right away */
1937 a_cancelled = (ta->check_cancellable &&
1938 g_cancellable_is_cancelled (ta->cancellable));
1939 b_cancelled = (tb->check_cancellable &&
1940 g_cancellable_is_cancelled (tb->cancellable));
1941 if (a_cancelled && !b_cancelled)
1942 return -1;
1943 else if (b_cancelled && !a_cancelled)
1944 return 1;
1946 /* Lower priority == run sooner == negative return value */
1947 return ta->priority - tb->priority;
1950 static gboolean
1951 trivial_source_dispatch (GSource *source,
1952 GSourceFunc callback,
1953 gpointer user_data)
1955 return callback (user_data);
1958 GSourceFuncs trivial_source_funcs = {
1959 NULL, /* prepare */
1960 NULL, /* check */
1961 trivial_source_dispatch,
1962 NULL
1965 static void
1966 g_task_thread_pool_init (void)
1968 task_pool = g_thread_pool_new (g_task_thread_pool_thread, NULL,
1969 G_TASK_POOL_SIZE, FALSE, NULL);
1970 g_assert (task_pool != NULL);
1972 g_thread_pool_set_sort_function (task_pool, g_task_compare_priority, NULL);
1974 task_pool_manager = g_source_new (&trivial_source_funcs, sizeof (GSource));
1975 g_source_set_callback (task_pool_manager, task_pool_manager_timeout, NULL, NULL);
1976 g_source_set_ready_time (task_pool_manager, -1);
1977 g_source_attach (task_pool_manager,
1978 GLIB_PRIVATE_CALL (g_get_worker_context ()));
1979 g_source_unref (task_pool_manager);
1982 static void
1983 g_task_get_property (GObject *object,
1984 guint prop_id,
1985 GValue *value,
1986 GParamSpec *pspec)
1988 GTask *task = G_TASK (object);
1990 switch ((GTaskProperty) prop_id)
1992 case PROP_COMPLETED:
1993 g_value_set_boolean (value, task->completed);
1994 break;
1998 static void
1999 g_task_class_init (GTaskClass *klass)
2001 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
2003 gobject_class->get_property = g_task_get_property;
2004 gobject_class->finalize = g_task_finalize;
2007 * GTask:completed:
2009 * Whether the task has completed, meaning its callback (if set) has been
2010 * invoked. This can only happen after g_task_return_pointer(),
2011 * g_task_return_error() or one of the other return functions have been called
2012 * on the task.
2014 * This property is guaranteed to change from %FALSE to %TRUE exactly once.
2016 * The #GObject::notify signal for this change is emitted in the same main
2017 * context as the task’s callback, immediately after that callback is invoked.
2019 * Since: 2.44
2021 g_object_class_install_property (gobject_class, PROP_COMPLETED,
2022 g_param_spec_boolean ("completed",
2023 P_("Task completed"),
2024 P_("Whether the task has completed yet"),
2025 FALSE, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
2028 static gpointer
2029 g_task_get_user_data (GAsyncResult *res)
2031 return G_TASK (res)->callback_data;
2034 static gboolean
2035 g_task_is_tagged (GAsyncResult *res,
2036 gpointer source_tag)
2038 return G_TASK (res)->source_tag == source_tag;
2041 static void
2042 g_task_async_result_iface_init (GAsyncResultIface *iface)
2044 iface->get_user_data = g_task_get_user_data;
2045 iface->get_source_object = g_task_ref_source_object;
2046 iface->is_tagged = g_task_is_tagged;