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/>.
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
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
56 * Here is an example for using GTask as a GAsyncResult:
57 * |[<!-- language="C" -->
59 * CakeFrostingType frosting;
64 * decoration_data_free (DecorationData *decoration)
66 * g_free (decoration->message);
67 * g_slice_free (DecorationData, decoration);
71 * baked_cb (Cake *cake,
74 * GTask *task = user_data;
75 * DecorationData *decoration = g_task_get_task_data (task);
76 * GError *error = NULL;
80 * g_task_return_new_error (task, BAKER_ERROR, BAKER_ERROR_NO_FLOUR,
81 * "Go to the supermarket");
82 * g_object_unref (task);
86 * if (!cake_decorate (cake, decoration->frosting, decoration->message, &error))
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);
95 * g_task_return_pointer (task, cake, g_object_unref);
96 * g_object_unref (task);
100 * baker_bake_cake_async (Baker *self,
103 * CakeFrostingType frosting,
104 * const char *message,
105 * GCancellable *cancellable,
106 * GAsyncReadyCallback callback,
107 * gpointer user_data)
110 * DecorationData *decoration;
113 * task = g_task_new (self, cancellable, callback, user_data);
116 * g_task_return_new_error (task, BAKER_ERROR, BAKER_ERROR_TOO_SMALL,
117 * "%ucm radius cakes are silly",
119 * g_object_unref (task);
123 * cake = _baker_get_cached_cake (self, radius, flavor, frosting, message);
126 * // _baker_get_cached_cake() returns a reffed cake
127 * g_task_return_pointer (task, cake, g_object_unref);
128 * g_object_unref (task);
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);
141 * baker_bake_cake_finish (Baker *self,
142 * GAsyncResult *result,
145 * g_return_val_if_fail (g_task_is_valid (result, self), NULL);
147 * return g_task_propagate_pointer (G_TASK (result), error);
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" -->
167 * CakeFrostingType frosting;
172 * decoration_data_free (BakingData *bd)
175 * g_object_unref (bd->cake);
176 * g_free (bd->message);
177 * g_slice_free (BakingData, bd);
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);
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);
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;
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;
225 * g_task_return_new_error (task, BAKER_ERROR, BAKER_ERROR_NO_FLOUR,
226 * "Go to the supermarket");
227 * g_object_unref (task);
233 * // Bail out now if the user has already cancelled
234 * if (g_task_return_error_if_cancelled (task))
236 * g_object_unref (task);
240 * if (cake_decorator_available (cake))
241 * decorator_ready (task);
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);
255 * baker_bake_cake_async (Baker *self,
258 * CakeFrostingType frosting,
259 * const char *message,
261 * GCancellable *cancellable,
262 * GAsyncReadyCallback callback,
263 * gpointer user_data)
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);
280 * baker_bake_cake_finish (Baker *self,
281 * GAsyncResult *result,
284 * g_return_val_if_fail (g_task_is_valid (result, self), NULL);
286 * return g_task_propagate_pointer (G_TASK (result), error);
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" -->
302 * CakeFrostingType frosting;
307 * cake_data_free (CakeData *cake_data)
309 * g_free (cake_data->message);
310 * g_slice_free (CakeData, cake_data);
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;
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);
328 * g_task_return_pointer (task, cake, g_object_unref);
330 * g_task_return_error (task, error);
334 * baker_bake_cake_async (Baker *self,
337 * CakeFrostingType frosting,
338 * const char *message,
339 * GCancellable *cancellable,
340 * GAsyncReadyCallback callback,
341 * gpointer user_data)
343 * CakeData *cake_data;
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);
358 * baker_bake_cake_finish (Baker *self,
359 * GAsyncResult *result,
362 * g_return_val_if_fail (g_task_is_valid (result, self), NULL);
364 * return g_task_propagate_pointer (G_TASK (result), error);
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.
383 * |[<!-- language="C" -->
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;
393 * GError *error = NULL;
395 * cake = bake_cake (baker, cake_data->radius, cake_data->flavor,
396 * cake_data->frosting, cake_data->message,
400 * g_task_return_error (task, error);
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);
424 * baker_bake_cake_async (Baker *self,
427 * CakeFrostingType frosting,
428 * const char *message,
429 * GCancellable *cancellable,
430 * GAsyncReadyCallback callback,
431 * gpointer user_data)
433 * CakeData *cake_data;
436 * cake_data = g_slice_new (CakeData);
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);
447 * baker_bake_cake_sync (Baker *self,
450 * CakeFrostingType frosting,
451 * const char *message,
452 * GCancellable *cancellable,
455 * CakeData *cake_data;
459 * cake_data = g_slice_new (CakeData);
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);
474 * ## Porting from GSimpleAsyncResult
476 * #GTask's API attempts to be simpler than #GSimpleAsyncResult's
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
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()).
534 * The opaque object representing a synchronous or asynchronous task
539 GObject parent_instance
;
541 gpointer source_object
;
545 GDestroyNotify task_data_destroy
;
547 GMainContext
*context
;
548 gint64 creation_time
;
550 GCancellable
*cancellable
;
551 gboolean check_cancellable
;
553 GAsyncReadyCallback callback
;
554 gpointer callback_data
;
557 GTaskThreadFunc task_func
;
560 gboolean return_on_cancel
;
561 gboolean thread_cancelled
;
562 gboolean synchronous
;
563 gboolean thread_complete
;
564 gboolean blocking_other_task
;
572 GDestroyNotify result_destroy
;
577 #define G_TASK_IS_THREADED(task) ((task)->task_func != NULL)
581 GObjectClass parent_class
;
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)
621 g_task_init (GTask
*task
)
623 task
->check_cancellable
= TRUE
;
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
);
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
);
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
);
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.
685 g_task_new (gpointer source_object
,
686 GCancellable
*cancellable
,
687 GAsyncReadyCallback callback
,
688 gpointer callback_data
)
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 ();
702 task
->creation_time
= g_source_get_time (source
);
704 TRACE (GIO_TASK_NEW (task
, source_object
, cancellable
,
705 callback
, callback_data
));
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().
731 g_task_report_error (gpointer source_object
,
732 GAsyncReadyCallback callback
,
733 gpointer callback_data
,
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().
770 g_task_report_new_error (gpointer source_object
,
771 GAsyncReadyCallback callback
,
772 gpointer callback_data
,
782 va_start (ap
, format
);
783 error
= g_error_new_valist (domain
, code
, format
, ap
);
786 g_task_report_error (source_object
, callback
, callback_data
,
791 * g_task_set_task_data:
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).
801 g_task_set_task_data (GTask
*task
,
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:
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().
832 g_task_set_priority (GTask
*task
,
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:
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.
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:
880 * @return_on_cancel: whether the task returns automatically when
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
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
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
;
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
);
940 g_mutex_unlock (&task
->lock
);
943 task
->return_on_cancel
= return_on_cancel
;
944 g_mutex_unlock (&task
->lock
);
950 * g_task_set_source_tag:
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
964 g_task_set_source_tag (GTask
*task
,
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:
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
986 g_task_get_source_object (GTask
*task
)
988 g_return_val_if_fail (G_IS_TASK (task
), NULL
);
990 return task
->source_object
;
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
);
1005 * g_task_get_task_data:
1008 * Gets @task's `task_data`.
1010 * Returns: (transfer none): @task's `task_data`.
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:
1026 * Gets @task's priority
1028 * Returns: @task's priority
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:
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
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:
1068 * Gets @task's #GCancellable
1070 * Returns: (transfer none): @task's #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:
1086 * Gets @task's check-cancellable flag. See
1087 * g_task_set_check_cancellable() for more details.
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:
1103 * Gets @task's return-on-cancel flag. See
1104 * g_task_set_return_on_cancel() for more details.
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:
1120 * Gets @task's source tag. See g_task_set_source_tag().
1122 * Returns: (transfer none): @task's source tag
1127 g_task_get_source_tag (GTask
*task
)
1129 g_return_val_if_fail (G_IS_TASK (task
), NULL
);
1131 return task
->source_tag
;
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
);
1157 complete_in_idle_cb (gpointer task
)
1159 g_task_return_now (task
);
1160 g_object_unref (task
);
1165 G_TASK_RETURN_SUCCESS
,
1166 G_TASK_RETURN_ERROR
,
1167 G_TASK_RETURN_FROM_THREAD
1171 g_task_return (GTask
*task
,
1172 GTaskReturnType type
)
1176 if (type
== G_TASK_RETURN_SUCCESS
)
1177 task
->result_set
= TRUE
;
1179 if (task
->synchronous
)
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
)
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
);
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
);
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.
1243 static void task_thread_cancelled (GCancellable
*cancellable
,
1244 gpointer user_data
);
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
);
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
);
1270 g_task_return (task
, G_TASK_RETURN_FROM_THREAD
);
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
);
1285 g_task_thread_setup (void)
1287 g_private_set (&task_private
, GUINT_TO_POINTER (TRUE
));
1288 g_mutex_lock (&task_pool_mutex
);
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
);
1303 g_task_thread_cleanup (void)
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);
1316 g_mutex_unlock (&task_pool_mutex
);
1317 g_private_set (&task_private
, GUINT_TO_POINTER (FALSE
));
1321 g_task_thread_pool_thread (gpointer thread_data
,
1324 GTask
*task
= thread_data
;
1326 g_task_thread_setup ();
1328 task
->task_func (task
, task
->source_object
, task
->task_data
,
1330 g_task_thread_complete (task
);
1331 g_object_unref (task
);
1333 g_task_thread_cleanup ();
1337 task_thread_cancelled (GCancellable
*cancellable
,
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
);
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
);
1365 task_thread_cancelled_disconnect_notify (gpointer task
,
1368 g_object_unref (task
);
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
,
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
);
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
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:
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.
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
1447 if (task
->thread_complete
)
1449 g_mutex_unlock (&task
->lock
);
1450 g_task_return (task
, G_TASK_RETURN_FROM_THREAD
);
1453 g_mutex_unlock (&task
->lock
);
1455 g_object_unref (task
);
1459 * g_task_run_in_thread_sync:
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.
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:
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.
1525 g_task_attach_source (GTask
*task
,
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
);
1539 g_task_propagate_error (GTask
*task
,
1544 if (task
->check_cancellable
&&
1545 g_cancellable_set_error_if_cancelled (task
->cancellable
, error
))
1547 else if (task
->error
)
1549 g_propagate_error (error
, task
->error
);
1551 task
->had_error
= TRUE
;
1557 TRACE (GIO_TASK_PROPAGATE (task
, error_set
));
1563 * g_task_return_pointer:
1565 * @result: (nullable) (transfer full): the pointer result of a task
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
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
1591 g_task_return_pointer (GTask
*task
,
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:
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
1623 g_task_propagate_pointer (GTask
*task
,
1626 g_return_val_if_fail (G_IS_TASK (task
), NULL
);
1628 if (g_task_propagate_error (task
, error
))
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:
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
1650 g_task_return_int (GTask
*task
,
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:
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
1679 g_task_propagate_int (GTask
*task
,
1682 g_return_val_if_fail (G_IS_TASK (task
), -1);
1684 if (g_task_propagate_error (task
, error
))
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:
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
1705 g_task_return_boolean (GTask
*task
,
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:
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
1734 g_task_propagate_boolean (GTask
*task
,
1737 g_return_val_if_fail (G_IS_TASK (task
), FALSE
);
1739 if (g_task_propagate_error (task
, error
))
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:
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
1763 * See also g_task_return_new_error().
1768 g_task_return_error (GTask
*task
,
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:
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
1793 * See also g_task_return_error().
1798 g_task_return_new_error (GTask
*task
,
1807 va_start (args
, format
);
1808 error
= g_error_new_valist (domain
, code
, format
, args
);
1811 g_task_return_error (task
, error
);
1815 * g_task_return_error_if_cancelled:
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
1823 * Returns: %TRUE if @task has been cancelled, %FALSE if not
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
);
1854 * Tests if @task resulted in an error.
1856 * Returns: %TRUE if the task resulted in an error, %FALSE otherwise.
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
)
1868 if (task
->check_cancellable
&& g_cancellable_is_cancelled (task
->cancellable
))
1875 * g_task_get_completed:
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
1882 * Returns: %TRUE if the task has completed, %FALSE otherwise.
1887 g_task_get_completed (GTask
*task
)
1889 g_return_val_if_fail (G_IS_TASK (task
), FALSE
);
1891 return task
->completed
;
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
1910 g_task_is_valid (gpointer result
,
1911 gpointer source_object
)
1913 if (!G_IS_TASK (result
))
1916 return G_TASK (result
)->source_object
== source_object
;
1920 g_task_compare_priority (gconstpointer a
,
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
1931 if (ta
->blocking_other_task
&& !tb
->blocking_other_task
)
1933 else if (tb
->blocking_other_task
&& !ta
->blocking_other_task
)
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
)
1943 else if (b_cancelled
&& !a_cancelled
)
1946 /* Lower priority == run sooner == negative return value */
1947 return ta
->priority
- tb
->priority
;
1951 trivial_source_dispatch (GSource
*source
,
1952 GSourceFunc callback
,
1955 return callback (user_data
);
1958 GSourceFuncs trivial_source_funcs
= {
1961 trivial_source_dispatch
,
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
);
1983 g_task_get_property (GObject
*object
,
1988 GTask
*task
= G_TASK (object
);
1990 switch ((GTaskProperty
) prop_id
)
1992 case PROP_COMPLETED
:
1993 g_value_set_boolean (value
, task
->completed
);
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
;
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
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.
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
));
2029 g_task_get_user_data (GAsyncResult
*res
)
2031 return G_TASK (res
)->callback_data
;
2035 g_task_is_tagged (GAsyncResult
*res
,
2036 gpointer source_tag
)
2038 return G_TASK (res
)->source_tag
== source_tag
;
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
;