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.1 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/>.
20 #include "gio_trace.h"
24 #include "gasyncresult.h"
25 #include "gcancellable.h"
26 #include "glib-private.h"
32 * @short_description: Cancellable synchronous or asynchronous task
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
51 * [thread-default main context][g-main-context-push-thread-default]
52 * where it was created (waiting until the next iteration of the main
53 * loop first, if necessary). The caller will pass the #GTask back to
54 * the operation's finish function (as a #GAsyncResult), and you can
55 * can use g_task_propagate_pointer() or the like to extract the
58 * Here is an example for using GTask as a GAsyncResult:
59 * |[<!-- language="C" -->
61 * CakeFrostingType frosting;
66 * decoration_data_free (DecorationData *decoration)
68 * g_free (decoration->message);
69 * g_slice_free (DecorationData, decoration);
73 * baked_cb (Cake *cake,
76 * GTask *task = user_data;
77 * DecorationData *decoration = g_task_get_task_data (task);
78 * GError *error = NULL;
82 * g_task_return_new_error (task, BAKER_ERROR, BAKER_ERROR_NO_FLOUR,
83 * "Go to the supermarket");
84 * g_object_unref (task);
88 * if (!cake_decorate (cake, decoration->frosting, decoration->message, &error))
90 * g_object_unref (cake);
91 * // g_task_return_error() takes ownership of error
92 * g_task_return_error (task, error);
93 * g_object_unref (task);
97 * g_task_return_pointer (task, cake, g_object_unref);
98 * g_object_unref (task);
102 * baker_bake_cake_async (Baker *self,
105 * CakeFrostingType frosting,
106 * const char *message,
107 * GCancellable *cancellable,
108 * GAsyncReadyCallback callback,
109 * gpointer user_data)
112 * DecorationData *decoration;
115 * task = g_task_new (self, cancellable, callback, user_data);
118 * g_task_return_new_error (task, BAKER_ERROR, BAKER_ERROR_TOO_SMALL,
119 * "%ucm radius cakes are silly",
121 * g_object_unref (task);
125 * cake = _baker_get_cached_cake (self, radius, flavor, frosting, message);
128 * // _baker_get_cached_cake() returns a reffed cake
129 * g_task_return_pointer (task, cake, g_object_unref);
130 * g_object_unref (task);
134 * decoration = g_slice_new (DecorationData);
135 * decoration->frosting = frosting;
136 * decoration->message = g_strdup (message);
137 * g_task_set_task_data (task, decoration, (GDestroyNotify) decoration_data_free);
139 * _baker_begin_cake (self, radius, flavor, cancellable, baked_cb, task);
143 * baker_bake_cake_finish (Baker *self,
144 * GAsyncResult *result,
147 * g_return_val_if_fail (g_task_is_valid (result, self), NULL);
149 * return g_task_propagate_pointer (G_TASK (result), error);
153 * ## Chained asynchronous operations
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(),
158 * and g_task_get_priority() allow you to get back the task's
159 * #GCancellable, #GMainContext, and [I/O priority][io-priority]
160 * when starting a new subtask, so you don't have to keep track
161 * of them yourself. g_task_attach_source() simplifies the case
162 * of waiting for a source to fire (automatically using the correct
163 * #GMainContext and priority).
165 * Here is an example for chained asynchronous operations:
166 * |[<!-- language="C" -->
169 * CakeFrostingType frosting;
174 * decoration_data_free (BakingData *bd)
177 * g_object_unref (bd->cake);
178 * g_free (bd->message);
179 * g_slice_free (BakingData, bd);
183 * decorated_cb (Cake *cake,
184 * GAsyncResult *result,
185 * gpointer user_data)
187 * GTask *task = user_data;
188 * GError *error = NULL;
190 * if (!cake_decorate_finish (cake, result, &error))
192 * g_object_unref (cake);
193 * g_task_return_error (task, error);
194 * g_object_unref (task);
198 * // baking_data_free() will drop its ref on the cake, so we have to
199 * // take another here to give to the caller.
200 * g_task_return_pointer (task, g_object_ref (cake), g_object_unref);
201 * g_object_unref (task);
205 * decorator_ready (gpointer user_data)
207 * GTask *task = user_data;
208 * BakingData *bd = g_task_get_task_data (task);
210 * cake_decorate_async (bd->cake, bd->frosting, bd->message,
211 * g_task_get_cancellable (task),
212 * decorated_cb, task);
214 * return G_SOURCE_REMOVE;
218 * baked_cb (Cake *cake,
219 * gpointer user_data)
221 * GTask *task = user_data;
222 * BakingData *bd = g_task_get_task_data (task);
223 * GError *error = NULL;
227 * g_task_return_new_error (task, BAKER_ERROR, BAKER_ERROR_NO_FLOUR,
228 * "Go to the supermarket");
229 * g_object_unref (task);
235 * // Bail out now if the user has already cancelled
236 * if (g_task_return_error_if_cancelled (task))
238 * g_object_unref (task);
242 * if (cake_decorator_available (cake))
243 * decorator_ready (task);
248 * source = cake_decorator_wait_source_new (cake);
249 * // Attach @source to @task's GMainContext and have it call
250 * // decorator_ready() when it is ready.
251 * g_task_attach_source (task, source, decorator_ready);
252 * g_source_unref (source);
257 * baker_bake_cake_async (Baker *self,
260 * CakeFrostingType frosting,
261 * const char *message,
263 * GCancellable *cancellable,
264 * GAsyncReadyCallback callback,
265 * gpointer user_data)
270 * task = g_task_new (self, cancellable, callback, user_data);
271 * g_task_set_priority (task, priority);
273 * bd = g_slice_new0 (BakingData);
274 * bd->frosting = frosting;
275 * bd->message = g_strdup (message);
276 * g_task_set_task_data (task, bd, (GDestroyNotify) baking_data_free);
278 * _baker_begin_cake (self, radius, flavor, cancellable, baked_cb, task);
282 * baker_bake_cake_finish (Baker *self,
283 * GAsyncResult *result,
286 * g_return_val_if_fail (g_task_is_valid (result, self), NULL);
288 * return g_task_propagate_pointer (G_TASK (result), error);
292 * ## Asynchronous operations from synchronous ones
294 * You can use g_task_run_in_thread() to turn a synchronous
295 * operation into an asynchronous one, by running it in a thread.
296 * When it completes, the result will be dispatched to the
297 * [thread-default main context][g-main-context-push-thread-default]
298 * where the #GTask was created.
300 * Running a task in a thread:
301 * |[<!-- language="C" -->
305 * CakeFrostingType frosting;
310 * cake_data_free (CakeData *cake_data)
312 * g_free (cake_data->message);
313 * g_slice_free (CakeData, cake_data);
317 * bake_cake_thread (GTask *task,
318 * gpointer source_object,
319 * gpointer task_data,
320 * GCancellable *cancellable)
322 * Baker *self = source_object;
323 * CakeData *cake_data = task_data;
325 * GError *error = NULL;
327 * cake = bake_cake (baker, cake_data->radius, cake_data->flavor,
328 * cake_data->frosting, cake_data->message,
329 * cancellable, &error);
331 * g_task_return_pointer (task, cake, g_object_unref);
333 * g_task_return_error (task, error);
337 * baker_bake_cake_async (Baker *self,
340 * CakeFrostingType frosting,
341 * const char *message,
342 * GCancellable *cancellable,
343 * GAsyncReadyCallback callback,
344 * gpointer user_data)
346 * CakeData *cake_data;
349 * cake_data = g_slice_new (CakeData);
350 * cake_data->radius = radius;
351 * cake_data->flavor = flavor;
352 * cake_data->frosting = frosting;
353 * cake_data->message = g_strdup (message);
354 * task = g_task_new (self, cancellable, callback, user_data);
355 * g_task_set_task_data (task, cake_data, (GDestroyNotify) cake_data_free);
356 * g_task_run_in_thread (task, bake_cake_thread);
357 * g_object_unref (task);
361 * baker_bake_cake_finish (Baker *self,
362 * GAsyncResult *result,
365 * g_return_val_if_fail (g_task_is_valid (result, self), NULL);
367 * return g_task_propagate_pointer (G_TASK (result), error);
371 * ## Adding cancellability to uncancellable tasks
373 * Finally, g_task_run_in_thread() and g_task_run_in_thread_sync()
374 * can be used to turn an uncancellable operation into a
375 * cancellable one. If you call g_task_set_return_on_cancel(),
376 * passing %TRUE, then if the task's #GCancellable is cancelled,
377 * it will return control back to the caller immediately, while
378 * allowing the task thread to continue running in the background
379 * (and simply discarding its result when it finally does finish).
380 * Provided that the task thread is careful about how it uses
381 * locks and other externally-visible resources, this allows you
382 * to make "GLib-friendly" asynchronous and cancellable
383 * synchronous variants of blocking APIs.
386 * |[<!-- language="C" -->
388 * bake_cake_thread (GTask *task,
389 * gpointer source_object,
390 * gpointer task_data,
391 * GCancellable *cancellable)
393 * Baker *self = source_object;
394 * CakeData *cake_data = task_data;
396 * GError *error = NULL;
398 * cake = bake_cake (baker, cake_data->radius, cake_data->flavor,
399 * cake_data->frosting, cake_data->message,
403 * g_task_return_error (task, error);
407 * // If the task has already been cancelled, then we don't want to add
408 * // the cake to the cake cache. Likewise, we don't want to have the
409 * // task get cancelled in the middle of updating the cache.
410 * // g_task_set_return_on_cancel() will return %TRUE here if it managed
411 * // to disable return-on-cancel, or %FALSE if the task was cancelled
412 * // before it could.
413 * if (g_task_set_return_on_cancel (task, FALSE))
415 * // If the caller cancels at this point, their
416 * // GAsyncReadyCallback won't be invoked until we return,
417 * // so we don't have to worry that this code will run at
418 * // the same time as that code does. But if there were
419 * // other functions that might look at the cake cache,
420 * // then we'd probably need a GMutex here as well.
421 * baker_add_cake_to_cache (baker, cake);
422 * g_task_return_pointer (task, cake, g_object_unref);
427 * baker_bake_cake_async (Baker *self,
430 * CakeFrostingType frosting,
431 * const char *message,
432 * GCancellable *cancellable,
433 * GAsyncReadyCallback callback,
434 * gpointer user_data)
436 * CakeData *cake_data;
439 * cake_data = g_slice_new (CakeData);
443 * task = g_task_new (self, cancellable, callback, user_data);
444 * g_task_set_task_data (task, cake_data, (GDestroyNotify) cake_data_free);
445 * g_task_set_return_on_cancel (task, TRUE);
446 * g_task_run_in_thread (task, bake_cake_thread);
450 * baker_bake_cake_sync (Baker *self,
453 * CakeFrostingType frosting,
454 * const char *message,
455 * GCancellable *cancellable,
458 * CakeData *cake_data;
462 * cake_data = g_slice_new (CakeData);
466 * task = g_task_new (self, cancellable, NULL, NULL);
467 * g_task_set_task_data (task, cake_data, (GDestroyNotify) cake_data_free);
468 * g_task_set_return_on_cancel (task, TRUE);
469 * g_task_run_in_thread_sync (task, bake_cake_thread);
471 * cake = g_task_propagate_pointer (task, error);
472 * g_object_unref (task);
477 * ## Porting from GSimpleAsyncResult
479 * #GTask's API attempts to be simpler than #GSimpleAsyncResult's
481 * - You can save task-specific data with g_task_set_task_data(), and
482 * retrieve it later with g_task_get_task_data(). This replaces the
483 * abuse of g_simple_async_result_set_op_res_gpointer() for the same
484 * purpose with #GSimpleAsyncResult.
485 * - In addition to the task data, #GTask also keeps track of the
486 * [priority][io-priority], #GCancellable, and
487 * #GMainContext associated with the task, so tasks that consist of
488 * a chain of simpler asynchronous operations will have easy access
489 * to those values when starting each sub-task.
490 * - g_task_return_error_if_cancelled() provides simplified
491 * handling for cancellation. In addition, cancellation
492 * overrides any other #GTask return value by default, like
493 * #GSimpleAsyncResult does when
494 * g_simple_async_result_set_check_cancellable() is called.
495 * (You can use g_task_set_check_cancellable() to turn off that
496 * behavior.) On the other hand, g_task_run_in_thread()
497 * guarantees that it will always run your
498 * `task_func`, even if the task's #GCancellable
499 * is already cancelled before the task gets a chance to run;
500 * you can start your `task_func` with a
501 * g_task_return_error_if_cancelled() check if you need the
503 * - The "return" methods (eg, g_task_return_pointer())
504 * automatically cause the task to be "completed" as well, and
505 * there is no need to worry about the "complete" vs "complete
506 * in idle" distinction. (#GTask automatically figures out
507 * whether the task's callback can be invoked directly, or
508 * if it needs to be sent to another #GMainContext, or delayed
509 * until the next iteration of the current #GMainContext.)
510 * - The "finish" functions for #GTask based operations are generally
511 * much simpler than #GSimpleAsyncResult ones, normally consisting
512 * of only a single call to g_task_propagate_pointer() or the like.
513 * Since g_task_propagate_pointer() "steals" the return value from
514 * the #GTask, it is not necessary to juggle pointers around to
515 * prevent it from being freed twice.
516 * - With #GSimpleAsyncResult, it was common to call
517 * g_simple_async_result_propagate_error() from the
518 * `_finish()` wrapper function, and have
519 * virtual method implementations only deal with successful
520 * returns. This behavior is deprecated, because it makes it
521 * difficult for a subclass to chain to a parent class's async
522 * methods. Instead, the wrapper function should just be a
523 * simple wrapper, and the virtual method should call an
524 * appropriate `g_task_propagate_` function.
525 * Note that wrapper methods can now use
526 * g_async_result_legacy_propagate_error() to do old-style
527 * #GSimpleAsyncResult error-returning behavior, and
528 * g_async_result_is_tagged() to check if a result is tagged as
529 * having come from the `_async()` wrapper
530 * function (for "short-circuit" results, such as when passing
531 * 0 to g_input_stream_read_async()).
537 * The opaque object representing a synchronous or asynchronous task
542 GObject parent_instance
;
544 gpointer source_object
;
548 GDestroyNotify task_data_destroy
;
550 GMainContext
*context
;
551 gint64 creation_time
;
553 GCancellable
*cancellable
;
554 gboolean check_cancellable
;
556 GAsyncReadyCallback callback
;
557 gpointer callback_data
;
560 GTaskThreadFunc task_func
;
563 gboolean return_on_cancel
;
564 gboolean thread_cancelled
;
565 gboolean synchronous
;
566 gboolean thread_complete
;
567 gboolean blocking_other_task
;
575 GDestroyNotify result_destroy
;
580 #define G_TASK_IS_THREADED(task) ((task)->task_func != NULL)
584 GObjectClass parent_class
;
592 static void g_task_async_result_iface_init (GAsyncResultIface
*iface
);
593 static void g_task_thread_pool_init (void);
595 G_DEFINE_TYPE_WITH_CODE (GTask
, g_task
, G_TYPE_OBJECT
,
596 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_RESULT
,
597 g_task_async_result_iface_init
);
598 g_task_thread_pool_init ();)
600 static GThreadPool
*task_pool
;
601 static GMutex task_pool_mutex
;
602 static GPrivate task_private
= G_PRIVATE_INIT (NULL
);
603 static GSource
*task_pool_manager
;
604 static guint64 task_wait_time
;
605 static gint tasks_running
;
607 /* When the task pool fills up and blocks, and the program keeps
608 * queueing more tasks, we will slowly add more threads to the pool
609 * (in case the existing tasks are trying to queue subtasks of their
610 * own) until tasks start completing again. These "overflow" threads
611 * will only run one task apiece, and then exit, so the pool will
612 * eventually get back down to its base size.
614 * The base and multiplier below gives us 10 extra threads after about
615 * a second of blocking, 30 after 5 seconds, 100 after a minute, and
616 * 200 after 20 minutes.
618 #define G_TASK_POOL_SIZE 10
619 #define G_TASK_WAIT_TIME_BASE 100000
620 #define G_TASK_WAIT_TIME_MULTIPLIER 1.03
621 #define G_TASK_WAIT_TIME_MAX (30 * 60 * 1000000)
624 g_task_init (GTask
*task
)
626 task
->check_cancellable
= TRUE
;
630 g_task_finalize (GObject
*object
)
632 GTask
*task
= G_TASK (object
);
634 g_clear_object (&task
->source_object
);
635 g_clear_object (&task
->cancellable
);
638 g_main_context_unref (task
->context
);
640 if (task
->task_data_destroy
)
641 task
->task_data_destroy (task
->task_data
);
643 if (task
->result_destroy
&& task
->result
.pointer
)
644 task
->result_destroy (task
->result
.pointer
);
647 g_error_free (task
->error
);
649 if (G_TASK_IS_THREADED (task
))
651 g_mutex_clear (&task
->lock
);
652 g_cond_clear (&task
->cond
);
655 G_OBJECT_CLASS (g_task_parent_class
)->finalize (object
);
660 * @source_object: (nullable) (type GObject): the #GObject that owns
661 * this task, or %NULL.
662 * @cancellable: (nullable): optional #GCancellable object, %NULL to ignore.
663 * @callback: (scope async): a #GAsyncReadyCallback.
664 * @callback_data: (closure): user data passed to @callback.
666 * Creates a #GTask acting on @source_object, which will eventually be
667 * used to invoke @callback in the current
668 * [thread-default main context][g-main-context-push-thread-default].
670 * Call this in the "start" method of your asynchronous method, and
671 * pass the #GTask around throughout the asynchronous operation. You
672 * can use g_task_set_task_data() to attach task-specific data to the
673 * object, which you can retrieve later via g_task_get_task_data().
675 * By default, if @cancellable is cancelled, then the return value of
676 * the task will always be %G_IO_ERROR_CANCELLED, even if the task had
677 * already completed before the cancellation. This allows for
678 * simplified handling in cases where cancellation may imply that
679 * other objects that the task depends on have been destroyed. If you
680 * do not want this behavior, you can use
681 * g_task_set_check_cancellable() to change it.
688 g_task_new (gpointer source_object
,
689 GCancellable
*cancellable
,
690 GAsyncReadyCallback callback
,
691 gpointer callback_data
)
696 task
= g_object_new (G_TYPE_TASK
, NULL
);
697 task
->source_object
= source_object
? g_object_ref (source_object
) : NULL
;
698 task
->cancellable
= cancellable
? g_object_ref (cancellable
) : NULL
;
699 task
->callback
= callback
;
700 task
->callback_data
= callback_data
;
701 task
->context
= g_main_context_ref_thread_default ();
703 source
= g_main_current_source ();
705 task
->creation_time
= g_source_get_time (source
);
707 TRACE (GIO_TASK_NEW (task
, source_object
, cancellable
,
708 callback
, callback_data
));
714 * g_task_report_error:
715 * @source_object: (nullable) (type GObject): the #GObject that owns
716 * this task, or %NULL.
717 * @callback: (scope async): a #GAsyncReadyCallback.
718 * @callback_data: (closure): user data passed to @callback.
719 * @source_tag: an opaque pointer indicating the source of this task
720 * @error: (transfer full): error to report
722 * Creates a #GTask and then immediately calls g_task_return_error()
723 * on it. Use this in the wrapper function of an asynchronous method
724 * when you want to avoid even calling the virtual method. You can
725 * then use g_async_result_is_tagged() in the finish method wrapper to
726 * check if the result there is tagged as having been created by the
727 * wrapper method, and deal with it appropriately if so.
729 * See also g_task_report_new_error().
734 g_task_report_error (gpointer source_object
,
735 GAsyncReadyCallback callback
,
736 gpointer callback_data
,
742 task
= g_task_new (source_object
, NULL
, callback
, callback_data
);
743 g_task_set_source_tag (task
, source_tag
);
744 g_task_return_error (task
, error
);
745 g_object_unref (task
);
749 * g_task_report_new_error:
750 * @source_object: (nullable) (type GObject): the #GObject that owns
751 * this task, or %NULL.
752 * @callback: (scope async): a #GAsyncReadyCallback.
753 * @callback_data: (closure): user data passed to @callback.
754 * @source_tag: an opaque pointer indicating the source of this task
755 * @domain: a #GQuark.
756 * @code: an error code.
757 * @format: a string with format characters.
758 * @...: a list of values to insert into @format.
760 * Creates a #GTask and then immediately calls
761 * g_task_return_new_error() on it. Use this in the wrapper function
762 * of an asynchronous method when you want to avoid even calling the
763 * virtual method. You can then use g_async_result_is_tagged() in the
764 * finish method wrapper to check if the result there is tagged as
765 * having been created by the wrapper method, and deal with it
766 * appropriately if so.
768 * See also g_task_report_error().
773 g_task_report_new_error (gpointer source_object
,
774 GAsyncReadyCallback callback
,
775 gpointer callback_data
,
785 va_start (ap
, format
);
786 error
= g_error_new_valist (domain
, code
, format
, ap
);
789 g_task_report_error (source_object
, callback
, callback_data
,
794 * g_task_set_task_data:
796 * @task_data: (nullable): task-specific data
797 * @task_data_destroy: (nullable): #GDestroyNotify for @task_data
799 * Sets @task's task data (freeing the existing task data, if any).
804 g_task_set_task_data (GTask
*task
,
806 GDestroyNotify task_data_destroy
)
808 g_return_if_fail (G_IS_TASK (task
));
810 if (task
->task_data_destroy
)
811 task
->task_data_destroy (task
->task_data
);
813 task
->task_data
= task_data
;
814 task
->task_data_destroy
= task_data_destroy
;
816 TRACE (GIO_TASK_SET_TASK_DATA (task
, task_data
, task_data_destroy
));
820 * g_task_set_priority:
822 * @priority: the [priority][io-priority] of the request
824 * Sets @task's priority. If you do not call this, it will default to
825 * %G_PRIORITY_DEFAULT.
827 * This will affect the priority of #GSources created with
828 * g_task_attach_source() and the scheduling of tasks run in threads,
829 * and can also be explicitly retrieved later via
830 * g_task_get_priority().
835 g_task_set_priority (GTask
*task
,
838 g_return_if_fail (G_IS_TASK (task
));
840 task
->priority
= priority
;
842 TRACE (GIO_TASK_SET_PRIORITY (task
, priority
));
846 * g_task_set_check_cancellable:
848 * @check_cancellable: whether #GTask will check the state of
849 * its #GCancellable for you.
851 * Sets or clears @task's check-cancellable flag. If this is %TRUE
852 * (the default), then g_task_propagate_pointer(), etc, and
853 * g_task_had_error() will check the task's #GCancellable first, and
854 * if it has been cancelled, then they will consider the task to have
855 * returned an "Operation was cancelled" error
856 * (%G_IO_ERROR_CANCELLED), regardless of any other error or return
857 * value the task may have had.
859 * If @check_cancellable is %FALSE, then the #GTask will not check the
860 * cancellable itself, and it is up to @task's owner to do this (eg,
861 * via g_task_return_error_if_cancelled()).
863 * If you are using g_task_set_return_on_cancel() as well, then
864 * you must leave check-cancellable set %TRUE.
869 g_task_set_check_cancellable (GTask
*task
,
870 gboolean check_cancellable
)
872 g_return_if_fail (G_IS_TASK (task
));
873 g_return_if_fail (check_cancellable
|| !task
->return_on_cancel
);
875 task
->check_cancellable
= check_cancellable
;
878 static void g_task_thread_complete (GTask
*task
);
881 * g_task_set_return_on_cancel:
883 * @return_on_cancel: whether the task returns automatically when
886 * Sets or clears @task's return-on-cancel flag. This is only
887 * meaningful for tasks run via g_task_run_in_thread() or
888 * g_task_run_in_thread_sync().
890 * If @return_on_cancel is %TRUE, then cancelling @task's
891 * #GCancellable will immediately cause it to return, as though the
892 * task's #GTaskThreadFunc had called
893 * g_task_return_error_if_cancelled() and then returned.
895 * This allows you to create a cancellable wrapper around an
896 * uninterruptable function. The #GTaskThreadFunc just needs to be
897 * careful that it does not modify any externally-visible state after
898 * it has been cancelled. To do that, the thread should call
899 * g_task_set_return_on_cancel() again to (atomically) set
900 * return-on-cancel %FALSE before making externally-visible changes;
901 * if the task gets cancelled before the return-on-cancel flag could
902 * be changed, g_task_set_return_on_cancel() will indicate this by
905 * You can disable and re-enable this flag multiple times if you wish.
906 * If the task's #GCancellable is cancelled while return-on-cancel is
907 * %FALSE, then calling g_task_set_return_on_cancel() to set it %TRUE
908 * again will cause the task to be cancelled at that point.
910 * If the task's #GCancellable is already cancelled before you call
911 * g_task_run_in_thread()/g_task_run_in_thread_sync(), then the
912 * #GTaskThreadFunc will still be run (for consistency), but the task
913 * will also be completed right away.
915 * Returns: %TRUE if @task's return-on-cancel flag was changed to
916 * match @return_on_cancel. %FALSE if @task has already been
922 g_task_set_return_on_cancel (GTask
*task
,
923 gboolean return_on_cancel
)
925 g_return_val_if_fail (G_IS_TASK (task
), FALSE
);
926 g_return_val_if_fail (task
->check_cancellable
|| !return_on_cancel
, FALSE
);
928 if (!G_TASK_IS_THREADED (task
))
930 task
->return_on_cancel
= return_on_cancel
;
934 g_mutex_lock (&task
->lock
);
935 if (task
->thread_cancelled
)
937 if (return_on_cancel
&& !task
->return_on_cancel
)
939 g_mutex_unlock (&task
->lock
);
940 g_task_thread_complete (task
);
943 g_mutex_unlock (&task
->lock
);
946 task
->return_on_cancel
= return_on_cancel
;
947 g_mutex_unlock (&task
->lock
);
953 * g_task_set_source_tag:
955 * @source_tag: an opaque pointer indicating the source of this task
957 * Sets @task's source tag. You can use this to tag a task return
958 * value with a particular pointer (usually a pointer to the function
959 * doing the tagging) and then later check it using
960 * g_task_get_source_tag() (or g_async_result_is_tagged()) in the
961 * task's "finish" function, to figure out if the response came from a
967 g_task_set_source_tag (GTask
*task
,
970 g_return_if_fail (G_IS_TASK (task
));
972 task
->source_tag
= source_tag
;
974 TRACE (GIO_TASK_SET_SOURCE_TAG (task
, source_tag
));
978 * g_task_get_source_object:
981 * Gets the source object from @task. Like
982 * g_async_result_get_source_object(), but does not ref the object.
984 * Returns: (transfer none) (nullable) (type GObject): @task's source object, or %NULL
989 g_task_get_source_object (GTask
*task
)
991 g_return_val_if_fail (G_IS_TASK (task
), NULL
);
993 return task
->source_object
;
997 g_task_ref_source_object (GAsyncResult
*res
)
999 GTask
*task
= G_TASK (res
);
1001 if (task
->source_object
)
1002 return g_object_ref (task
->source_object
);
1008 * g_task_get_task_data:
1011 * Gets @task's `task_data`.
1013 * Returns: (transfer none): @task's `task_data`.
1018 g_task_get_task_data (GTask
*task
)
1020 g_return_val_if_fail (G_IS_TASK (task
), NULL
);
1022 return task
->task_data
;
1026 * g_task_get_priority:
1029 * Gets @task's priority
1031 * Returns: @task's priority
1036 g_task_get_priority (GTask
*task
)
1038 g_return_val_if_fail (G_IS_TASK (task
), G_PRIORITY_DEFAULT
);
1040 return task
->priority
;
1044 * g_task_get_context:
1047 * Gets the #GMainContext that @task will return its result in (that
1048 * is, the context that was the
1049 * [thread-default main context][g-main-context-push-thread-default]
1050 * at the point when @task was created).
1052 * This will always return a non-%NULL value, even if the task's
1053 * context is the default #GMainContext.
1055 * Returns: (transfer none): @task's #GMainContext
1060 g_task_get_context (GTask
*task
)
1062 g_return_val_if_fail (G_IS_TASK (task
), NULL
);
1064 return task
->context
;
1068 * g_task_get_cancellable:
1071 * Gets @task's #GCancellable
1073 * Returns: (transfer none): @task's #GCancellable
1078 g_task_get_cancellable (GTask
*task
)
1080 g_return_val_if_fail (G_IS_TASK (task
), NULL
);
1082 return task
->cancellable
;
1086 * g_task_get_check_cancellable:
1089 * Gets @task's check-cancellable flag. See
1090 * g_task_set_check_cancellable() for more details.
1095 g_task_get_check_cancellable (GTask
*task
)
1097 g_return_val_if_fail (G_IS_TASK (task
), FALSE
);
1099 return task
->check_cancellable
;
1103 * g_task_get_return_on_cancel:
1106 * Gets @task's return-on-cancel flag. See
1107 * g_task_set_return_on_cancel() for more details.
1112 g_task_get_return_on_cancel (GTask
*task
)
1114 g_return_val_if_fail (G_IS_TASK (task
), FALSE
);
1116 return task
->return_on_cancel
;
1120 * g_task_get_source_tag:
1123 * Gets @task's source tag. See g_task_set_source_tag().
1125 * Returns: (transfer none): @task's source tag
1130 g_task_get_source_tag (GTask
*task
)
1132 g_return_val_if_fail (G_IS_TASK (task
), NULL
);
1134 return task
->source_tag
;
1139 g_task_return_now (GTask
*task
)
1141 TRACE (GIO_TASK_BEFORE_RETURN (task
, task
->source_object
, task
->callback
,
1142 task
->callback_data
));
1144 g_main_context_push_thread_default (task
->context
);
1146 if (task
->callback
!= NULL
)
1148 task
->callback (task
->source_object
,
1149 G_ASYNC_RESULT (task
),
1150 task
->callback_data
);
1153 task
->completed
= TRUE
;
1154 g_object_notify (G_OBJECT (task
), "completed");
1156 g_main_context_pop_thread_default (task
->context
);
1160 complete_in_idle_cb (gpointer task
)
1162 g_task_return_now (task
);
1163 g_object_unref (task
);
1168 G_TASK_RETURN_SUCCESS
,
1169 G_TASK_RETURN_ERROR
,
1170 G_TASK_RETURN_FROM_THREAD
1174 g_task_return (GTask
*task
,
1175 GTaskReturnType type
)
1179 if (type
== G_TASK_RETURN_SUCCESS
)
1180 task
->result_set
= TRUE
;
1182 if (task
->synchronous
)
1185 /* Normally we want to invoke the task's callback when its return
1186 * value is set. But if the task is running in a thread, then we
1187 * want to wait until after the task_func returns, to simplify
1188 * locking/refcounting/etc.
1190 if (G_TASK_IS_THREADED (task
) && type
!= G_TASK_RETURN_FROM_THREAD
)
1193 g_object_ref (task
);
1195 /* See if we can complete the task immediately. First, we have to be
1196 * running inside the task's thread/GMainContext.
1198 source
= g_main_current_source ();
1199 if (source
&& g_source_get_context (source
) == task
->context
)
1201 /* Second, we can only complete immediately if this is not the
1202 * same iteration of the main loop that the task was created in.
1204 if (g_source_get_time (source
) > task
->creation_time
)
1206 g_task_return_now (task
);
1207 g_object_unref (task
);
1212 /* Otherwise, complete in the next iteration */
1213 source
= g_idle_source_new ();
1214 g_source_set_name (source
, "[gio] complete_in_idle_cb");
1215 g_task_attach_source (task
, source
, complete_in_idle_cb
);
1216 g_source_unref (source
);
1223 * @source_object: (type GObject): @task's source object
1224 * @task_data: @task's task data
1225 * @cancellable: @task's #GCancellable, or %NULL
1227 * The prototype for a task function to be run in a thread via
1228 * g_task_run_in_thread() or g_task_run_in_thread_sync().
1230 * If the return-on-cancel flag is set on @task, and @cancellable gets
1231 * cancelled, then the #GTask will be completed immediately (as though
1232 * g_task_return_error_if_cancelled() had been called), without
1233 * waiting for the task function to complete. However, the task
1234 * function will continue running in its thread in the background. The
1235 * function therefore needs to be careful about how it uses
1236 * externally-visible state in this case. See
1237 * g_task_set_return_on_cancel() for more details.
1239 * Other than in that case, @task will be completed when the
1240 * #GTaskThreadFunc returns, not when it calls a
1241 * `g_task_return_` function.
1246 static void task_thread_cancelled (GCancellable
*cancellable
,
1247 gpointer user_data
);
1250 g_task_thread_complete (GTask
*task
)
1252 g_mutex_lock (&task
->lock
);
1253 if (task
->thread_complete
)
1255 /* The task belatedly completed after having been cancelled
1256 * (or was cancelled in the midst of being completed).
1258 g_mutex_unlock (&task
->lock
);
1262 TRACE (GIO_TASK_AFTER_RUN_IN_THREAD (task
, task
->thread_cancelled
));
1264 task
->thread_complete
= TRUE
;
1265 g_mutex_unlock (&task
->lock
);
1267 if (task
->cancellable
)
1268 g_signal_handlers_disconnect_by_func (task
->cancellable
, task_thread_cancelled
, task
);
1270 if (task
->synchronous
)
1271 g_cond_signal (&task
->cond
);
1273 g_task_return (task
, G_TASK_RETURN_FROM_THREAD
);
1277 task_pool_manager_timeout (gpointer user_data
)
1279 g_mutex_lock (&task_pool_mutex
);
1280 g_thread_pool_set_max_threads (task_pool
, tasks_running
+ 1, NULL
);
1281 g_source_set_ready_time (task_pool_manager
, -1);
1282 g_mutex_unlock (&task_pool_mutex
);
1288 g_task_thread_setup (void)
1290 g_private_set (&task_private
, GUINT_TO_POINTER (TRUE
));
1291 g_mutex_lock (&task_pool_mutex
);
1294 if (tasks_running
== G_TASK_POOL_SIZE
)
1295 task_wait_time
= G_TASK_WAIT_TIME_BASE
;
1296 else if (tasks_running
> G_TASK_POOL_SIZE
&& task_wait_time
< G_TASK_WAIT_TIME_MAX
)
1297 task_wait_time
*= G_TASK_WAIT_TIME_MULTIPLIER
;
1299 if (tasks_running
>= G_TASK_POOL_SIZE
)
1300 g_source_set_ready_time (task_pool_manager
, g_get_monotonic_time () + task_wait_time
);
1302 g_mutex_unlock (&task_pool_mutex
);
1306 g_task_thread_cleanup (void)
1310 g_mutex_lock (&task_pool_mutex
);
1311 tasks_pending
= g_thread_pool_unprocessed (task_pool
);
1313 if (tasks_running
> G_TASK_POOL_SIZE
)
1314 g_thread_pool_set_max_threads (task_pool
, tasks_running
- 1, NULL
);
1315 else if (tasks_running
+ tasks_pending
< G_TASK_POOL_SIZE
)
1316 g_source_set_ready_time (task_pool_manager
, -1);
1319 g_mutex_unlock (&task_pool_mutex
);
1320 g_private_set (&task_private
, GUINT_TO_POINTER (FALSE
));
1324 g_task_thread_pool_thread (gpointer thread_data
,
1327 GTask
*task
= thread_data
;
1329 g_task_thread_setup ();
1331 task
->task_func (task
, task
->source_object
, task
->task_data
,
1333 g_task_thread_complete (task
);
1334 g_object_unref (task
);
1336 g_task_thread_cleanup ();
1340 task_thread_cancelled (GCancellable
*cancellable
,
1343 GTask
*task
= user_data
;
1345 /* Move this task to the front of the queue - no need for
1346 * a complete resorting of the queue.
1348 g_thread_pool_move_to_front (task_pool
, task
);
1350 g_mutex_lock (&task
->lock
);
1351 task
->thread_cancelled
= TRUE
;
1353 if (!task
->return_on_cancel
)
1355 g_mutex_unlock (&task
->lock
);
1359 /* We don't actually set task->error; g_task_return_error() doesn't
1360 * use a lock, and g_task_propagate_error() will call
1361 * g_cancellable_set_error_if_cancelled() anyway.
1363 g_mutex_unlock (&task
->lock
);
1364 g_task_thread_complete (task
);
1368 task_thread_cancelled_disconnect_notify (gpointer task
,
1371 g_object_unref (task
);
1375 g_task_start_task_thread (GTask
*task
,
1376 GTaskThreadFunc task_func
)
1378 g_mutex_init (&task
->lock
);
1379 g_cond_init (&task
->cond
);
1381 g_mutex_lock (&task
->lock
);
1383 TRACE (GIO_TASK_BEFORE_RUN_IN_THREAD (task
, task_func
));
1385 task
->task_func
= task_func
;
1387 if (task
->cancellable
)
1389 if (task
->return_on_cancel
&&
1390 g_cancellable_set_error_if_cancelled (task
->cancellable
,
1393 task
->thread_cancelled
= task
->thread_complete
= TRUE
;
1394 TRACE (GIO_TASK_AFTER_RUN_IN_THREAD (task
, task
->thread_cancelled
));
1395 g_thread_pool_push (task_pool
, g_object_ref (task
), NULL
);
1399 /* This introduces a reference count loop between the GTask and
1400 * GCancellable, but is necessary to avoid a race on finalising the GTask
1401 * between task_thread_cancelled() (in one thread) and
1402 * g_task_thread_complete() (in another).
1404 * Accordingly, the signal handler *must* be removed once the task has
1407 g_signal_connect_data (task
->cancellable
, "cancelled",
1408 G_CALLBACK (task_thread_cancelled
),
1409 g_object_ref (task
),
1410 task_thread_cancelled_disconnect_notify
, 0);
1413 if (g_private_get (&task_private
))
1414 task
->blocking_other_task
= TRUE
;
1415 g_thread_pool_push (task_pool
, g_object_ref (task
), NULL
);
1419 * g_task_run_in_thread:
1421 * @task_func: a #GTaskThreadFunc
1423 * Runs @task_func in another thread. When @task_func returns, @task's
1424 * #GAsyncReadyCallback will be invoked in @task's #GMainContext.
1426 * This takes a ref on @task until the task completes.
1428 * See #GTaskThreadFunc for more details about how @task_func is handled.
1430 * Although GLib currently rate-limits the tasks queued via
1431 * g_task_run_in_thread(), you should not assume that it will always
1432 * do this. If you have a very large number of tasks to run, but don't
1433 * want them to all run at once, you should only queue a limited
1434 * number of them at a time.
1439 g_task_run_in_thread (GTask
*task
,
1440 GTaskThreadFunc task_func
)
1442 g_return_if_fail (G_IS_TASK (task
));
1444 g_object_ref (task
);
1445 g_task_start_task_thread (task
, task_func
);
1447 /* The task may already be cancelled, or g_thread_pool_push() may
1450 if (task
->thread_complete
)
1452 g_mutex_unlock (&task
->lock
);
1453 g_task_return (task
, G_TASK_RETURN_FROM_THREAD
);
1456 g_mutex_unlock (&task
->lock
);
1458 g_object_unref (task
);
1462 * g_task_run_in_thread_sync:
1464 * @task_func: a #GTaskThreadFunc
1466 * Runs @task_func in another thread, and waits for it to return or be
1467 * cancelled. You can use g_task_propagate_pointer(), etc, afterward
1468 * to get the result of @task_func.
1470 * See #GTaskThreadFunc for more details about how @task_func is handled.
1472 * Normally this is used with tasks created with a %NULL
1473 * `callback`, but note that even if the task does
1474 * have a callback, it will not be invoked when @task_func returns.
1475 * #GTask:completed will be set to %TRUE just before this function returns.
1477 * Although GLib currently rate-limits the tasks queued via
1478 * g_task_run_in_thread_sync(), you should not assume that it will
1479 * always do this. If you have a very large number of tasks to run,
1480 * but don't want them to all run at once, you should only queue a
1481 * limited number of them at a time.
1486 g_task_run_in_thread_sync (GTask
*task
,
1487 GTaskThreadFunc task_func
)
1489 g_return_if_fail (G_IS_TASK (task
));
1491 g_object_ref (task
);
1493 task
->synchronous
= TRUE
;
1494 g_task_start_task_thread (task
, task_func
);
1496 while (!task
->thread_complete
)
1497 g_cond_wait (&task
->cond
, &task
->lock
);
1499 g_mutex_unlock (&task
->lock
);
1501 TRACE (GIO_TASK_BEFORE_RETURN (task
, task
->source_object
,
1502 NULL
/* callback */,
1503 NULL
/* callback data */));
1505 /* Notify of completion in this thread. */
1506 task
->completed
= TRUE
;
1507 g_object_notify (G_OBJECT (task
), "completed");
1509 g_object_unref (task
);
1513 * g_task_attach_source:
1515 * @source: the source to attach
1516 * @callback: the callback to invoke when @source triggers
1518 * A utility function for dealing with async operations where you need
1519 * to wait for a #GSource to trigger. Attaches @source to @task's
1520 * #GMainContext with @task's [priority][io-priority], and sets @source's
1521 * callback to @callback, with @task as the callback's `user_data`.
1523 * This takes a reference on @task until @source is destroyed.
1528 g_task_attach_source (GTask
*task
,
1530 GSourceFunc callback
)
1532 g_return_if_fail (G_IS_TASK (task
));
1534 g_source_set_callback (source
, callback
,
1535 g_object_ref (task
), g_object_unref
);
1536 g_source_set_priority (source
, task
->priority
);
1537 g_source_attach (source
, task
->context
);
1542 g_task_propagate_error (GTask
*task
,
1547 if (task
->check_cancellable
&&
1548 g_cancellable_set_error_if_cancelled (task
->cancellable
, error
))
1550 else if (task
->error
)
1552 g_propagate_error (error
, task
->error
);
1554 task
->had_error
= TRUE
;
1560 TRACE (GIO_TASK_PROPAGATE (task
, error_set
));
1566 * g_task_return_pointer:
1568 * @result: (nullable) (transfer full): the pointer result of a task
1570 * @result_destroy: (nullable): a #GDestroyNotify function.
1572 * Sets @task's result to @result and completes the task. If @result
1573 * is not %NULL, then @result_destroy will be used to free @result if
1574 * the caller does not take ownership of it with
1575 * g_task_propagate_pointer().
1577 * "Completes the task" means that for an ordinary asynchronous task
1578 * it will either invoke the task's callback, or else queue that
1579 * callback to be invoked in the proper #GMainContext, or in the next
1580 * iteration of the current #GMainContext. For a task run via
1581 * g_task_run_in_thread() or g_task_run_in_thread_sync(), calling this
1582 * method will save @result to be returned to the caller later, but
1583 * the task will not actually be completed until the #GTaskThreadFunc
1586 * Note that since the task may be completed before returning from
1587 * g_task_return_pointer(), you cannot assume that @result is still
1588 * valid after calling this, unless you are still holding another
1594 g_task_return_pointer (GTask
*task
,
1596 GDestroyNotify result_destroy
)
1598 g_return_if_fail (G_IS_TASK (task
));
1599 g_return_if_fail (task
->result_set
== FALSE
);
1601 task
->result
.pointer
= result
;
1602 task
->result_destroy
= result_destroy
;
1604 g_task_return (task
, G_TASK_RETURN_SUCCESS
);
1608 * g_task_propagate_pointer:
1610 * @error: return location for a #GError
1612 * Gets the result of @task as a pointer, and transfers ownership
1613 * of that value to the caller.
1615 * If the task resulted in an error, or was cancelled, then this will
1616 * instead return %NULL and set @error.
1618 * Since this method transfers ownership of the return value (or
1619 * error) to the caller, you may only call it once.
1621 * Returns: (transfer full): the task result, or %NULL on error
1626 g_task_propagate_pointer (GTask
*task
,
1629 g_return_val_if_fail (G_IS_TASK (task
), NULL
);
1631 if (g_task_propagate_error (task
, error
))
1634 g_return_val_if_fail (task
->result_set
== TRUE
, NULL
);
1636 task
->result_destroy
= NULL
;
1637 task
->result_set
= FALSE
;
1638 return task
->result
.pointer
;
1642 * g_task_return_int:
1644 * @result: the integer (#gssize) result of a task function.
1646 * Sets @task's result to @result and completes the task (see
1647 * g_task_return_pointer() for more discussion of exactly what this
1653 g_task_return_int (GTask
*task
,
1656 g_return_if_fail (G_IS_TASK (task
));
1657 g_return_if_fail (task
->result_set
== FALSE
);
1659 task
->result
.size
= result
;
1661 g_task_return (task
, G_TASK_RETURN_SUCCESS
);
1665 * g_task_propagate_int:
1667 * @error: return location for a #GError
1669 * Gets the result of @task as an integer (#gssize).
1671 * If the task resulted in an error, or was cancelled, then this will
1672 * instead return -1 and set @error.
1674 * Since this method transfers ownership of the return value (or
1675 * error) to the caller, you may only call it once.
1677 * Returns: the task result, or -1 on error
1682 g_task_propagate_int (GTask
*task
,
1685 g_return_val_if_fail (G_IS_TASK (task
), -1);
1687 if (g_task_propagate_error (task
, error
))
1690 g_return_val_if_fail (task
->result_set
== TRUE
, -1);
1692 task
->result_set
= FALSE
;
1693 return task
->result
.size
;
1697 * g_task_return_boolean:
1699 * @result: the #gboolean result of a task function.
1701 * Sets @task's result to @result and completes the task (see
1702 * g_task_return_pointer() for more discussion of exactly what this
1708 g_task_return_boolean (GTask
*task
,
1711 g_return_if_fail (G_IS_TASK (task
));
1712 g_return_if_fail (task
->result_set
== FALSE
);
1714 task
->result
.boolean
= result
;
1716 g_task_return (task
, G_TASK_RETURN_SUCCESS
);
1720 * g_task_propagate_boolean:
1722 * @error: return location for a #GError
1724 * Gets the result of @task as a #gboolean.
1726 * If the task resulted in an error, or was cancelled, then this will
1727 * instead return %FALSE and set @error.
1729 * Since this method transfers ownership of the return value (or
1730 * error) to the caller, you may only call it once.
1732 * Returns: the task result, or %FALSE on error
1737 g_task_propagate_boolean (GTask
*task
,
1740 g_return_val_if_fail (G_IS_TASK (task
), FALSE
);
1742 if (g_task_propagate_error (task
, error
))
1745 g_return_val_if_fail (task
->result_set
== TRUE
, FALSE
);
1747 task
->result_set
= FALSE
;
1748 return task
->result
.boolean
;
1752 * g_task_return_error:
1754 * @error: (transfer full): the #GError result of a task function.
1756 * Sets @task's result to @error (which @task assumes ownership of)
1757 * and completes the task (see g_task_return_pointer() for more
1758 * discussion of exactly what this means).
1760 * Note that since the task takes ownership of @error, and since the
1761 * task may be completed before returning from g_task_return_error(),
1762 * you cannot assume that @error is still valid after calling this.
1763 * Call g_error_copy() on the error if you need to keep a local copy
1766 * See also g_task_return_new_error().
1771 g_task_return_error (GTask
*task
,
1774 g_return_if_fail (G_IS_TASK (task
));
1775 g_return_if_fail (task
->result_set
== FALSE
);
1776 g_return_if_fail (error
!= NULL
);
1778 task
->error
= error
;
1780 g_task_return (task
, G_TASK_RETURN_ERROR
);
1784 * g_task_return_new_error:
1786 * @domain: a #GQuark.
1787 * @code: an error code.
1788 * @format: a string with format characters.
1789 * @...: a list of values to insert into @format.
1791 * Sets @task's result to a new #GError created from @domain, @code,
1792 * @format, and the remaining arguments, and completes the task (see
1793 * g_task_return_pointer() for more discussion of exactly what this
1796 * See also g_task_return_error().
1801 g_task_return_new_error (GTask
*task
,
1810 va_start (args
, format
);
1811 error
= g_error_new_valist (domain
, code
, format
, args
);
1814 g_task_return_error (task
, error
);
1818 * g_task_return_error_if_cancelled:
1821 * Checks if @task's #GCancellable has been cancelled, and if so, sets
1822 * @task's error accordingly and completes the task (see
1823 * g_task_return_pointer() for more discussion of exactly what this
1826 * Returns: %TRUE if @task has been cancelled, %FALSE if not
1831 g_task_return_error_if_cancelled (GTask
*task
)
1833 GError
*error
= NULL
;
1835 g_return_val_if_fail (G_IS_TASK (task
), FALSE
);
1836 g_return_val_if_fail (task
->result_set
== FALSE
, FALSE
);
1838 if (g_cancellable_set_error_if_cancelled (task
->cancellable
, &error
))
1840 /* We explicitly set task->error so this works even when
1841 * check-cancellable is not set.
1843 g_clear_error (&task
->error
);
1844 task
->error
= error
;
1846 g_task_return (task
, G_TASK_RETURN_ERROR
);
1857 * Tests if @task resulted in an error.
1859 * Returns: %TRUE if the task resulted in an error, %FALSE otherwise.
1864 g_task_had_error (GTask
*task
)
1866 g_return_val_if_fail (G_IS_TASK (task
), FALSE
);
1868 if (task
->error
!= NULL
|| task
->had_error
)
1871 if (task
->check_cancellable
&& g_cancellable_is_cancelled (task
->cancellable
))
1878 * g_task_get_completed:
1881 * Gets the value of #GTask:completed. This changes from %FALSE to %TRUE after
1882 * the task’s callback is invoked, and will return %FALSE if called from inside
1885 * Returns: %TRUE if the task has completed, %FALSE otherwise.
1890 g_task_get_completed (GTask
*task
)
1892 g_return_val_if_fail (G_IS_TASK (task
), FALSE
);
1894 return task
->completed
;
1899 * @result: (type Gio.AsyncResult): A #GAsyncResult
1900 * @source_object: (nullable) (type GObject): the source object
1901 * expected to be associated with the task
1903 * Checks that @result is a #GTask, and that @source_object is its
1904 * source object (or that @source_object is %NULL and @result has no
1905 * source object). This can be used in g_return_if_fail() checks.
1907 * Returns: %TRUE if @result and @source_object are valid, %FALSE
1913 g_task_is_valid (gpointer result
,
1914 gpointer source_object
)
1916 if (!G_IS_TASK (result
))
1919 return G_TASK (result
)->source_object
== source_object
;
1923 g_task_compare_priority (gconstpointer a
,
1927 const GTask
*ta
= a
;
1928 const GTask
*tb
= b
;
1929 gboolean a_cancelled
, b_cancelled
;
1931 /* Tasks that are causing other tasks to block have higher
1934 if (ta
->blocking_other_task
&& !tb
->blocking_other_task
)
1936 else if (tb
->blocking_other_task
&& !ta
->blocking_other_task
)
1939 /* Let already-cancelled tasks finish right away */
1940 a_cancelled
= (ta
->check_cancellable
&&
1941 g_cancellable_is_cancelled (ta
->cancellable
));
1942 b_cancelled
= (tb
->check_cancellable
&&
1943 g_cancellable_is_cancelled (tb
->cancellable
));
1944 if (a_cancelled
&& !b_cancelled
)
1946 else if (b_cancelled
&& !a_cancelled
)
1949 /* Lower priority == run sooner == negative return value */
1950 return ta
->priority
- tb
->priority
;
1954 trivial_source_dispatch (GSource
*source
,
1955 GSourceFunc callback
,
1958 return callback (user_data
);
1961 GSourceFuncs trivial_source_funcs
= {
1964 trivial_source_dispatch
,
1969 g_task_thread_pool_init (void)
1971 task_pool
= g_thread_pool_new (g_task_thread_pool_thread
, NULL
,
1972 G_TASK_POOL_SIZE
, FALSE
, NULL
);
1973 g_assert (task_pool
!= NULL
);
1975 g_thread_pool_set_sort_function (task_pool
, g_task_compare_priority
, NULL
);
1977 task_pool_manager
= g_source_new (&trivial_source_funcs
, sizeof (GSource
));
1978 g_source_set_name (task_pool_manager
, "GTask thread pool manager");
1979 g_source_set_callback (task_pool_manager
, task_pool_manager_timeout
, NULL
, NULL
);
1980 g_source_set_ready_time (task_pool_manager
, -1);
1981 g_source_attach (task_pool_manager
,
1982 GLIB_PRIVATE_CALL (g_get_worker_context ()));
1983 g_source_unref (task_pool_manager
);
1987 g_task_get_property (GObject
*object
,
1992 GTask
*task
= G_TASK (object
);
1994 switch ((GTaskProperty
) prop_id
)
1996 case PROP_COMPLETED
:
1997 g_value_set_boolean (value
, task
->completed
);
2003 g_task_class_init (GTaskClass
*klass
)
2005 GObjectClass
*gobject_class
= G_OBJECT_CLASS (klass
);
2007 gobject_class
->get_property
= g_task_get_property
;
2008 gobject_class
->finalize
= g_task_finalize
;
2013 * Whether the task has completed, meaning its callback (if set) has been
2014 * invoked. This can only happen after g_task_return_pointer(),
2015 * g_task_return_error() or one of the other return functions have been called
2018 * This property is guaranteed to change from %FALSE to %TRUE exactly once.
2020 * The #GObject::notify signal for this change is emitted in the same main
2021 * context as the task’s callback, immediately after that callback is invoked.
2025 g_object_class_install_property (gobject_class
, PROP_COMPLETED
,
2026 g_param_spec_boolean ("completed",
2027 P_("Task completed"),
2028 P_("Whether the task has completed yet"),
2029 FALSE
, G_PARAM_READABLE
| G_PARAM_STATIC_STRINGS
));
2033 g_task_get_user_data (GAsyncResult
*res
)
2035 return G_TASK (res
)->callback_data
;
2039 g_task_is_tagged (GAsyncResult
*res
,
2040 gpointer source_tag
)
2042 return G_TASK (res
)->source_tag
== source_tag
;
2046 g_task_async_result_iface_init (GAsyncResultIface
*iface
)
2048 iface
->get_user_data
= g_task_get_user_data
;
2049 iface
->get_source_object
= g_task_ref_source_object
;
2050 iface
->is_tagged
= g_task_is_tagged
;