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/>.
23 #include "gasyncresult.h"
24 #include "gcancellable.h"
28 * @short_description: Cancellable synchronous or asynchronous task
31 * @see_also: #GAsyncResult
33 * A #GTask represents and manages a cancellable "task".
35 * ## Asynchronous operations
37 * The most common usage of #GTask is as a #GAsyncResult, to
38 * manage data during an asynchronous operation. You call
39 * g_task_new() in the "start" method, followed by
40 * g_task_set_task_data() and the like if you need to keep some
41 * additional data associated with the task, and then pass the
42 * task object around through your asynchronous operation.
43 * Eventually, you will call a method such as
44 * g_task_return_pointer() or g_task_return_error(), which will
45 * save the value you give it and then invoke the task's callback
46 * function (waiting until the next iteration of the main
47 * loop first, if necessary). The caller will pass the #GTask back
48 * to the operation's finish function (as a #GAsyncResult), and
49 * you can use g_task_propagate_pointer() or the like to extract
52 * Here is an example for using GTask as a GAsyncResult:
53 * |[<!-- language="C" -->
55 * CakeFrostingType frosting;
60 * decoration_data_free (DecorationData *decoration)
62 * g_free (decoration->message);
63 * g_slice_free (DecorationData, decoration);
67 * baked_cb (Cake *cake,
70 * GTask *task = user_data;
71 * DecorationData *decoration = g_task_get_task_data (task);
72 * GError *error = NULL;
76 * g_task_return_new_error (task, BAKER_ERROR, BAKER_ERROR_NO_FLOUR,
77 * "Go to the supermarket");
78 * g_object_unref (task);
82 * if (!cake_decorate (cake, decoration->frosting, decoration->message, &error))
84 * g_object_unref (cake);
85 * /* g_task_return_error() takes ownership of error */
86 * g_task_return_error (task, error);
87 * g_object_unref (task);
91 * g_task_return_pointer (task, cake, g_object_unref);
92 * g_object_unref (task);
96 * baker_bake_cake_async (Baker *self,
99 * CakeFrostingType frosting,
100 * const char *message,
101 * GCancellable *cancellable,
102 * GAsyncReadyCallback callback,
103 * gpointer user_data)
106 * DecorationData *decoration;
109 * task = g_task_new (self, cancellable, callback, user_data);
112 * g_task_return_new_error (task, BAKER_ERROR, BAKER_ERROR_TOO_SMALL,
113 * "%ucm radius cakes are silly",
115 * g_object_unref (task);
119 * cake = _baker_get_cached_cake (self, radius, flavor, frosting, message);
122 * /* _baker_get_cached_cake() returns a reffed cake */
123 * g_task_return_pointer (task, cake, g_object_unref);
124 * g_object_unref (task);
128 * decoration = g_slice_new (DecorationData);
129 * decoration->frosting = frosting;
130 * decoration->message = g_strdup (message);
131 * g_task_set_task_data (task, decoration, (GDestroyNotify) decoration_data_free);
133 * _baker_begin_cake (self, radius, flavor, cancellable, baked_cb, task);
137 * baker_bake_cake_finish (Baker *self,
138 * GAsyncResult *result,
141 * g_return_val_if_fail (g_task_is_valid (result, self), NULL);
143 * return g_task_propagate_pointer (G_TASK (result), error);
147 * ## Chained asynchronous operations
149 * #GTask also tries to simplify asynchronous operations that
150 * internally chain together several smaller asynchronous
151 * operations. g_task_get_cancellable(), g_task_get_context(),
152 * and g_task_get_priority() allow you to get back the task's
153 * #GCancellable, #GMainContext, and [I/O priority][io-priority]
154 * when starting a new subtask, so you don't have to keep track
155 * of them yourself. g_task_attach_source() simplifies the case
156 * of waiting for a source to fire (automatically using the correct
157 * #GMainContext and priority).
159 * Here is an example for chained asynchronous operations:
160 * |[<!-- language="C" -->
163 * CakeFrostingType frosting;
168 * decoration_data_free (BakingData *bd)
171 * g_object_unref (bd->cake);
172 * g_free (bd->message);
173 * g_slice_free (BakingData, bd);
177 * decorated_cb (Cake *cake,
178 * GAsyncResult *result,
179 * gpointer user_data)
181 * GTask *task = user_data;
182 * GError *error = NULL;
184 * if (!cake_decorate_finish (cake, result, &error))
186 * g_object_unref (cake);
187 * g_task_return_error (task, error);
188 * g_object_unref (task);
192 * /* baking_data_free() will drop its ref on the cake, so
193 * * we have to take another here to give to the caller.
195 * g_task_return_pointer (result, g_object_ref (cake), g_object_unref);
196 * g_object_unref (task);
200 * decorator_ready (gpointer user_data)
202 * GTask *task = user_data;
203 * BakingData *bd = g_task_get_task_data (task);
205 * cake_decorate_async (bd->cake, bd->frosting, bd->message,
206 * g_task_get_cancellable (task),
207 * decorated_cb, task);
211 * baked_cb (Cake *cake,
212 * gpointer user_data)
214 * GTask *task = user_data;
215 * BakingData *bd = g_task_get_task_data (task);
216 * GError *error = NULL;
220 * g_task_return_new_error (task, BAKER_ERROR, BAKER_ERROR_NO_FLOUR,
221 * "Go to the supermarket");
222 * g_object_unref (task);
228 * /* Bail out now if the user has already cancelled */
229 * if (g_task_return_error_if_cancelled (task))
231 * g_object_unref (task);
235 * if (cake_decorator_available (cake))
236 * decorator_ready (task);
241 * source = cake_decorator_wait_source_new (cake);
242 * /* Attach @source to @task's GMainContext and have it call
243 * * decorator_ready() when it is ready.
245 * g_task_attach_source (task, source,
246 * G_CALLBACK (decorator_ready));
247 * g_source_unref (source);
252 * baker_bake_cake_async (Baker *self,
255 * CakeFrostingType frosting,
256 * const char *message,
258 * GCancellable *cancellable,
259 * GAsyncReadyCallback callback,
260 * gpointer user_data)
265 * task = g_task_new (self, cancellable, callback, user_data);
266 * g_task_set_priority (task, priority);
268 * bd = g_slice_new0 (BakingData);
269 * bd->frosting = frosting;
270 * bd->message = g_strdup (message);
271 * g_task_set_task_data (task, bd, (GDestroyNotify) baking_data_free);
273 * _baker_begin_cake (self, radius, flavor, cancellable, baked_cb, task);
277 * baker_bake_cake_finish (Baker *self,
278 * GAsyncResult *result,
281 * g_return_val_if_fail (g_task_is_valid (result, self), NULL);
283 * return g_task_propagate_pointer (G_TASK (result), error);
287 * ## Asynchronous operations from synchronous ones
289 * You can use g_task_run_in_thread() to turn a synchronous
290 * operation into an asynchronous one, by running it in a thread
291 * which will then dispatch the result back to the caller's
292 * #GMainContext when it completes.
294 * Running a task in a thread:
295 * |[<!-- language="C" -->
299 * CakeFrostingType frosting;
304 * cake_data_free (CakeData *cake_data)
306 * g_free (cake_data->message);
307 * g_slice_free (CakeData, cake_data);
311 * bake_cake_thread (GTask *task,
312 * gpointer source_object,
313 * gpointer task_data,
314 * GCancellable *cancellable)
316 * Baker *self = source_object;
317 * CakeData *cake_data = task_data;
319 * GError *error = NULL;
321 * cake = bake_cake (baker, cake_data->radius, cake_data->flavor,
322 * cake_data->frosting, cake_data->message,
323 * cancellable, &error);
325 * g_task_return_pointer (task, cake, g_object_unref);
327 * g_task_return_error (task, error);
331 * baker_bake_cake_async (Baker *self,
334 * CakeFrostingType frosting,
335 * const char *message,
336 * GCancellable *cancellable,
337 * GAsyncReadyCallback callback,
338 * gpointer user_data)
340 * CakeData *cake_data;
343 * cake_data = g_slice_new (CakeData);
344 * cake_data->radius = radius;
345 * cake_data->flavor = flavor;
346 * cake_data->frosting = frosting;
347 * cake_data->message = g_strdup (message);
348 * task = g_task_new (self, cancellable, callback, user_data);
349 * g_task_set_task_data (task, cake_data, (GDestroyNotify) cake_data_free);
350 * g_task_run_in_thread (task, bake_cake_thread);
354 * baker_bake_cake_finish (Baker *self,
355 * GAsyncResult *result,
358 * g_return_val_if_fail (g_task_is_valid (result, self), NULL);
360 * return g_task_propagate_pointer (G_TASK (result), error);
364 * ## Adding cancellability to uncancellable tasks
366 * Finally, g_task_run_in_thread() and g_task_run_in_thread_sync()
367 * can be used to turn an uncancellable operation into a
368 * cancellable one. If you call g_task_set_return_on_cancel(),
369 * passing %TRUE, then if the task's #GCancellable is cancelled,
370 * it will return control back to the caller immediately, while
371 * allowing the task thread to continue running in the background
372 * (and simply discarding its result when it finally does finish).
373 * Provided that the task thread is careful about how it uses
374 * locks and other externally-visible resources, this allows you
375 * to make "GLib-friendly" asynchronous and cancellable
376 * synchronous variants of blocking APIs.
379 * |[<!-- language="C" -->
381 * bake_cake_thread (GTask *task,
382 * gpointer source_object,
383 * gpointer task_data,
384 * GCancellable *cancellable)
386 * Baker *self = source_object;
387 * CakeData *cake_data = task_data;
389 * GError *error = NULL;
391 * cake = bake_cake (baker, cake_data->radius, cake_data->flavor,
392 * cake_data->frosting, cake_data->message,
396 * g_task_return_error (task, error);
400 * /* If the task has already been cancelled, then we don't
401 * * want to add the cake to the cake cache. Likewise, we don't
402 * * want to have the task get cancelled in the middle of
403 * * updating the cache. g_task_set_return_on_cancel() will
404 * * return %TRUE here if it managed to disable return-on-cancel,
405 * * or %FALSE if the task was cancelled before it could.
407 * if (g_task_set_return_on_cancel (task, FALSE))
409 * /* If the caller cancels at this point, their
410 * * GAsyncReadyCallback won't be invoked until we return,
411 * * so we don't have to worry that this code will run at
412 * * the same time as that code does. But if there were
413 * * other functions that might look at the cake cache,
414 * * then we'd probably need a GMutex here as well.
416 * baker_add_cake_to_cache (baker, cake);
417 * g_task_return_pointer (task, cake, g_object_unref);
422 * baker_bake_cake_async (Baker *self,
425 * CakeFrostingType frosting,
426 * const char *message,
427 * GCancellable *cancellable,
428 * GAsyncReadyCallback callback,
429 * gpointer user_data)
431 * CakeData *cake_data;
434 * cake_data = g_slice_new (CakeData);
437 * task = g_task_new (self, cancellable, callback, user_data);
438 * g_task_set_task_data (task, cake_data, (GDestroyNotify) cake_data_free);
439 * g_task_set_return_on_cancel (task, TRUE);
440 * g_task_run_in_thread (task, bake_cake_thread);
444 * baker_bake_cake_sync (Baker *self,
447 * CakeFrostingType frosting,
448 * const char *message,
449 * GCancellable *cancellable,
452 * CakeData *cake_data;
456 * cake_data = g_slice_new (CakeData);
459 * task = g_task_new (self, cancellable, NULL, NULL);
460 * g_task_set_task_data (task, cake_data, (GDestroyNotify) cake_data_free);
461 * g_task_set_return_on_cancel (task, TRUE);
462 * g_task_run_in_thread_sync (task, bake_cake_thread);
464 * cake = g_task_propagate_pointer (task, error);
465 * g_object_unref (task);
470 * ## Porting from GSimpleAsyncResult
472 * #GTask's API attempts to be simpler than #GSimpleAsyncResult's
474 * - You can save task-specific data with g_task_set_task_data(), and
475 * retrieve it later with g_task_get_task_data(). This replaces the
476 * abuse of g_simple_async_result_set_op_res_gpointer() for the same
477 * purpose with #GSimpleAsyncResult.
478 * - In addition to the task data, #GTask also keeps track of the
479 * [priority][io-priority], #GCancellable, and
480 * #GMainContext associated with the task, so tasks that consist of
481 * a chain of simpler asynchronous operations will have easy access
482 * to those values when starting each sub-task.
483 * - g_task_return_error_if_cancelled() provides simplified
484 * handling for cancellation. In addition, cancellation
485 * overrides any other #GTask return value by default, like
486 * #GSimpleAsyncResult does when
487 * g_simple_async_result_set_check_cancellable() is called.
488 * (You can use g_task_set_check_cancellable() to turn off that
489 * behavior.) On the other hand, g_task_run_in_thread()
490 * guarantees that it will always run your
491 * `task_func`, even if the task's #GCancellable
492 * is already cancelled before the task gets a chance to run;
493 * you can start your `task_func` with a
494 * g_task_return_error_if_cancelled() check if you need the
496 * - The "return" methods (eg, g_task_return_pointer())
497 * automatically cause the task to be "completed" as well, and
498 * there is no need to worry about the "complete" vs "complete
499 * in idle" distinction. (#GTask automatically figures out
500 * whether the task's callback can be invoked directly, or
501 * if it needs to be sent to another #GMainContext, or delayed
502 * until the next iteration of the current #GMainContext.)
503 * - The "finish" functions for #GTask-based operations are generally
504 * much simpler than #GSimpleAsyncResult ones, normally consisting
505 * of only a single call to g_task_propagate_pointer() or the like.
506 * Since g_task_propagate_pointer() "steals" the return value from
507 * the #GTask, it is not necessary to juggle pointers around to
508 * prevent it from being freed twice.
509 * - With #GSimpleAsyncResult, it was common to call
510 * g_simple_async_result_propagate_error() from the
511 * `_finish()` wrapper function, and have
512 * virtual method implementations only deal with successful
513 * returns. This behavior is deprecated, because it makes it
514 * difficult for a subclass to chain to a parent class's async
515 * methods. Instead, the wrapper function should just be a
516 * simple wrapper, and the virtual method should call an
517 * appropriate `g_task_propagate_` function.
518 * Note that wrapper methods can now use
519 * g_async_result_legacy_propagate_error() to do old-style
520 * #GSimpleAsyncResult error-returning behavior, and
521 * g_async_result_is_tagged() to check if a result is tagged as
522 * having come from the `_async()` wrapper
523 * function (for "short-circuit" results, such as when passing
524 * 0 to g_input_stream_read_async()).
530 * The opaque object representing a synchronous or asynchronous task
535 GObject parent_instance;
537 gpointer source_object;
541 GDestroyNotify task_data_destroy;
543 GMainContext *context;
544 guint64 creation_time;
546 GCancellable *cancellable;
547 gboolean check_cancellable;
549 GAsyncReadyCallback callback;
550 gpointer callback_data;
552 GTaskThreadFunc task_func;
555 gboolean return_on_cancel;
556 gboolean thread_cancelled;
557 gboolean synchronous;
558 gboolean thread_complete;
559 gboolean blocking_other_task;
567 GDestroyNotify result_destroy;
571 #define G_TASK_IS_THREADED(task) ((task)->task_func != NULL)
575 GObjectClass parent_class;
578 static void g_task_thread_pool_resort (void);
580 static void g_task_async_result_iface_init (GAsyncResultIface *iface);
581 static void g_task_thread_pool_init (void);
583 G_DEFINE_TYPE_WITH_CODE (GTask, g_task, G_TYPE_OBJECT,
584 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_RESULT,
585 g_task_async_result_iface_init);
586 g_task_thread_pool_init ();)
588 static GThreadPool *task_pool;
589 static GMutex task_pool_mutex;
590 static GPrivate task_private = G_PRIVATE_INIT (NULL);
593 g_task_init (GTask *task)
595 task->check_cancellable = TRUE;
599 g_task_finalize (GObject *object)
601 GTask *task = G_TASK (object);
603 g_clear_object (&task->source_object);
604 g_clear_object (&task->cancellable);
607 g_main_context_unref (task->context);
609 if (task->task_data_destroy)
610 task->task_data_destroy (task->task_data);
612 if (task->result_destroy && task->result.pointer)
613 task->result_destroy (task->result.pointer);
616 g_error_free (task->error);
618 if (G_TASK_IS_THREADED (task))
620 g_mutex_clear (&task->lock);
621 g_cond_clear (&task->cond);
624 G_OBJECT_CLASS (g_task_parent_class)->finalize (object);
629 * @source_object: (allow-none) (type GObject): the #GObject that owns
630 * this task, or %NULL.
631 * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore.
632 * @callback: (scope async): a #GAsyncReadyCallback.
633 * @callback_data: (closure): user data passed to @callback.
635 * Creates a #GTask acting on @source_object, which will eventually be
636 * used to invoke @callback in the current
637 * [thread-default main context][g-main-context-push-thread-default].
639 * Call this in the "start" method of your asynchronous method, and
640 * pass the #GTask around throughout the asynchronous operation. You
641 * can use g_task_set_task_data() to attach task-specific data to the
642 * object, which you can retrieve later via g_task_get_task_data().
644 * By default, if @cancellable is cancelled, then the return value of
645 * the task will always be %G_IO_ERROR_CANCELLED, even if the task had
646 * already completed before the cancellation. This allows for
647 * simplified handling in cases where cancellation may imply that
648 * other objects that the task depends on have been destroyed. If you
649 * do not want this behavior, you can use
650 * g_task_set_check_cancellable() to change it.
657 g_task_new (gpointer source_object,
658 GCancellable *cancellable,
659 GAsyncReadyCallback callback,
660 gpointer callback_data)
665 task = g_object_new (G_TYPE_TASK, NULL);
666 task->source_object = source_object ? g_object_ref (source_object) : NULL;
667 task->cancellable = cancellable ? g_object_ref (cancellable) : NULL;
668 task->callback = callback;
669 task->callback_data = callback_data;
670 task->context = g_main_context_ref_thread_default ();
672 source = g_main_current_source ();
674 task->creation_time = g_source_get_time (source);
680 * g_task_report_error:
681 * @source_object: (allow-none) (type GObject): the #GObject that owns
682 * this task, or %NULL.
683 * @callback: (scope async): a #GAsyncReadyCallback.
684 * @callback_data: (closure): user data passed to @callback.
685 * @source_tag: an opaque pointer indicating the source of this task
686 * @error: (transfer full): error to report
688 * Creates a #GTask and then immediately calls g_task_return_error()
689 * on it. Use this in the wrapper function of an asynchronous method
690 * when you want to avoid even calling the virtual method. You can
691 * then use g_async_result_is_tagged() in the finish method wrapper to
692 * check if the result there is tagged as having been created by the
693 * wrapper method, and deal with it appropriately if so.
695 * See also g_task_report_new_error().
700 g_task_report_error (gpointer source_object,
701 GAsyncReadyCallback callback,
702 gpointer callback_data,
708 task = g_task_new (source_object, NULL, callback, callback_data);
709 g_task_set_source_tag (task, source_tag);
710 g_task_return_error (task, error);
711 g_object_unref (task);
715 * g_task_report_new_error:
716 * @source_object: (allow-none) (type GObject): the #GObject that owns
717 * this task, or %NULL.
718 * @callback: (scope async): a #GAsyncReadyCallback.
719 * @callback_data: (closure): user data passed to @callback.
720 * @source_tag: an opaque pointer indicating the source of this task
721 * @domain: a #GQuark.
722 * @code: an error code.
723 * @format: a string with format characters.
724 * @...: a list of values to insert into @format.
726 * Creates a #GTask and then immediately calls
727 * g_task_return_new_error() on it. Use this in the wrapper function
728 * of an asynchronous method when you want to avoid even calling the
729 * virtual method. You can then use g_async_result_is_tagged() in the
730 * finish method wrapper to check if the result there is tagged as
731 * having been created by the wrapper method, and deal with it
732 * appropriately if so.
734 * See also g_task_report_error().
739 g_task_report_new_error (gpointer source_object,
740 GAsyncReadyCallback callback,
741 gpointer callback_data,
751 va_start (ap, format);
752 error = g_error_new_valist (domain, code, format, ap);
755 g_task_report_error (source_object, callback, callback_data,
760 * g_task_set_task_data:
762 * @task_data: (allow-none): task-specific data
763 * @task_data_destroy: (allow-none): #GDestroyNotify for @task_data
765 * Sets @task's task data (freeing the existing task data, if any).
770 g_task_set_task_data (GTask *task,
772 GDestroyNotify task_data_destroy)
774 if (task->task_data_destroy)
775 task->task_data_destroy (task->task_data);
777 task->task_data = task_data;
778 task->task_data_destroy = task_data_destroy;
782 * g_task_set_priority:
784 * @priority: the [priority][io-priority] of the request
786 * Sets @task's priority. If you do not call this, it will default to
787 * %G_PRIORITY_DEFAULT.
789 * This will affect the priority of #GSources created with
790 * g_task_attach_source() and the scheduling of tasks run in threads,
791 * and can also be explicitly retrieved later via
792 * g_task_get_priority().
797 g_task_set_priority (GTask *task,
800 task->priority = priority;
804 * g_task_set_check_cancellable:
806 * @check_cancellable: whether #GTask will check the state of
807 * its #GCancellable for you.
809 * Sets or clears @task's check-cancellable flag. If this is %TRUE
810 * (the default), then g_task_propagate_pointer(), etc, and
811 * g_task_had_error() will check the task's #GCancellable first, and
812 * if it has been cancelled, then they will consider the task to have
813 * returned an "Operation was cancelled" error
814 * (%G_IO_ERROR_CANCELLED), regardless of any other error or return
815 * value the task may have had.
817 * If @check_cancellable is %FALSE, then the #GTask will not check the
818 * cancellable itself, and it is up to @task's owner to do this (eg,
819 * via g_task_return_error_if_cancelled()).
821 * If you are using g_task_set_return_on_cancel() as well, then
822 * you must leave check-cancellable set %TRUE.
827 g_task_set_check_cancellable (GTask *task,
828 gboolean check_cancellable)
830 g_return_if_fail (check_cancellable || !task->return_on_cancel);
832 task->check_cancellable = check_cancellable;
835 static void g_task_thread_complete (GTask *task);
838 * g_task_set_return_on_cancel:
840 * @return_on_cancel: whether the task returns automatically when
843 * Sets or clears @task's return-on-cancel flag. This is only
844 * meaningful for tasks run via g_task_run_in_thread() or
845 * g_task_run_in_thread_sync().
847 * If @return_on_cancel is %TRUE, then cancelling @task's
848 * #GCancellable will immediately cause it to return, as though the
849 * task's #GTaskThreadFunc had called
850 * g_task_return_error_if_cancelled() and then returned.
852 * This allows you to create a cancellable wrapper around an
853 * uninterruptable function. The #GTaskThreadFunc just needs to be
854 * careful that it does not modify any externally-visible state after
855 * it has been cancelled. To do that, the thread should call
856 * g_task_set_return_on_cancel() again to (atomically) set
857 * return-on-cancel %FALSE before making externally-visible changes;
858 * if the task gets cancelled before the return-on-cancel flag could
859 * be changed, g_task_set_return_on_cancel() will indicate this by
862 * You can disable and re-enable this flag multiple times if you wish.
863 * If the task's #GCancellable is cancelled while return-on-cancel is
864 * %FALSE, then calling g_task_set_return_on_cancel() to set it %TRUE
865 * again will cause the task to be cancelled at that point.
867 * If the task's #GCancellable is already cancelled before you call
868 * g_task_run_in_thread()/g_task_run_in_thread_sync(), then the
869 * #GTaskThreadFunc will still be run (for consistency), but the task
870 * will also be completed right away.
872 * Returns: %TRUE if @task's return-on-cancel flag was changed to
873 * match @return_on_cancel. %FALSE if @task has already been
879 g_task_set_return_on_cancel (GTask *task,
880 gboolean return_on_cancel)
882 g_return_val_if_fail (task->check_cancellable || !return_on_cancel, FALSE);
884 if (!G_TASK_IS_THREADED (task))
886 task->return_on_cancel = return_on_cancel;
890 g_mutex_lock (&task->lock);
891 if (task->thread_cancelled)
893 if (return_on_cancel && !task->return_on_cancel)
895 g_mutex_unlock (&task->lock);
896 g_task_thread_complete (task);
899 g_mutex_unlock (&task->lock);
902 task->return_on_cancel = return_on_cancel;
903 g_mutex_unlock (&task->lock);
909 * g_task_set_source_tag:
911 * @source_tag: an opaque pointer indicating the source of this task
913 * Sets @task's source tag. You can use this to tag a task return
914 * value with a particular pointer (usually a pointer to the function
915 * doing the tagging) and then later check it using
916 * g_task_get_source_tag() (or g_async_result_is_tagged()) in the
917 * task's "finish" function, to figure out if the response came from a
923 g_task_set_source_tag (GTask *task,
926 task->source_tag = source_tag;
930 * g_task_get_source_object:
933 * Gets the source object from @task. Like
934 * g_async_result_get_source_object(), but does not ref the object.
936 * Returns: (transfer none) (type GObject): @task's source object, or %NULL
941 g_task_get_source_object (GTask *task)
943 return task->source_object;
947 g_task_ref_source_object (GAsyncResult *res)
949 GTask *task = G_TASK (res);
951 if (task->source_object)
952 return g_object_ref (task->source_object);
958 * g_task_get_task_data:
961 * Gets @task's `task_data`.
963 * Returns: (transfer none): @task's `task_data`.
968 g_task_get_task_data (GTask *task)
970 return task->task_data;
974 * g_task_get_priority:
977 * Gets @task's priority
979 * Returns: @task's priority
984 g_task_get_priority (GTask *task)
986 return task->priority;
990 * g_task_get_context:
993 * Gets the #GMainContext that @task will return its result in (that
994 * is, the context that was the
995 * [thread-default main context][g-main-context-push-thread-default]
996 * at the point when @task was created).
998 * This will always return a non-%NULL value, even if the task's
999 * context is the default #GMainContext.
1001 * Returns: (transfer none): @task's #GMainContext
1006 g_task_get_context (GTask *task)
1008 return task->context;
1012 * g_task_get_cancellable:
1015 * Gets @task's #GCancellable
1017 * Returns: (transfer none): @task's #GCancellable
1022 g_task_get_cancellable (GTask *task)
1024 return task->cancellable;
1028 * g_task_get_check_cancellable:
1031 * Gets @task's check-cancellable flag. See
1032 * g_task_set_check_cancellable() for more details.
1037 g_task_get_check_cancellable (GTask *task)
1039 return task->check_cancellable;
1043 * g_task_get_return_on_cancel:
1046 * Gets @task's return-on-cancel flag. See
1047 * g_task_set_return_on_cancel() for more details.
1052 g_task_get_return_on_cancel (GTask *task)
1054 return task->return_on_cancel;
1058 * g_task_get_source_tag:
1061 * Gets @task's source tag. See g_task_set_source_tag().
1063 * Return value: (transfer none): @task's source tag
1068 g_task_get_source_tag (GTask *task)
1070 return task->source_tag;
1075 g_task_return_now (GTask *task)
1077 g_main_context_push_thread_default (task->context);
1078 task->callback (task->source_object,
1079 G_ASYNC_RESULT (task),
1080 task->callback_data);
1081 g_main_context_pop_thread_default (task->context);
1085 complete_in_idle_cb (gpointer task)
1087 g_task_return_now (task);
1088 g_object_unref (task);
1093 G_TASK_RETURN_SUCCESS,
1094 G_TASK_RETURN_ERROR,
1095 G_TASK_RETURN_FROM_THREAD
1099 g_task_return (GTask *task,
1100 GTaskReturnType type)
1104 if (type == G_TASK_RETURN_SUCCESS)
1105 task->result_set = TRUE;
1107 if (task->synchronous || !task->callback)
1110 /* Normally we want to invoke the task's callback when its return
1111 * value is set. But if the task is running in a thread, then we
1112 * want to wait until after the task_func returns, to simplify
1113 * locking/refcounting/etc.
1115 if (G_TASK_IS_THREADED (task) && type != G_TASK_RETURN_FROM_THREAD)
1118 g_object_ref (task);
1120 /* See if we can complete the task immediately. First, we have to be
1121 * running inside the task's thread/GMainContext.
1123 source = g_main_current_source ();
1124 if (source && g_source_get_context (source) == task->context)
1126 /* Second, we can only complete immediately if this is not the
1127 * same iteration of the main loop that the task was created in.
1129 if (g_source_get_time (source) > task->creation_time)
1131 g_task_return_now (task);
1132 g_object_unref (task);
1137 /* Otherwise, complete in the next iteration */
1138 source = g_idle_source_new ();
1139 g_task_attach_source (task, source, complete_in_idle_cb);
1140 g_source_unref (source);
1147 * @source_object: (type GObject): @task's source object
1148 * @task_data: @task's task data
1149 * @cancellable: @task's #GCancellable, or %NULL
1151 * The prototype for a task function to be run in a thread via
1152 * g_task_run_in_thread() or g_task_run_in_thread_sync().
1154 * If the return-on-cancel flag is set on @task, and @cancellable gets
1155 * cancelled, then the #GTask will be completed immediately (as though
1156 * g_task_return_error_if_cancelled() had been called), without
1157 * waiting for the task function to complete. However, the task
1158 * function will continue running in its thread in the background. The
1159 * function therefore needs to be careful about how it uses
1160 * externally-visible state in this case. See
1161 * g_task_set_return_on_cancel() for more details.
1163 * Other than in that case, @task will be completed when the
1164 * #GTaskThreadFunc returns, not when it calls a
1165 * `g_task_return_` function.
1170 static void task_thread_cancelled (GCancellable *cancellable,
1171 gpointer user_data);
1174 g_task_thread_complete (GTask *task)
1176 g_mutex_lock (&task->lock);
1177 if (task->thread_complete)
1179 /* The task belatedly completed after having been cancelled
1180 * (or was cancelled in the midst of being completed).
1182 g_mutex_unlock (&task->lock);
1186 task->thread_complete = TRUE;
1188 if (task->blocking_other_task)
1190 g_mutex_lock (&task_pool_mutex);
1191 g_thread_pool_set_max_threads (task_pool,
1192 g_thread_pool_get_max_threads (task_pool) - 1,
1194 g_mutex_unlock (&task_pool_mutex);
1196 g_mutex_unlock (&task->lock);
1198 if (task->cancellable)
1199 g_signal_handlers_disconnect_by_func (task->cancellable, task_thread_cancelled, task);
1201 if (task->synchronous)
1202 g_cond_signal (&task->cond);
1204 g_task_return (task, G_TASK_RETURN_FROM_THREAD);
1208 g_task_thread_pool_thread (gpointer thread_data,
1211 GTask *task = thread_data;
1213 g_private_set (&task_private, task);
1215 task->task_func (task, task->source_object, task->task_data,
1217 g_task_thread_complete (task);
1219 g_private_set (&task_private, NULL);
1220 g_object_unref (task);
1224 task_thread_cancelled (GCancellable *cancellable,
1227 GTask *task = user_data;
1229 g_task_thread_pool_resort ();
1231 g_mutex_lock (&task->lock);
1232 task->thread_cancelled = TRUE;
1234 if (!task->return_on_cancel)
1236 g_mutex_unlock (&task->lock);
1240 /* We don't actually set task->error; g_task_return_error() doesn't
1241 * use a lock, and g_task_propagate_error() will call
1242 * g_cancellable_set_error_if_cancelled() anyway.
1244 g_mutex_unlock (&task->lock);
1245 g_task_thread_complete (task);
1249 task_thread_cancelled_disconnect_notify (gpointer task,
1252 g_object_unref (task);
1256 g_task_start_task_thread (GTask *task,
1257 GTaskThreadFunc task_func)
1259 g_mutex_init (&task->lock);
1260 g_cond_init (&task->cond);
1262 g_mutex_lock (&task->lock);
1264 task->task_func = task_func;
1266 if (task->cancellable)
1268 if (task->return_on_cancel &&
1269 g_cancellable_set_error_if_cancelled (task->cancellable,
1272 task->thread_cancelled = task->thread_complete = TRUE;
1273 g_thread_pool_push (task_pool, g_object_ref (task), NULL);
1277 g_signal_connect_data (task->cancellable, "cancelled",
1278 G_CALLBACK (task_thread_cancelled),
1279 g_object_ref (task),
1280 task_thread_cancelled_disconnect_notify, 0);
1283 g_thread_pool_push (task_pool, g_object_ref (task), &task->error);
1285 task->thread_complete = TRUE;
1286 else if (g_private_get (&task_private))
1288 /* This thread is being spawned from another GTask thread, so
1289 * bump up max-threads so we don't starve.
1291 g_mutex_lock (&task_pool_mutex);
1292 if (g_thread_pool_set_max_threads (task_pool,
1293 g_thread_pool_get_max_threads (task_pool) + 1,
1295 task->blocking_other_task = TRUE;
1296 g_mutex_unlock (&task_pool_mutex);
1301 * g_task_run_in_thread:
1303 * @task_func: a #GTaskThreadFunc
1305 * Runs @task_func in another thread. When @task_func returns, @task's
1306 * #GAsyncReadyCallback will be invoked in @task's #GMainContext.
1308 * This takes a ref on @task until the task completes.
1310 * See #GTaskThreadFunc for more details about how @task_func is handled.
1315 g_task_run_in_thread (GTask *task,
1316 GTaskThreadFunc task_func)
1318 g_return_if_fail (G_IS_TASK (task));
1320 g_object_ref (task);
1321 g_task_start_task_thread (task, task_func);
1323 /* The task may already be cancelled, or g_thread_pool_push() may
1326 if (task->thread_complete)
1328 g_mutex_unlock (&task->lock);
1329 g_task_return (task, G_TASK_RETURN_FROM_THREAD);
1332 g_mutex_unlock (&task->lock);
1334 g_object_unref (task);
1338 * g_task_run_in_thread_sync:
1340 * @task_func: a #GTaskThreadFunc
1342 * Runs @task_func in another thread, and waits for it to return or be
1343 * cancelled. You can use g_task_propagate_pointer(), etc, afterward
1344 * to get the result of @task_func.
1346 * See #GTaskThreadFunc for more details about how @task_func is handled.
1348 * Normally this is used with tasks created with a %NULL
1349 * `callback`, but note that even if the task does
1350 * have a callback, it will not be invoked when @task_func returns.
1355 g_task_run_in_thread_sync (GTask *task,
1356 GTaskThreadFunc task_func)
1358 g_return_if_fail (G_IS_TASK (task));
1360 g_object_ref (task);
1362 task->synchronous = TRUE;
1363 g_task_start_task_thread (task, task_func);
1365 while (!task->thread_complete)
1366 g_cond_wait (&task->cond, &task->lock);
1368 g_mutex_unlock (&task->lock);
1369 g_object_unref (task);
1373 * g_task_attach_source:
1375 * @source: the source to attach
1376 * @callback: the callback to invoke when @source triggers
1378 * A utility function for dealing with async operations where you need
1379 * to wait for a #GSource to trigger. Attaches @source to @task's
1380 * #GMainContext with @task's [priority][io-priority], and sets @source's
1381 * callback to @callback, with @task as the callback's `user_data`.
1383 * This takes a reference on @task until @source is destroyed.
1388 g_task_attach_source (GTask *task,
1390 GSourceFunc callback)
1392 g_source_set_callback (source, callback,
1393 g_object_ref (task), g_object_unref);
1394 g_source_set_priority (source, task->priority);
1395 g_source_attach (source, task->context);
1400 g_task_propagate_error (GTask *task,
1403 if (task->check_cancellable &&
1404 g_cancellable_set_error_if_cancelled (task->cancellable, error))
1406 else if (task->error)
1408 g_propagate_error (error, task->error);
1417 * g_task_return_pointer:
1419 * @result: (allow-none) (transfer full): the pointer result of a task
1421 * @result_destroy: (allow-none): a #GDestroyNotify function.
1423 * Sets @task's result to @result and completes the task. If @result
1424 * is not %NULL, then @result_destroy will be used to free @result if
1425 * the caller does not take ownership of it with
1426 * g_task_propagate_pointer().
1428 * "Completes the task" means that for an ordinary asynchronous task
1429 * it will either invoke the task's callback, or else queue that
1430 * callback to be invoked in the proper #GMainContext, or in the next
1431 * iteration of the current #GMainContext. For a task run via
1432 * g_task_run_in_thread() or g_task_run_in_thread_sync(), calling this
1433 * method will save @result to be returned to the caller later, but
1434 * the task will not actually be completed until the #GTaskThreadFunc
1437 * Note that since the task may be completed before returning from
1438 * g_task_return_pointer(), you cannot assume that @result is still
1439 * valid after calling this, unless you are still holding another
1445 g_task_return_pointer (GTask *task,
1447 GDestroyNotify result_destroy)
1449 g_return_if_fail (task->result_set == FALSE);
1451 task->result.pointer = result;
1452 task->result_destroy = result_destroy;
1454 g_task_return (task, G_TASK_RETURN_SUCCESS);
1458 * g_task_propagate_pointer:
1460 * @error: return location for a #GError
1462 * Gets the result of @task as a pointer, and transfers ownership
1463 * of that value to the caller.
1465 * If the task resulted in an error, or was cancelled, then this will
1466 * instead return %NULL and set @error.
1468 * Since this method transfers ownership of the return value (or
1469 * error) to the caller, you may only call it once.
1471 * Returns: (transfer full): the task result, or %NULL on error
1476 g_task_propagate_pointer (GTask *task,
1479 if (g_task_propagate_error (task, error))
1482 g_return_val_if_fail (task->result_set == TRUE, NULL);
1484 task->result_destroy = NULL;
1485 task->result_set = FALSE;
1486 return task->result.pointer;
1490 * g_task_return_int:
1492 * @result: the integer (#gssize) result of a task function.
1494 * Sets @task's result to @result and completes the task (see
1495 * g_task_return_pointer() for more discussion of exactly what this
1501 g_task_return_int (GTask *task,
1504 g_return_if_fail (task->result_set == FALSE);
1506 task->result.size = result;
1508 g_task_return (task, G_TASK_RETURN_SUCCESS);
1512 * g_task_propagate_int:
1514 * @error: return location for a #GError
1516 * Gets the result of @task as an integer (#gssize).
1518 * If the task resulted in an error, or was cancelled, then this will
1519 * instead return -1 and set @error.
1521 * Since this method transfers ownership of the return value (or
1522 * error) to the caller, you may only call it once.
1524 * Returns: the task result, or -1 on error
1529 g_task_propagate_int (GTask *task,
1532 if (g_task_propagate_error (task, error))
1535 g_return_val_if_fail (task->result_set == TRUE, -1);
1537 task->result_set = FALSE;
1538 return task->result.size;
1542 * g_task_return_boolean:
1544 * @result: the #gboolean result of a task function.
1546 * Sets @task's result to @result and completes the task (see
1547 * g_task_return_pointer() for more discussion of exactly what this
1553 g_task_return_boolean (GTask *task,
1556 g_return_if_fail (task->result_set == FALSE);
1558 task->result.boolean = result;
1560 g_task_return (task, G_TASK_RETURN_SUCCESS);
1564 * g_task_propagate_boolean:
1566 * @error: return location for a #GError
1568 * Gets the result of @task as a #gboolean.
1570 * If the task resulted in an error, or was cancelled, then this will
1571 * instead return %FALSE and set @error.
1573 * Since this method transfers ownership of the return value (or
1574 * error) to the caller, you may only call it once.
1576 * Returns: the task result, or %FALSE on error
1581 g_task_propagate_boolean (GTask *task,
1584 if (g_task_propagate_error (task, error))
1587 g_return_val_if_fail (task->result_set == TRUE, FALSE);
1589 task->result_set = FALSE;
1590 return task->result.boolean;
1594 * g_task_return_error:
1596 * @error: (transfer full): the #GError result of a task function.
1598 * Sets @task's result to @error (which @task assumes ownership of)
1599 * and completes the task (see g_task_return_pointer() for more
1600 * discussion of exactly what this means).
1602 * Note that since the task takes ownership of @error, and since the
1603 * task may be completed before returning from g_task_return_error(),
1604 * you cannot assume that @error is still valid after calling this.
1605 * Call g_error_copy() on the error if you need to keep a local copy
1608 * See also g_task_return_new_error().
1613 g_task_return_error (GTask *task,
1616 g_return_if_fail (task->result_set == FALSE);
1617 g_return_if_fail (error != NULL);
1619 task->error = error;
1621 g_task_return (task, G_TASK_RETURN_ERROR);
1625 * g_task_return_new_error:
1627 * @domain: a #GQuark.
1628 * @code: an error code.
1629 * @format: a string with format characters.
1630 * @...: a list of values to insert into @format.
1632 * Sets @task's result to a new #GError created from @domain, @code,
1633 * @format, and the remaining arguments, and completes the task (see
1634 * g_task_return_pointer() for more discussion of exactly what this
1637 * See also g_task_return_error().
1642 g_task_return_new_error (GTask *task,
1651 va_start (args, format);
1652 error = g_error_new_valist (domain, code, format, args);
1655 g_task_return_error (task, error);
1659 * g_task_return_error_if_cancelled:
1662 * Checks if @task's #GCancellable has been cancelled, and if so, sets
1663 * @task's error accordingly and completes the task (see
1664 * g_task_return_pointer() for more discussion of exactly what this
1667 * Return value: %TRUE if @task has been cancelled, %FALSE if not
1672 g_task_return_error_if_cancelled (GTask *task)
1674 GError *error = NULL;
1676 g_return_val_if_fail (task->result_set == FALSE, FALSE);
1678 if (g_cancellable_set_error_if_cancelled (task->cancellable, &error))
1680 /* We explicitly set task->error so this works even when
1681 * check-cancellable is not set.
1683 g_clear_error (&task->error);
1684 task->error = error;
1686 g_task_return (task, G_TASK_RETURN_ERROR);
1697 * Tests if @task resulted in an error.
1699 * Returns: %TRUE if the task resulted in an error, %FALSE otherwise.
1704 g_task_had_error (GTask *task)
1706 if (task->error != NULL)
1709 if (task->check_cancellable && g_cancellable_is_cancelled (task->cancellable))
1717 * @result: (type Gio.AsyncResult): A #GAsyncResult
1718 * @source_object: (allow-none) (type GObject): the source object
1719 * expected to be associated with the task
1721 * Checks that @result is a #GTask, and that @source_object is its
1722 * source object (or that @source_object is %NULL and @result has no
1723 * source object). This can be used in g_return_if_fail() checks.
1725 * Return value: %TRUE if @result and @source_object are valid, %FALSE
1731 g_task_is_valid (gpointer result,
1732 gpointer source_object)
1734 if (!G_IS_TASK (result))
1737 return G_TASK (result)->source_object == source_object;
1741 g_task_compare_priority (gconstpointer a,
1745 const GTask *ta = a;
1746 const GTask *tb = b;
1747 gboolean a_cancelled, b_cancelled;
1749 /* Tasks that are causing other tasks to block have higher
1752 if (ta->blocking_other_task && !tb->blocking_other_task)
1754 else if (tb->blocking_other_task && !ta->blocking_other_task)
1757 /* Let already-cancelled tasks finish right away */
1758 a_cancelled = (ta->check_cancellable &&
1759 g_cancellable_is_cancelled (ta->cancellable));
1760 b_cancelled = (tb->check_cancellable &&
1761 g_cancellable_is_cancelled (tb->cancellable));
1762 if (a_cancelled && !b_cancelled)
1764 else if (b_cancelled && !a_cancelled)
1767 /* Lower priority == run sooner == negative return value */
1768 return ta->priority - tb->priority;
1772 g_task_thread_pool_init (void)
1774 task_pool = g_thread_pool_new (g_task_thread_pool_thread, NULL,
1776 g_assert (task_pool != NULL);
1778 g_thread_pool_set_sort_function (task_pool, g_task_compare_priority, NULL);
1782 g_task_thread_pool_resort (void)
1784 g_thread_pool_set_sort_function (task_pool, g_task_compare_priority, NULL);
1788 g_task_class_init (GTaskClass *klass)
1790 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
1792 gobject_class->finalize = g_task_finalize;
1796 g_task_get_user_data (GAsyncResult *res)
1798 return G_TASK (res)->callback_data;
1802 g_task_is_tagged (GAsyncResult *res,
1803 gpointer source_tag)
1805 return G_TASK (res)->source_tag == source_tag;
1809 g_task_async_result_iface_init (GAsyncResultIface *iface)
1811 iface->get_user_data = g_task_get_user_data;
1812 iface->get_source_object = g_task_ref_source_object;
1813 iface->is_tagged = g_task_is_tagged;