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 we have to
193 * // take another here to give to the caller.
194 * g_task_return_pointer (result, g_object_ref (cake), g_object_unref);
195 * g_object_unref (task);
199 * decorator_ready (gpointer user_data)
201 * GTask *task = user_data;
202 * BakingData *bd = g_task_get_task_data (task);
204 * cake_decorate_async (bd->cake, bd->frosting, bd->message,
205 * g_task_get_cancellable (task),
206 * decorated_cb, task);
210 * baked_cb (Cake *cake,
211 * gpointer user_data)
213 * GTask *task = user_data;
214 * BakingData *bd = g_task_get_task_data (task);
215 * GError *error = NULL;
219 * g_task_return_new_error (task, BAKER_ERROR, BAKER_ERROR_NO_FLOUR,
220 * "Go to the supermarket");
221 * g_object_unref (task);
227 * // Bail out now if the user has already cancelled
228 * if (g_task_return_error_if_cancelled (task))
230 * g_object_unref (task);
234 * if (cake_decorator_available (cake))
235 * decorator_ready (task);
240 * source = cake_decorator_wait_source_new (cake);
241 * // Attach @source to @task's GMainContext and have it call
242 * // decorator_ready() when it is ready.
243 * g_task_attach_source (task, source,
244 * G_CALLBACK (decorator_ready));
245 * g_source_unref (source);
250 * baker_bake_cake_async (Baker *self,
253 * CakeFrostingType frosting,
254 * const char *message,
256 * GCancellable *cancellable,
257 * GAsyncReadyCallback callback,
258 * gpointer user_data)
263 * task = g_task_new (self, cancellable, callback, user_data);
264 * g_task_set_priority (task, priority);
266 * bd = g_slice_new0 (BakingData);
267 * bd->frosting = frosting;
268 * bd->message = g_strdup (message);
269 * g_task_set_task_data (task, bd, (GDestroyNotify) baking_data_free);
271 * _baker_begin_cake (self, radius, flavor, cancellable, baked_cb, task);
275 * baker_bake_cake_finish (Baker *self,
276 * GAsyncResult *result,
279 * g_return_val_if_fail (g_task_is_valid (result, self), NULL);
281 * return g_task_propagate_pointer (G_TASK (result), error);
285 * ## Asynchronous operations from synchronous ones
287 * You can use g_task_run_in_thread() to turn a synchronous
288 * operation into an asynchronous one, by running it in a thread
289 * which will then dispatch the result back to the caller's
290 * #GMainContext when it completes.
292 * Running a task in a thread:
293 * |[<!-- language="C" -->
297 * CakeFrostingType frosting;
302 * cake_data_free (CakeData *cake_data)
304 * g_free (cake_data->message);
305 * g_slice_free (CakeData, cake_data);
309 * bake_cake_thread (GTask *task,
310 * gpointer source_object,
311 * gpointer task_data,
312 * GCancellable *cancellable)
314 * Baker *self = source_object;
315 * CakeData *cake_data = task_data;
317 * GError *error = NULL;
319 * cake = bake_cake (baker, cake_data->radius, cake_data->flavor,
320 * cake_data->frosting, cake_data->message,
321 * cancellable, &error);
323 * g_task_return_pointer (task, cake, g_object_unref);
325 * g_task_return_error (task, error);
329 * baker_bake_cake_async (Baker *self,
332 * CakeFrostingType frosting,
333 * const char *message,
334 * GCancellable *cancellable,
335 * GAsyncReadyCallback callback,
336 * gpointer user_data)
338 * CakeData *cake_data;
341 * cake_data = g_slice_new (CakeData);
342 * cake_data->radius = radius;
343 * cake_data->flavor = flavor;
344 * cake_data->frosting = frosting;
345 * cake_data->message = g_strdup (message);
346 * task = g_task_new (self, cancellable, callback, user_data);
347 * g_task_set_task_data (task, cake_data, (GDestroyNotify) cake_data_free);
348 * g_task_run_in_thread (task, bake_cake_thread);
349 * g_object_unref (task);
353 * baker_bake_cake_finish (Baker *self,
354 * GAsyncResult *result,
357 * g_return_val_if_fail (g_task_is_valid (result, self), NULL);
359 * return g_task_propagate_pointer (G_TASK (result), error);
363 * ## Adding cancellability to uncancellable tasks
365 * Finally, g_task_run_in_thread() and g_task_run_in_thread_sync()
366 * can be used to turn an uncancellable operation into a
367 * cancellable one. If you call g_task_set_return_on_cancel(),
368 * passing %TRUE, then if the task's #GCancellable is cancelled,
369 * it will return control back to the caller immediately, while
370 * allowing the task thread to continue running in the background
371 * (and simply discarding its result when it finally does finish).
372 * Provided that the task thread is careful about how it uses
373 * locks and other externally-visible resources, this allows you
374 * to make "GLib-friendly" asynchronous and cancellable
375 * synchronous variants of blocking APIs.
378 * |[<!-- language="C" -->
380 * bake_cake_thread (GTask *task,
381 * gpointer source_object,
382 * gpointer task_data,
383 * GCancellable *cancellable)
385 * Baker *self = source_object;
386 * CakeData *cake_data = task_data;
388 * GError *error = NULL;
390 * cake = bake_cake (baker, cake_data->radius, cake_data->flavor,
391 * cake_data->frosting, cake_data->message,
395 * g_task_return_error (task, error);
399 * // If the task has already been cancelled, then we don't want to add
400 * // the cake to the cake cache. Likewise, we don't want to have the
401 * // task get cancelled in the middle of updating the cache.
402 * // g_task_set_return_on_cancel() will return %TRUE here if it managed
403 * // to disable return-on-cancel, or %FALSE if the task was cancelled
404 * // before it could.
405 * if (g_task_set_return_on_cancel (task, FALSE))
407 * // If the caller cancels at this point, their
408 * // GAsyncReadyCallback won't be invoked until we return,
409 * // so we don't have to worry that this code will run at
410 * // the same time as that code does. But if there were
411 * // other functions that might look at the cake cache,
412 * // then we'd probably need a GMutex here as well.
413 * baker_add_cake_to_cache (baker, cake);
414 * g_task_return_pointer (task, cake, g_object_unref);
419 * baker_bake_cake_async (Baker *self,
422 * CakeFrostingType frosting,
423 * const char *message,
424 * GCancellable *cancellable,
425 * GAsyncReadyCallback callback,
426 * gpointer user_data)
428 * CakeData *cake_data;
431 * cake_data = g_slice_new (CakeData);
435 * task = g_task_new (self, cancellable, callback, user_data);
436 * g_task_set_task_data (task, cake_data, (GDestroyNotify) cake_data_free);
437 * g_task_set_return_on_cancel (task, TRUE);
438 * g_task_run_in_thread (task, bake_cake_thread);
442 * baker_bake_cake_sync (Baker *self,
445 * CakeFrostingType frosting,
446 * const char *message,
447 * GCancellable *cancellable,
450 * CakeData *cake_data;
454 * cake_data = g_slice_new (CakeData);
458 * task = g_task_new (self, cancellable, NULL, NULL);
459 * g_task_set_task_data (task, cake_data, (GDestroyNotify) cake_data_free);
460 * g_task_set_return_on_cancel (task, TRUE);
461 * g_task_run_in_thread_sync (task, bake_cake_thread);
463 * cake = g_task_propagate_pointer (task, error);
464 * g_object_unref (task);
469 * ## Porting from GSimpleAsyncResult
471 * #GTask's API attempts to be simpler than #GSimpleAsyncResult's
473 * - You can save task-specific data with g_task_set_task_data(), and
474 * retrieve it later with g_task_get_task_data(). This replaces the
475 * abuse of g_simple_async_result_set_op_res_gpointer() for the same
476 * purpose with #GSimpleAsyncResult.
477 * - In addition to the task data, #GTask also keeps track of the
478 * [priority][io-priority], #GCancellable, and
479 * #GMainContext associated with the task, so tasks that consist of
480 * a chain of simpler asynchronous operations will have easy access
481 * to those values when starting each sub-task.
482 * - g_task_return_error_if_cancelled() provides simplified
483 * handling for cancellation. In addition, cancellation
484 * overrides any other #GTask return value by default, like
485 * #GSimpleAsyncResult does when
486 * g_simple_async_result_set_check_cancellable() is called.
487 * (You can use g_task_set_check_cancellable() to turn off that
488 * behavior.) On the other hand, g_task_run_in_thread()
489 * guarantees that it will always run your
490 * `task_func`, even if the task's #GCancellable
491 * is already cancelled before the task gets a chance to run;
492 * you can start your `task_func` with a
493 * g_task_return_error_if_cancelled() check if you need the
495 * - The "return" methods (eg, g_task_return_pointer())
496 * automatically cause the task to be "completed" as well, and
497 * there is no need to worry about the "complete" vs "complete
498 * in idle" distinction. (#GTask automatically figures out
499 * whether the task's callback can be invoked directly, or
500 * if it needs to be sent to another #GMainContext, or delayed
501 * until the next iteration of the current #GMainContext.)
502 * - The "finish" functions for #GTask-based operations are generally
503 * much simpler than #GSimpleAsyncResult ones, normally consisting
504 * of only a single call to g_task_propagate_pointer() or the like.
505 * Since g_task_propagate_pointer() "steals" the return value from
506 * the #GTask, it is not necessary to juggle pointers around to
507 * prevent it from being freed twice.
508 * - With #GSimpleAsyncResult, it was common to call
509 * g_simple_async_result_propagate_error() from the
510 * `_finish()` wrapper function, and have
511 * virtual method implementations only deal with successful
512 * returns. This behavior is deprecated, because it makes it
513 * difficult for a subclass to chain to a parent class's async
514 * methods. Instead, the wrapper function should just be a
515 * simple wrapper, and the virtual method should call an
516 * appropriate `g_task_propagate_` function.
517 * Note that wrapper methods can now use
518 * g_async_result_legacy_propagate_error() to do old-style
519 * #GSimpleAsyncResult error-returning behavior, and
520 * g_async_result_is_tagged() to check if a result is tagged as
521 * having come from the `_async()` wrapper
522 * function (for "short-circuit" results, such as when passing
523 * 0 to g_input_stream_read_async()).
529 * The opaque object representing a synchronous or asynchronous task
534 GObject parent_instance;
536 gpointer source_object;
540 GDestroyNotify task_data_destroy;
542 GMainContext *context;
543 gint64 creation_time;
545 GCancellable *cancellable;
546 gboolean check_cancellable;
548 GAsyncReadyCallback callback;
549 gpointer callback_data;
551 GTaskThreadFunc task_func;
554 gboolean return_on_cancel;
555 gboolean thread_cancelled;
556 gboolean synchronous;
557 gboolean thread_complete;
558 gboolean blocking_other_task;
566 GDestroyNotify result_destroy;
570 #define G_TASK_IS_THREADED(task) ((task)->task_func != NULL)
574 GObjectClass parent_class;
577 static void g_task_thread_pool_resort (void);
579 static void g_task_async_result_iface_init (GAsyncResultIface *iface);
580 static void g_task_thread_pool_init (void);
582 G_DEFINE_TYPE_WITH_CODE (GTask, g_task, G_TYPE_OBJECT,
583 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_RESULT,
584 g_task_async_result_iface_init);
585 g_task_thread_pool_init ();)
587 static GThreadPool *task_pool;
588 static GMutex task_pool_mutex;
589 static GPrivate task_private = G_PRIVATE_INIT (NULL);
592 g_task_init (GTask *task)
594 task->check_cancellable = TRUE;
598 g_task_finalize (GObject *object)
600 GTask *task = G_TASK (object);
602 g_clear_object (&task->source_object);
603 g_clear_object (&task->cancellable);
606 g_main_context_unref (task->context);
608 if (task->task_data_destroy)
609 task->task_data_destroy (task->task_data);
611 if (task->result_destroy && task->result.pointer)
612 task->result_destroy (task->result.pointer);
615 g_error_free (task->error);
617 if (G_TASK_IS_THREADED (task))
619 g_mutex_clear (&task->lock);
620 g_cond_clear (&task->cond);
623 G_OBJECT_CLASS (g_task_parent_class)->finalize (object);
628 * @source_object: (allow-none) (type GObject): the #GObject that owns
629 * this task, or %NULL.
630 * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore.
631 * @callback: (scope async): a #GAsyncReadyCallback.
632 * @callback_data: (closure): user data passed to @callback.
634 * Creates a #GTask acting on @source_object, which will eventually be
635 * used to invoke @callback in the current
636 * [thread-default main context][g-main-context-push-thread-default].
638 * Call this in the "start" method of your asynchronous method, and
639 * pass the #GTask around throughout the asynchronous operation. You
640 * can use g_task_set_task_data() to attach task-specific data to the
641 * object, which you can retrieve later via g_task_get_task_data().
643 * By default, if @cancellable is cancelled, then the return value of
644 * the task will always be %G_IO_ERROR_CANCELLED, even if the task had
645 * already completed before the cancellation. This allows for
646 * simplified handling in cases where cancellation may imply that
647 * other objects that the task depends on have been destroyed. If you
648 * do not want this behavior, you can use
649 * g_task_set_check_cancellable() to change it.
656 g_task_new (gpointer source_object,
657 GCancellable *cancellable,
658 GAsyncReadyCallback callback,
659 gpointer callback_data)
664 task = g_object_new (G_TYPE_TASK, NULL);
665 task->source_object = source_object ? g_object_ref (source_object) : NULL;
666 task->cancellable = cancellable ? g_object_ref (cancellable) : NULL;
667 task->callback = callback;
668 task->callback_data = callback_data;
669 task->context = g_main_context_ref_thread_default ();
671 source = g_main_current_source ();
673 task->creation_time = g_source_get_time (source);
679 * g_task_report_error:
680 * @source_object: (allow-none) (type GObject): the #GObject that owns
681 * this task, or %NULL.
682 * @callback: (scope async): a #GAsyncReadyCallback.
683 * @callback_data: (closure): user data passed to @callback.
684 * @source_tag: an opaque pointer indicating the source of this task
685 * @error: (transfer full): error to report
687 * Creates a #GTask and then immediately calls g_task_return_error()
688 * on it. Use this in the wrapper function of an asynchronous method
689 * when you want to avoid even calling the virtual method. You can
690 * then use g_async_result_is_tagged() in the finish method wrapper to
691 * check if the result there is tagged as having been created by the
692 * wrapper method, and deal with it appropriately if so.
694 * See also g_task_report_new_error().
699 g_task_report_error (gpointer source_object,
700 GAsyncReadyCallback callback,
701 gpointer callback_data,
707 task = g_task_new (source_object, NULL, callback, callback_data);
708 g_task_set_source_tag (task, source_tag);
709 g_task_return_error (task, error);
710 g_object_unref (task);
714 * g_task_report_new_error:
715 * @source_object: (allow-none) (type GObject): the #GObject that owns
716 * this task, or %NULL.
717 * @callback: (scope async): a #GAsyncReadyCallback.
718 * @callback_data: (closure): user data passed to @callback.
719 * @source_tag: an opaque pointer indicating the source of this task
720 * @domain: a #GQuark.
721 * @code: an error code.
722 * @format: a string with format characters.
723 * @...: a list of values to insert into @format.
725 * Creates a #GTask and then immediately calls
726 * g_task_return_new_error() on it. Use this in the wrapper function
727 * of an asynchronous method when you want to avoid even calling the
728 * virtual method. You can then use g_async_result_is_tagged() in the
729 * finish method wrapper to check if the result there is tagged as
730 * having been created by the wrapper method, and deal with it
731 * appropriately if so.
733 * See also g_task_report_error().
738 g_task_report_new_error (gpointer source_object,
739 GAsyncReadyCallback callback,
740 gpointer callback_data,
750 va_start (ap, format);
751 error = g_error_new_valist (domain, code, format, ap);
754 g_task_report_error (source_object, callback, callback_data,
759 * g_task_set_task_data:
761 * @task_data: (allow-none): task-specific data
762 * @task_data_destroy: (allow-none): #GDestroyNotify for @task_data
764 * Sets @task's task data (freeing the existing task data, if any).
769 g_task_set_task_data (GTask *task,
771 GDestroyNotify task_data_destroy)
773 if (task->task_data_destroy)
774 task->task_data_destroy (task->task_data);
776 task->task_data = task_data;
777 task->task_data_destroy = task_data_destroy;
781 * g_task_set_priority:
783 * @priority: the [priority][io-priority] of the request
785 * Sets @task's priority. If you do not call this, it will default to
786 * %G_PRIORITY_DEFAULT.
788 * This will affect the priority of #GSources created with
789 * g_task_attach_source() and the scheduling of tasks run in threads,
790 * and can also be explicitly retrieved later via
791 * g_task_get_priority().
796 g_task_set_priority (GTask *task,
799 task->priority = priority;
803 * g_task_set_check_cancellable:
805 * @check_cancellable: whether #GTask will check the state of
806 * its #GCancellable for you.
808 * Sets or clears @task's check-cancellable flag. If this is %TRUE
809 * (the default), then g_task_propagate_pointer(), etc, and
810 * g_task_had_error() will check the task's #GCancellable first, and
811 * if it has been cancelled, then they will consider the task to have
812 * returned an "Operation was cancelled" error
813 * (%G_IO_ERROR_CANCELLED), regardless of any other error or return
814 * value the task may have had.
816 * If @check_cancellable is %FALSE, then the #GTask will not check the
817 * cancellable itself, and it is up to @task's owner to do this (eg,
818 * via g_task_return_error_if_cancelled()).
820 * If you are using g_task_set_return_on_cancel() as well, then
821 * you must leave check-cancellable set %TRUE.
826 g_task_set_check_cancellable (GTask *task,
827 gboolean check_cancellable)
829 g_return_if_fail (check_cancellable || !task->return_on_cancel);
831 task->check_cancellable = check_cancellable;
834 static void g_task_thread_complete (GTask *task);
837 * g_task_set_return_on_cancel:
839 * @return_on_cancel: whether the task returns automatically when
842 * Sets or clears @task's return-on-cancel flag. This is only
843 * meaningful for tasks run via g_task_run_in_thread() or
844 * g_task_run_in_thread_sync().
846 * If @return_on_cancel is %TRUE, then cancelling @task's
847 * #GCancellable will immediately cause it to return, as though the
848 * task's #GTaskThreadFunc had called
849 * g_task_return_error_if_cancelled() and then returned.
851 * This allows you to create a cancellable wrapper around an
852 * uninterruptable function. The #GTaskThreadFunc just needs to be
853 * careful that it does not modify any externally-visible state after
854 * it has been cancelled. To do that, the thread should call
855 * g_task_set_return_on_cancel() again to (atomically) set
856 * return-on-cancel %FALSE before making externally-visible changes;
857 * if the task gets cancelled before the return-on-cancel flag could
858 * be changed, g_task_set_return_on_cancel() will indicate this by
861 * You can disable and re-enable this flag multiple times if you wish.
862 * If the task's #GCancellable is cancelled while return-on-cancel is
863 * %FALSE, then calling g_task_set_return_on_cancel() to set it %TRUE
864 * again will cause the task to be cancelled at that point.
866 * If the task's #GCancellable is already cancelled before you call
867 * g_task_run_in_thread()/g_task_run_in_thread_sync(), then the
868 * #GTaskThreadFunc will still be run (for consistency), but the task
869 * will also be completed right away.
871 * Returns: %TRUE if @task's return-on-cancel flag was changed to
872 * match @return_on_cancel. %FALSE if @task has already been
878 g_task_set_return_on_cancel (GTask *task,
879 gboolean return_on_cancel)
881 g_return_val_if_fail (task->check_cancellable || !return_on_cancel, FALSE);
883 if (!G_TASK_IS_THREADED (task))
885 task->return_on_cancel = return_on_cancel;
889 g_mutex_lock (&task->lock);
890 if (task->thread_cancelled)
892 if (return_on_cancel && !task->return_on_cancel)
894 g_mutex_unlock (&task->lock);
895 g_task_thread_complete (task);
898 g_mutex_unlock (&task->lock);
901 task->return_on_cancel = return_on_cancel;
902 g_mutex_unlock (&task->lock);
908 * g_task_set_source_tag:
910 * @source_tag: an opaque pointer indicating the source of this task
912 * Sets @task's source tag. You can use this to tag a task return
913 * value with a particular pointer (usually a pointer to the function
914 * doing the tagging) and then later check it using
915 * g_task_get_source_tag() (or g_async_result_is_tagged()) in the
916 * task's "finish" function, to figure out if the response came from a
922 g_task_set_source_tag (GTask *task,
925 task->source_tag = source_tag;
929 * g_task_get_source_object:
932 * Gets the source object from @task. Like
933 * g_async_result_get_source_object(), but does not ref the object.
935 * Returns: (transfer none) (type GObject): @task's source object, or %NULL
940 g_task_get_source_object (GTask *task)
942 return task->source_object;
946 g_task_ref_source_object (GAsyncResult *res)
948 GTask *task = G_TASK (res);
950 if (task->source_object)
951 return g_object_ref (task->source_object);
957 * g_task_get_task_data:
960 * Gets @task's `task_data`.
962 * Returns: (transfer none): @task's `task_data`.
967 g_task_get_task_data (GTask *task)
969 return task->task_data;
973 * g_task_get_priority:
976 * Gets @task's priority
978 * Returns: @task's priority
983 g_task_get_priority (GTask *task)
985 return task->priority;
989 * g_task_get_context:
992 * Gets the #GMainContext that @task will return its result in (that
993 * is, the context that was the
994 * [thread-default main context][g-main-context-push-thread-default]
995 * at the point when @task was created).
997 * This will always return a non-%NULL value, even if the task's
998 * context is the default #GMainContext.
1000 * Returns: (transfer none): @task's #GMainContext
1005 g_task_get_context (GTask *task)
1007 return task->context;
1011 * g_task_get_cancellable:
1014 * Gets @task's #GCancellable
1016 * Returns: (transfer none): @task's #GCancellable
1021 g_task_get_cancellable (GTask *task)
1023 return task->cancellable;
1027 * g_task_get_check_cancellable:
1030 * Gets @task's check-cancellable flag. See
1031 * g_task_set_check_cancellable() for more details.
1036 g_task_get_check_cancellable (GTask *task)
1038 return task->check_cancellable;
1042 * g_task_get_return_on_cancel:
1045 * Gets @task's return-on-cancel flag. See
1046 * g_task_set_return_on_cancel() for more details.
1051 g_task_get_return_on_cancel (GTask *task)
1053 return task->return_on_cancel;
1057 * g_task_get_source_tag:
1060 * Gets @task's source tag. See g_task_set_source_tag().
1062 * Returns: (transfer none): @task's source tag
1067 g_task_get_source_tag (GTask *task)
1069 return task->source_tag;
1074 g_task_return_now (GTask *task)
1076 g_main_context_push_thread_default (task->context);
1077 task->callback (task->source_object,
1078 G_ASYNC_RESULT (task),
1079 task->callback_data);
1080 g_main_context_pop_thread_default (task->context);
1084 complete_in_idle_cb (gpointer task)
1086 g_task_return_now (task);
1087 g_object_unref (task);
1092 G_TASK_RETURN_SUCCESS,
1093 G_TASK_RETURN_ERROR,
1094 G_TASK_RETURN_FROM_THREAD
1098 g_task_return (GTask *task,
1099 GTaskReturnType type)
1103 if (type == G_TASK_RETURN_SUCCESS)
1104 task->result_set = TRUE;
1106 if (task->synchronous || !task->callback)
1109 /* Normally we want to invoke the task's callback when its return
1110 * value is set. But if the task is running in a thread, then we
1111 * want to wait until after the task_func returns, to simplify
1112 * locking/refcounting/etc.
1114 if (G_TASK_IS_THREADED (task) && type != G_TASK_RETURN_FROM_THREAD)
1117 g_object_ref (task);
1119 /* See if we can complete the task immediately. First, we have to be
1120 * running inside the task's thread/GMainContext.
1122 source = g_main_current_source ();
1123 if (source && g_source_get_context (source) == task->context)
1125 /* Second, we can only complete immediately if this is not the
1126 * same iteration of the main loop that the task was created in.
1128 if (g_source_get_time (source) > task->creation_time)
1130 g_task_return_now (task);
1131 g_object_unref (task);
1136 /* Otherwise, complete in the next iteration */
1137 source = g_idle_source_new ();
1138 g_task_attach_source (task, source, complete_in_idle_cb);
1139 g_source_set_name (source, "[gio] 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 /* This introduces a reference count loop between the GTask and
1278 * GCancellable, but is necessary to avoid a race on finalising the GTask
1279 * between task_thread_cancelled() (in one thread) and
1280 * g_task_thread_complete() (in another).
1282 * Accordingly, the signal handler *must* be removed once the task has
1285 g_signal_connect_data (task->cancellable, "cancelled",
1286 G_CALLBACK (task_thread_cancelled),
1287 g_object_ref (task),
1288 task_thread_cancelled_disconnect_notify, 0);
1291 g_thread_pool_push (task_pool, g_object_ref (task), NULL);
1292 if (g_private_get (&task_private))
1294 /* This thread is being spawned from another GTask thread, so
1295 * bump up max-threads so we don't starve.
1297 g_mutex_lock (&task_pool_mutex);
1298 if (g_thread_pool_set_max_threads (task_pool,
1299 g_thread_pool_get_max_threads (task_pool) + 1,
1301 task->blocking_other_task = TRUE;
1302 g_mutex_unlock (&task_pool_mutex);
1307 * g_task_run_in_thread:
1309 * @task_func: a #GTaskThreadFunc
1311 * Runs @task_func in another thread. When @task_func returns, @task's
1312 * #GAsyncReadyCallback will be invoked in @task's #GMainContext.
1314 * This takes a ref on @task until the task completes.
1316 * See #GTaskThreadFunc for more details about how @task_func is handled.
1321 g_task_run_in_thread (GTask *task,
1322 GTaskThreadFunc task_func)
1324 g_return_if_fail (G_IS_TASK (task));
1326 g_object_ref (task);
1327 g_task_start_task_thread (task, task_func);
1329 /* The task may already be cancelled, or g_thread_pool_push() may
1332 if (task->thread_complete)
1334 g_mutex_unlock (&task->lock);
1335 g_task_return (task, G_TASK_RETURN_FROM_THREAD);
1338 g_mutex_unlock (&task->lock);
1340 g_object_unref (task);
1344 * g_task_run_in_thread_sync:
1346 * @task_func: a #GTaskThreadFunc
1348 * Runs @task_func in another thread, and waits for it to return or be
1349 * cancelled. You can use g_task_propagate_pointer(), etc, afterward
1350 * to get the result of @task_func.
1352 * See #GTaskThreadFunc for more details about how @task_func is handled.
1354 * Normally this is used with tasks created with a %NULL
1355 * `callback`, but note that even if the task does
1356 * have a callback, it will not be invoked when @task_func returns.
1361 g_task_run_in_thread_sync (GTask *task,
1362 GTaskThreadFunc task_func)
1364 g_return_if_fail (G_IS_TASK (task));
1366 g_object_ref (task);
1368 task->synchronous = TRUE;
1369 g_task_start_task_thread (task, task_func);
1371 while (!task->thread_complete)
1372 g_cond_wait (&task->cond, &task->lock);
1374 g_mutex_unlock (&task->lock);
1375 g_object_unref (task);
1379 * g_task_attach_source:
1381 * @source: the source to attach
1382 * @callback: the callback to invoke when @source triggers
1384 * A utility function for dealing with async operations where you need
1385 * to wait for a #GSource to trigger. Attaches @source to @task's
1386 * #GMainContext with @task's [priority][io-priority], and sets @source's
1387 * callback to @callback, with @task as the callback's `user_data`.
1389 * This takes a reference on @task until @source is destroyed.
1394 g_task_attach_source (GTask *task,
1396 GSourceFunc callback)
1398 g_source_set_callback (source, callback,
1399 g_object_ref (task), g_object_unref);
1400 g_source_set_priority (source, task->priority);
1401 g_source_attach (source, task->context);
1406 g_task_propagate_error (GTask *task,
1409 if (task->check_cancellable &&
1410 g_cancellable_set_error_if_cancelled (task->cancellable, error))
1412 else if (task->error)
1414 g_propagate_error (error, task->error);
1423 * g_task_return_pointer:
1425 * @result: (allow-none) (transfer full): the pointer result of a task
1427 * @result_destroy: (allow-none): a #GDestroyNotify function.
1429 * Sets @task's result to @result and completes the task. If @result
1430 * is not %NULL, then @result_destroy will be used to free @result if
1431 * the caller does not take ownership of it with
1432 * g_task_propagate_pointer().
1434 * "Completes the task" means that for an ordinary asynchronous task
1435 * it will either invoke the task's callback, or else queue that
1436 * callback to be invoked in the proper #GMainContext, or in the next
1437 * iteration of the current #GMainContext. For a task run via
1438 * g_task_run_in_thread() or g_task_run_in_thread_sync(), calling this
1439 * method will save @result to be returned to the caller later, but
1440 * the task will not actually be completed until the #GTaskThreadFunc
1443 * Note that since the task may be completed before returning from
1444 * g_task_return_pointer(), you cannot assume that @result is still
1445 * valid after calling this, unless you are still holding another
1451 g_task_return_pointer (GTask *task,
1453 GDestroyNotify result_destroy)
1455 g_return_if_fail (task->result_set == FALSE);
1457 task->result.pointer = result;
1458 task->result_destroy = result_destroy;
1460 g_task_return (task, G_TASK_RETURN_SUCCESS);
1464 * g_task_propagate_pointer:
1466 * @error: return location for a #GError
1468 * Gets the result of @task as a pointer, and transfers ownership
1469 * of that value to the caller.
1471 * If the task resulted in an error, or was cancelled, then this will
1472 * instead return %NULL and set @error.
1474 * Since this method transfers ownership of the return value (or
1475 * error) to the caller, you may only call it once.
1477 * Returns: (transfer full): the task result, or %NULL on error
1482 g_task_propagate_pointer (GTask *task,
1485 if (g_task_propagate_error (task, error))
1488 g_return_val_if_fail (task->result_set == TRUE, NULL);
1490 task->result_destroy = NULL;
1491 task->result_set = FALSE;
1492 return task->result.pointer;
1496 * g_task_return_int:
1498 * @result: the integer (#gssize) result of a task function.
1500 * Sets @task's result to @result and completes the task (see
1501 * g_task_return_pointer() for more discussion of exactly what this
1507 g_task_return_int (GTask *task,
1510 g_return_if_fail (task->result_set == FALSE);
1512 task->result.size = result;
1514 g_task_return (task, G_TASK_RETURN_SUCCESS);
1518 * g_task_propagate_int:
1520 * @error: return location for a #GError
1522 * Gets the result of @task as an integer (#gssize).
1524 * If the task resulted in an error, or was cancelled, then this will
1525 * instead return -1 and set @error.
1527 * Since this method transfers ownership of the return value (or
1528 * error) to the caller, you may only call it once.
1530 * Returns: the task result, or -1 on error
1535 g_task_propagate_int (GTask *task,
1538 if (g_task_propagate_error (task, error))
1541 g_return_val_if_fail (task->result_set == TRUE, -1);
1543 task->result_set = FALSE;
1544 return task->result.size;
1548 * g_task_return_boolean:
1550 * @result: the #gboolean result of a task function.
1552 * Sets @task's result to @result and completes the task (see
1553 * g_task_return_pointer() for more discussion of exactly what this
1559 g_task_return_boolean (GTask *task,
1562 g_return_if_fail (task->result_set == FALSE);
1564 task->result.boolean = result;
1566 g_task_return (task, G_TASK_RETURN_SUCCESS);
1570 * g_task_propagate_boolean:
1572 * @error: return location for a #GError
1574 * Gets the result of @task as a #gboolean.
1576 * If the task resulted in an error, or was cancelled, then this will
1577 * instead return %FALSE and set @error.
1579 * Since this method transfers ownership of the return value (or
1580 * error) to the caller, you may only call it once.
1582 * Returns: the task result, or %FALSE on error
1587 g_task_propagate_boolean (GTask *task,
1590 if (g_task_propagate_error (task, error))
1593 g_return_val_if_fail (task->result_set == TRUE, FALSE);
1595 task->result_set = FALSE;
1596 return task->result.boolean;
1600 * g_task_return_error:
1602 * @error: (transfer full): the #GError result of a task function.
1604 * Sets @task's result to @error (which @task assumes ownership of)
1605 * and completes the task (see g_task_return_pointer() for more
1606 * discussion of exactly what this means).
1608 * Note that since the task takes ownership of @error, and since the
1609 * task may be completed before returning from g_task_return_error(),
1610 * you cannot assume that @error is still valid after calling this.
1611 * Call g_error_copy() on the error if you need to keep a local copy
1614 * See also g_task_return_new_error().
1619 g_task_return_error (GTask *task,
1622 g_return_if_fail (task->result_set == FALSE);
1623 g_return_if_fail (error != NULL);
1625 task->error = error;
1627 g_task_return (task, G_TASK_RETURN_ERROR);
1631 * g_task_return_new_error:
1633 * @domain: a #GQuark.
1634 * @code: an error code.
1635 * @format: a string with format characters.
1636 * @...: a list of values to insert into @format.
1638 * Sets @task's result to a new #GError created from @domain, @code,
1639 * @format, and the remaining arguments, and completes the task (see
1640 * g_task_return_pointer() for more discussion of exactly what this
1643 * See also g_task_return_error().
1648 g_task_return_new_error (GTask *task,
1657 va_start (args, format);
1658 error = g_error_new_valist (domain, code, format, args);
1661 g_task_return_error (task, error);
1665 * g_task_return_error_if_cancelled:
1668 * Checks if @task's #GCancellable has been cancelled, and if so, sets
1669 * @task's error accordingly and completes the task (see
1670 * g_task_return_pointer() for more discussion of exactly what this
1673 * Returns: %TRUE if @task has been cancelled, %FALSE if not
1678 g_task_return_error_if_cancelled (GTask *task)
1680 GError *error = NULL;
1682 g_return_val_if_fail (task->result_set == FALSE, FALSE);
1684 if (g_cancellable_set_error_if_cancelled (task->cancellable, &error))
1686 /* We explicitly set task->error so this works even when
1687 * check-cancellable is not set.
1689 g_clear_error (&task->error);
1690 task->error = error;
1692 g_task_return (task, G_TASK_RETURN_ERROR);
1703 * Tests if @task resulted in an error.
1705 * Returns: %TRUE if the task resulted in an error, %FALSE otherwise.
1710 g_task_had_error (GTask *task)
1712 if (task->error != NULL)
1715 if (task->check_cancellable && g_cancellable_is_cancelled (task->cancellable))
1723 * @result: (type Gio.AsyncResult): A #GAsyncResult
1724 * @source_object: (allow-none) (type GObject): the source object
1725 * expected to be associated with the task
1727 * Checks that @result is a #GTask, and that @source_object is its
1728 * source object (or that @source_object is %NULL and @result has no
1729 * source object). This can be used in g_return_if_fail() checks.
1731 * Returns: %TRUE if @result and @source_object are valid, %FALSE
1737 g_task_is_valid (gpointer result,
1738 gpointer source_object)
1740 if (!G_IS_TASK (result))
1743 return G_TASK (result)->source_object == source_object;
1747 g_task_compare_priority (gconstpointer a,
1751 const GTask *ta = a;
1752 const GTask *tb = b;
1753 gboolean a_cancelled, b_cancelled;
1755 /* Tasks that are causing other tasks to block have higher
1758 if (ta->blocking_other_task && !tb->blocking_other_task)
1760 else if (tb->blocking_other_task && !ta->blocking_other_task)
1763 /* Let already-cancelled tasks finish right away */
1764 a_cancelled = (ta->check_cancellable &&
1765 g_cancellable_is_cancelled (ta->cancellable));
1766 b_cancelled = (tb->check_cancellable &&
1767 g_cancellable_is_cancelled (tb->cancellable));
1768 if (a_cancelled && !b_cancelled)
1770 else if (b_cancelled && !a_cancelled)
1773 /* Lower priority == run sooner == negative return value */
1774 return ta->priority - tb->priority;
1778 g_task_thread_pool_init (void)
1780 task_pool = g_thread_pool_new (g_task_thread_pool_thread, NULL,
1782 g_assert (task_pool != NULL);
1784 g_thread_pool_set_sort_function (task_pool, g_task_compare_priority, NULL);
1788 g_task_thread_pool_resort (void)
1790 g_thread_pool_set_sort_function (task_pool, g_task_compare_priority, NULL);
1794 g_task_class_init (GTaskClass *klass)
1796 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
1798 gobject_class->finalize = g_task_finalize;
1802 g_task_get_user_data (GAsyncResult *res)
1804 return G_TASK (res)->callback_data;
1808 g_task_is_tagged (GAsyncResult *res,
1809 gpointer source_tag)
1811 return G_TASK (res)->source_tag == source_tag;
1815 g_task_async_result_iface_init (GAsyncResultIface *iface)
1817 iface->get_user_data = g_task_get_user_data;
1818 iface->get_source_object = g_task_ref_source_object;
1819 iface->is_tagged = g_task_is_tagged;