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:
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(), and
152 * g_task_get_priority() allow you to get back the task's
153 * #GCancellable, #GMainContext, and <link
154 * linkend="io-priority">I/O priority</link> when starting a new
155 * subtask, so you don't have to keep track of them yourself.
156 * g_task_attach_source() simplifies the case of waiting for a
157 * source to fire (automatically using the correct #GMainContext
160 * Here is an example for chained asynchronous operations:
164 * CakeFrostingType frosting;
169 * decoration_data_free (BakingData *bd)
172 * g_object_unref (bd->cake);
173 * g_free (bd->message);
174 * g_slice_free (BakingData, bd);
178 * decorated_cb (Cake *cake,
179 * GAsyncResult *result,
180 * gpointer user_data)
182 * GTask *task = user_data;
183 * GError *error = NULL;
185 * if (!cake_decorate_finish (cake, result, &error))
187 * g_object_unref (cake);
188 * g_task_return_error (task, error);
189 * g_object_unref (task);
193 * /* baking_data_free() will drop its ref on the cake, so
194 * * we have to take another here to give to the caller.
196 * g_task_return_pointer (result, g_object_ref (cake), g_object_unref);
197 * g_object_unref (task);
201 * decorator_ready (gpointer user_data)
203 * GTask *task = user_data;
204 * BakingData *bd = g_task_get_task_data (task);
206 * cake_decorate_async (bd->cake, bd->frosting, bd->message,
207 * g_task_get_cancellable (task),
208 * decorated_cb, task);
212 * baked_cb (Cake *cake,
213 * gpointer user_data)
215 * GTask *task = user_data;
216 * BakingData *bd = g_task_get_task_data (task);
217 * GError *error = NULL;
221 * g_task_return_new_error (task, BAKER_ERROR, BAKER_ERROR_NO_FLOUR,
222 * "Go to the supermarket");
223 * g_object_unref (task);
229 * /* Bail out now if the user has already cancelled */
230 * if (g_task_return_error_if_cancelled (task))
232 * g_object_unref (task);
236 * if (cake_decorator_available (cake))
237 * decorator_ready (task);
242 * source = cake_decorator_wait_source_new (cake);
243 * /* Attach @source to @task's GMainContext and have it call
244 * * decorator_ready() when it is ready.
246 * g_task_attach_source (task, source,
247 * G_CALLBACK (decorator_ready));
248 * g_source_unref (source);
253 * baker_bake_cake_async (Baker *self,
256 * CakeFrostingType frosting,
257 * const char *message,
259 * GCancellable *cancellable,
260 * GAsyncReadyCallback callback,
261 * gpointer user_data)
266 * task = g_task_new (self, cancellable, callback, user_data);
267 * g_task_set_priority (task, priority);
269 * bd = g_slice_new0 (BakingData);
270 * bd->frosting = frosting;
271 * bd->message = g_strdup (message);
272 * g_task_set_task_data (task, bd, (GDestroyNotify) baking_data_free);
274 * _baker_begin_cake (self, radius, flavor, cancellable, baked_cb, task);
278 * baker_bake_cake_finish (Baker *self,
279 * GAsyncResult *result,
282 * g_return_val_if_fail (g_task_is_valid (result, self), NULL);
284 * return g_task_propagate_pointer (G_TASK (result), error);
288 * ## Asynchronous operations from synchronous ones
290 * You can use g_task_run_in_thread() to turn a synchronous
291 * operation into an asynchronous one, by running it in a thread
292 * which will then dispatch the result back to the caller's
293 * #GMainContext when it completes.
295 * Running a task in a thread:
300 * CakeFrostingType frosting;
305 * cake_data_free (CakeData *cake_data)
307 * g_free (cake_data->message);
308 * g_slice_free (CakeData, cake_data);
312 * bake_cake_thread (GTask *task,
313 * gpointer source_object,
314 * gpointer task_data,
315 * GCancellable *cancellable)
317 * Baker *self = source_object;
318 * CakeData *cake_data = task_data;
320 * GError *error = NULL;
322 * cake = bake_cake (baker, cake_data->radius, cake_data->flavor,
323 * cake_data->frosting, cake_data->message,
324 * cancellable, &error);
326 * g_task_return_pointer (task, cake, g_object_unref);
328 * g_task_return_error (task, error);
332 * baker_bake_cake_async (Baker *self,
335 * CakeFrostingType frosting,
336 * const char *message,
337 * GCancellable *cancellable,
338 * GAsyncReadyCallback callback,
339 * gpointer user_data)
341 * CakeData *cake_data;
344 * cake_data = g_slice_new (CakeData);
345 * cake_data->radius = radius;
346 * cake_data->flavor = flavor;
347 * cake_data->frosting = frosting;
348 * cake_data->message = g_strdup (message);
349 * task = g_task_new (self, cancellable, callback, user_data);
350 * g_task_set_task_data (task, cake_data, (GDestroyNotify) cake_data_free);
351 * g_task_run_in_thread (task, bake_cake_thread);
355 * baker_bake_cake_finish (Baker *self,
356 * GAsyncResult *result,
359 * g_return_val_if_fail (g_task_is_valid (result, self), NULL);
361 * return g_task_propagate_pointer (G_TASK (result), error);
365 * ## Adding cancellability to uncancellable tasks
367 * Finally, g_task_run_in_thread() and g_task_run_in_thread_sync()
368 * can be used to turn an uncancellable operation into a
369 * cancellable one. If you call g_task_set_return_on_cancel(),
370 * passing %TRUE, then if the task's #GCancellable is cancelled,
371 * it will return control back to the caller immediately, while
372 * allowing the task thread to continue running in the background
373 * (and simply discarding its result when it finally does finish).
374 * Provided that the task thread is careful about how it uses
375 * locks and other externally-visible resources, this allows you
376 * to make "GLib-friendly" asynchronous and cancellable
377 * synchronous variants of blocking APIs.
382 * bake_cake_thread (GTask *task,
383 * gpointer source_object,
384 * gpointer task_data,
385 * GCancellable *cancellable)
387 * Baker *self = source_object;
388 * CakeData *cake_data = task_data;
390 * GError *error = NULL;
392 * cake = bake_cake (baker, cake_data->radius, cake_data->flavor,
393 * cake_data->frosting, cake_data->message,
397 * g_task_return_error (task, error);
401 * /* If the task has already been cancelled, then we don't
402 * * want to add the cake to the cake cache. Likewise, we don't
403 * * want to have the task get cancelled in the middle of
404 * * updating the cache. g_task_set_return_on_cancel() will
405 * * return %TRUE here if it managed to disable return-on-cancel,
406 * * or %FALSE if the task was cancelled before it could.
408 * if (g_task_set_return_on_cancel (task, FALSE))
410 * /* If the caller cancels at this point, their
411 * * GAsyncReadyCallback won't be invoked until we return,
412 * * so we don't have to worry that this code will run at
413 * * the same time as that code does. But if there were
414 * * other functions that might look at the cake cache,
415 * * then we'd probably need a GMutex here as well.
417 * baker_add_cake_to_cache (baker, cake);
418 * g_task_return_pointer (task, cake, g_object_unref);
423 * baker_bake_cake_async (Baker *self,
426 * CakeFrostingType frosting,
427 * const char *message,
428 * GCancellable *cancellable,
429 * GAsyncReadyCallback callback,
430 * gpointer user_data)
432 J* CakeData *cake_data;
435 * cake_data = g_slice_new (CakeData);
438 * task = g_task_new (self, cancellable, callback, user_data);
439 * g_task_set_task_data (task, cake_data, (GDestroyNotify) cake_data_free);
440 * g_task_set_return_on_cancel (task, TRUE);
441 * g_task_run_in_thread (task, bake_cake_thread);
445 * baker_bake_cake_sync (Baker *self,
448 * CakeFrostingType frosting,
449 * const char *message,
450 * GCancellable *cancellable,
453 * CakeData *cake_data;
457 * cake_data = g_slice_new (CakeData);
460 * task = g_task_new (self, cancellable, NULL, NULL);
461 * g_task_set_task_data (task, cake_data, (GDestroyNotify) cake_data_free);
462 * g_task_set_return_on_cancel (task, TRUE);
463 * g_task_run_in_thread_sync (task, bake_cake_thread);
465 * cake = g_task_propagate_pointer (task, error);
466 * g_object_unref (task);
471 * ## Porting from GSimpleAsyncResult
473 * #GTask's API attempts to be simpler than #GSimpleAsyncResult's
475 * - You can save task-specific data with g_task_set_task_data(), and
476 * retrieve it later with g_task_get_task_data(). This replaces the
477 * abuse of g_simple_async_result_set_op_res_gpointer() for the same
478 * purpose with #GSimpleAsyncResult.
479 * - In addition to the task data, #GTask also keeps track of the
480 * <link linkend="io-priority">priority</link>, #GCancellable, and
481 * #GMainContext associated with the task, so tasks that consist of
482 * a chain of simpler asynchronous operations will have easy access
483 * to those values when starting each sub-task.
484 * - g_task_return_error_if_cancelled() provides simplified
485 * handling for cancellation. In addition, cancellation
486 * overrides any other #GTask return value by default, like
487 * #GSimpleAsyncResult does when
488 * g_simple_async_result_set_check_cancellable() is called.
489 * (You can use g_task_set_check_cancellable() to turn off that
490 * behavior.) On the other hand, g_task_run_in_thread()
491 * guarantees that it will always run your
492 * <literal>task_func</literal>, even if the task's #GCancellable
493 * is already cancelled before the task gets a chance to run;
494 * you can start your <literal>task_func</literal> with a
495 * g_task_return_error_if_cancelled() check if you need the
497 * - The "return" methods (eg, g_task_return_pointer())
498 * automatically cause the task to be "completed" as well, and
499 * there is no need to worry about the "complete" vs "complete
500 * in idle" distinction. (#GTask automatically figures out
501 * whether the task's callback can be invoked directly, or
502 * if it needs to be sent to another #GMainContext, or delayed
503 * until the next iteration of the current #GMainContext.)
504 * - The "finish" functions for #GTask-based operations are generally
505 * much simpler than #GSimpleAsyncResult ones, normally consisting
506 * of only a single call to g_task_propagate_pointer() or the like.
507 * Since g_task_propagate_pointer() "steals" the return value from
508 * the #GTask, it is not necessary to juggle pointers around to
509 * prevent it from being freed twice.
510 * - With #GSimpleAsyncResult, it was common to call
511 * g_simple_async_result_propagate_error() from the
512 * <literal>_finish()</literal> wrapper function, and have
513 * virtual method implementations only deal with successful
514 * returns. This behavior is deprecated, because it makes it
515 * difficult for a subclass to chain to a parent class's async
516 * methods. Instead, the wrapper function should just be a
517 * simple wrapper, and the virtual method should call an
518 * appropriate <literal>g_task_propagate_</literal> function.
519 * Note that wrapper methods can now use
520 * g_async_result_legacy_propagate_error() to do old-style
521 * #GSimpleAsyncResult error-returning behavior, and
522 * g_async_result_is_tagged() to check if a result is tagged as
523 * having come from the <literal>_async()</literal> wrapper
524 * function (for "short-circuit" results, such as when passing
525 * 0 to g_input_stream_read_async()).
531 * The opaque object representing a synchronous or asynchronous task
536 GObject parent_instance;
538 gpointer source_object;
542 GDestroyNotify task_data_destroy;
544 GMainContext *context;
545 guint64 creation_time;
547 GCancellable *cancellable;
548 gboolean check_cancellable;
550 GAsyncReadyCallback callback;
551 gpointer callback_data;
553 GTaskThreadFunc task_func;
556 gboolean return_on_cancel;
557 gboolean thread_cancelled;
558 gboolean synchronous;
559 gboolean thread_complete;
560 gboolean blocking_other_task;
568 GDestroyNotify result_destroy;
572 #define G_TASK_IS_THREADED(task) ((task)->task_func != NULL)
576 GObjectClass parent_class;
579 static void g_task_thread_pool_resort (void);
581 static void g_task_async_result_iface_init (GAsyncResultIface *iface);
582 static void g_task_thread_pool_init (void);
584 G_DEFINE_TYPE_WITH_CODE (GTask, g_task, G_TYPE_OBJECT,
585 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_RESULT,
586 g_task_async_result_iface_init);
587 g_task_thread_pool_init ();)
589 static GThreadPool *task_pool;
590 static GMutex task_pool_mutex;
591 static GPrivate task_private = G_PRIVATE_INIT (NULL);
594 g_task_init (GTask *task)
596 task->check_cancellable = TRUE;
600 g_task_finalize (GObject *object)
602 GTask *task = G_TASK (object);
604 g_clear_object (&task->source_object);
605 g_clear_object (&task->cancellable);
608 g_main_context_unref (task->context);
610 if (task->task_data_destroy)
611 task->task_data_destroy (task->task_data);
613 if (task->result_destroy && task->result.pointer)
614 task->result_destroy (task->result.pointer);
617 g_error_free (task->error);
619 if (G_TASK_IS_THREADED (task))
621 g_mutex_clear (&task->lock);
622 g_cond_clear (&task->cond);
625 G_OBJECT_CLASS (g_task_parent_class)->finalize (object);
630 * @source_object: (allow-none) (type GObject): the #GObject that owns
631 * this task, or %NULL.
632 * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore.
633 * @callback: (scope async): a #GAsyncReadyCallback.
634 * @callback_data: (closure): user data passed to @callback.
636 * Creates a #GTask acting on @source_object, which will eventually be
637 * used to invoke @callback in the current <link
638 * linkend="g-main-context-push-thread-default">thread-default main
641 * Call this in the "start" method of your asynchronous method, and
642 * pass the #GTask around throughout the asynchronous operation. You
643 * can use g_task_set_task_data() to attach task-specific data to the
644 * object, which you can retrieve later via g_task_get_task_data().
646 * By default, if @cancellable is cancelled, then the return value of
647 * the task will always be %G_IO_ERROR_CANCELLED, even if the task had
648 * already completed before the cancellation. This allows for
649 * simplified handling in cases where cancellation may imply that
650 * other objects that the task depends on have been destroyed. If you
651 * do not want this behavior, you can use
652 * g_task_set_check_cancellable() to change it.
659 g_task_new (gpointer source_object,
660 GCancellable *cancellable,
661 GAsyncReadyCallback callback,
662 gpointer callback_data)
667 task = g_object_new (G_TYPE_TASK, NULL);
668 task->source_object = source_object ? g_object_ref (source_object) : NULL;
669 task->cancellable = cancellable ? g_object_ref (cancellable) : NULL;
670 task->callback = callback;
671 task->callback_data = callback_data;
672 task->context = g_main_context_ref_thread_default ();
674 source = g_main_current_source ();
676 task->creation_time = g_source_get_time (source);
682 * g_task_report_error:
683 * @source_object: (allow-none) (type GObject): the #GObject that owns
684 * this task, or %NULL.
685 * @callback: (scope async): a #GAsyncReadyCallback.
686 * @callback_data: (closure): user data passed to @callback.
687 * @source_tag: an opaque pointer indicating the source of this task
688 * @error: (transfer full): error to report
690 * Creates a #GTask and then immediately calls g_task_return_error()
691 * on it. Use this in the wrapper function of an asynchronous method
692 * when you want to avoid even calling the virtual method. You can
693 * then use g_async_result_is_tagged() in the finish method wrapper to
694 * check if the result there is tagged as having been created by the
695 * wrapper method, and deal with it appropriately if so.
697 * See also g_task_report_new_error().
702 g_task_report_error (gpointer source_object,
703 GAsyncReadyCallback callback,
704 gpointer callback_data,
710 task = g_task_new (source_object, NULL, callback, callback_data);
711 g_task_set_source_tag (task, source_tag);
712 g_task_return_error (task, error);
713 g_object_unref (task);
717 * g_task_report_new_error:
718 * @source_object: (allow-none) (type GObject): the #GObject that owns
719 * this task, or %NULL.
720 * @callback: (scope async): a #GAsyncReadyCallback.
721 * @callback_data: (closure): user data passed to @callback.
722 * @source_tag: an opaque pointer indicating the source of this task
723 * @domain: a #GQuark.
724 * @code: an error code.
725 * @format: a string with format characters.
726 * @...: a list of values to insert into @format.
728 * Creates a #GTask and then immediately calls
729 * g_task_return_new_error() on it. Use this in the wrapper function
730 * of an asynchronous method when you want to avoid even calling the
731 * virtual method. You can then use g_async_result_is_tagged() in the
732 * finish method wrapper to check if the result there is tagged as
733 * having been created by the wrapper method, and deal with it
734 * appropriately if so.
736 * See also g_task_report_error().
741 g_task_report_new_error (gpointer source_object,
742 GAsyncReadyCallback callback,
743 gpointer callback_data,
753 va_start (ap, format);
754 error = g_error_new_valist (domain, code, format, ap);
757 g_task_report_error (source_object, callback, callback_data,
762 * g_task_set_task_data:
764 * @task_data: (allow-none): task-specific data
765 * @task_data_destroy: (allow-none): #GDestroyNotify for @task_data
767 * Sets @task's task data (freeing the existing task data, if any).
772 g_task_set_task_data (GTask *task,
774 GDestroyNotify task_data_destroy)
776 if (task->task_data_destroy)
777 task->task_data_destroy (task->task_data);
779 task->task_data = task_data;
780 task->task_data_destroy = task_data_destroy;
784 * g_task_set_priority:
786 * @priority: the <link linkend="io-priority">priority</link>
789 * Sets @task's priority. If you do not call this, it will default to
790 * %G_PRIORITY_DEFAULT.
792 * This will affect the priority of #GSources created with
793 * g_task_attach_source() and the scheduling of tasks run in threads,
794 * and can also be explicitly retrieved later via
795 * g_task_get_priority().
800 g_task_set_priority (GTask *task,
803 task->priority = priority;
807 * g_task_set_check_cancellable:
809 * @check_cancellable: whether #GTask will check the state of
810 * its #GCancellable for you.
812 * Sets or clears @task's check-cancellable flag. If this is %TRUE
813 * (the default), then g_task_propagate_pointer(), etc, and
814 * g_task_had_error() will check the task's #GCancellable first, and
815 * if it has been cancelled, then they will consider the task to have
816 * returned an "Operation was cancelled" error
817 * (%G_IO_ERROR_CANCELLED), regardless of any other error or return
818 * value the task may have had.
820 * If @check_cancellable is %FALSE, then the #GTask will not check the
821 * cancellable itself, and it is up to @task's owner to do this (eg,
822 * via g_task_return_error_if_cancelled()).
824 * If you are using g_task_set_return_on_cancel() as well, then
825 * you must leave check-cancellable set %TRUE.
830 g_task_set_check_cancellable (GTask *task,
831 gboolean check_cancellable)
833 g_return_if_fail (check_cancellable || !task->return_on_cancel);
835 task->check_cancellable = check_cancellable;
838 static void g_task_thread_complete (GTask *task);
841 * g_task_set_return_on_cancel:
843 * @return_on_cancel: whether the task returns automatically when
846 * Sets or clears @task's return-on-cancel flag. This is only
847 * meaningful for tasks run via g_task_run_in_thread() or
848 * g_task_run_in_thread_sync().
850 * If @return_on_cancel is %TRUE, then cancelling @task's
851 * #GCancellable will immediately cause it to return, as though the
852 * task's #GTaskThreadFunc had called
853 * g_task_return_error_if_cancelled() and then returned.
855 * This allows you to create a cancellable wrapper around an
856 * uninterruptable function. The #GTaskThreadFunc just needs to be
857 * careful that it does not modify any externally-visible state after
858 * it has been cancelled. To do that, the thread should call
859 * g_task_set_return_on_cancel() again to (atomically) set
860 * return-on-cancel %FALSE before making externally-visible changes;
861 * if the task gets cancelled before the return-on-cancel flag could
862 * be changed, g_task_set_return_on_cancel() will indicate this by
865 * You can disable and re-enable this flag multiple times if you wish.
866 * If the task's #GCancellable is cancelled while return-on-cancel is
867 * %FALSE, then calling g_task_set_return_on_cancel() to set it %TRUE
868 * again will cause the task to be cancelled at that point.
870 * If the task's #GCancellable is already cancelled before you call
871 * g_task_run_in_thread()/g_task_run_in_thread_sync(), then the
872 * #GTaskThreadFunc will still be run (for consistency), but the task
873 * will also be completed right away.
875 * Returns: %TRUE if @task's return-on-cancel flag was changed to
876 * match @return_on_cancel. %FALSE if @task has already been
882 g_task_set_return_on_cancel (GTask *task,
883 gboolean return_on_cancel)
885 g_return_val_if_fail (task->check_cancellable || !return_on_cancel, FALSE);
887 if (!G_TASK_IS_THREADED (task))
889 task->return_on_cancel = return_on_cancel;
893 g_mutex_lock (&task->lock);
894 if (task->thread_cancelled)
896 if (return_on_cancel && !task->return_on_cancel)
898 g_mutex_unlock (&task->lock);
899 g_task_thread_complete (task);
902 g_mutex_unlock (&task->lock);
905 task->return_on_cancel = return_on_cancel;
906 g_mutex_unlock (&task->lock);
912 * g_task_set_source_tag:
914 * @source_tag: an opaque pointer indicating the source of this task
916 * Sets @task's source tag. You can use this to tag a task return
917 * value with a particular pointer (usually a pointer to the function
918 * doing the tagging) and then later check it using
919 * g_task_get_source_tag() (or g_async_result_is_tagged()) in the
920 * task's "finish" function, to figure out if the response came from a
926 g_task_set_source_tag (GTask *task,
929 task->source_tag = source_tag;
933 * g_task_get_source_object:
936 * Gets the source object from @task. Like
937 * g_async_result_get_source_object(), but does not ref the object.
939 * Returns: (transfer none) (type GObject): @task's source object, or %NULL
944 g_task_get_source_object (GTask *task)
946 return task->source_object;
950 g_task_ref_source_object (GAsyncResult *res)
952 GTask *task = G_TASK (res);
954 if (task->source_object)
955 return g_object_ref (task->source_object);
961 * g_task_get_task_data:
964 * Gets @task's <literal>task_data</literal>.
966 * Returns: (transfer none): @task's <literal>task_data</literal>.
971 g_task_get_task_data (GTask *task)
973 return task->task_data;
977 * g_task_get_priority:
980 * Gets @task's priority
982 * Returns: @task's priority
987 g_task_get_priority (GTask *task)
989 return task->priority;
993 * g_task_get_context:
996 * Gets the #GMainContext that @task will return its result in (that
997 * is, the context that was the <link
998 * linkend="g-main-context-push-thread-default">thread-default main
999 * context</link> at the point when @task was created).
1001 * This will always return a non-%NULL value, even if the task's
1002 * context is the default #GMainContext.
1004 * Returns: (transfer none): @task's #GMainContext
1009 g_task_get_context (GTask *task)
1011 return task->context;
1015 * g_task_get_cancellable:
1018 * Gets @task's #GCancellable
1020 * Returns: (transfer none): @task's #GCancellable
1025 g_task_get_cancellable (GTask *task)
1027 return task->cancellable;
1031 * g_task_get_check_cancellable:
1034 * Gets @task's check-cancellable flag. See
1035 * g_task_set_check_cancellable() for more details.
1040 g_task_get_check_cancellable (GTask *task)
1042 return task->check_cancellable;
1046 * g_task_get_return_on_cancel:
1049 * Gets @task's return-on-cancel flag. See
1050 * g_task_set_return_on_cancel() for more details.
1055 g_task_get_return_on_cancel (GTask *task)
1057 return task->return_on_cancel;
1061 * g_task_get_source_tag:
1064 * Gets @task's source tag. See g_task_set_source_tag().
1066 * Return value: (transfer none): @task's source tag
1071 g_task_get_source_tag (GTask *task)
1073 return task->source_tag;
1078 g_task_return_now (GTask *task)
1080 g_main_context_push_thread_default (task->context);
1081 task->callback (task->source_object,
1082 G_ASYNC_RESULT (task),
1083 task->callback_data);
1084 g_main_context_pop_thread_default (task->context);
1088 complete_in_idle_cb (gpointer task)
1090 g_task_return_now (task);
1091 g_object_unref (task);
1096 G_TASK_RETURN_SUCCESS,
1097 G_TASK_RETURN_ERROR,
1098 G_TASK_RETURN_FROM_THREAD
1102 g_task_return (GTask *task,
1103 GTaskReturnType type)
1107 if (type == G_TASK_RETURN_SUCCESS)
1108 task->result_set = TRUE;
1110 if (task->synchronous || !task->callback)
1113 /* Normally we want to invoke the task's callback when its return
1114 * value is set. But if the task is running in a thread, then we
1115 * want to wait until after the task_func returns, to simplify
1116 * locking/refcounting/etc.
1118 if (G_TASK_IS_THREADED (task) && type != G_TASK_RETURN_FROM_THREAD)
1121 g_object_ref (task);
1123 /* See if we can complete the task immediately. First, we have to be
1124 * running inside the task's thread/GMainContext.
1126 source = g_main_current_source ();
1127 if (source && g_source_get_context (source) == task->context)
1129 /* Second, we can only complete immediately if this is not the
1130 * same iteration of the main loop that the task was created in.
1132 if (g_source_get_time (source) > task->creation_time)
1134 g_task_return_now (task);
1135 g_object_unref (task);
1140 /* Otherwise, complete in the next iteration */
1141 source = g_idle_source_new ();
1142 g_task_attach_source (task, source, complete_in_idle_cb);
1143 g_source_unref (source);
1150 * @source_object: (type GObject): @task's source object
1151 * @task_data: @task's task data
1152 * @cancellable: @task's #GCancellable, or %NULL
1154 * The prototype for a task function to be run in a thread via
1155 * g_task_run_in_thread() or g_task_run_in_thread_sync().
1157 * If the return-on-cancel flag is set on @task, and @cancellable gets
1158 * cancelled, then the #GTask will be completed immediately (as though
1159 * g_task_return_error_if_cancelled() had been called), without
1160 * waiting for the task function to complete. However, the task
1161 * function will continue running in its thread in the background. The
1162 * function therefore needs to be careful about how it uses
1163 * externally-visible state in this case. See
1164 * g_task_set_return_on_cancel() for more details.
1166 * Other than in that case, @task will be completed when the
1167 * #GTaskThreadFunc returns, not when it calls a
1168 * <literal>g_task_return_</literal> function.
1173 static void task_thread_cancelled (GCancellable *cancellable,
1174 gpointer user_data);
1177 g_task_thread_complete (GTask *task)
1179 g_mutex_lock (&task->lock);
1180 if (task->thread_complete)
1182 /* The task belatedly completed after having been cancelled
1183 * (or was cancelled in the midst of being completed).
1185 g_mutex_unlock (&task->lock);
1189 task->thread_complete = TRUE;
1191 if (task->blocking_other_task)
1193 g_mutex_lock (&task_pool_mutex);
1194 g_thread_pool_set_max_threads (task_pool,
1195 g_thread_pool_get_max_threads (task_pool) - 1,
1197 g_mutex_unlock (&task_pool_mutex);
1199 g_mutex_unlock (&task->lock);
1201 if (task->cancellable)
1202 g_signal_handlers_disconnect_by_func (task->cancellable, task_thread_cancelled, task);
1204 if (task->synchronous)
1205 g_cond_signal (&task->cond);
1207 g_task_return (task, G_TASK_RETURN_FROM_THREAD);
1211 g_task_thread_pool_thread (gpointer thread_data,
1214 GTask *task = thread_data;
1216 g_private_set (&task_private, task);
1218 task->task_func (task, task->source_object, task->task_data,
1220 g_task_thread_complete (task);
1222 g_private_set (&task_private, NULL);
1223 g_object_unref (task);
1227 task_thread_cancelled (GCancellable *cancellable,
1230 GTask *task = user_data;
1232 g_task_thread_pool_resort ();
1234 g_mutex_lock (&task->lock);
1235 task->thread_cancelled = TRUE;
1237 if (!task->return_on_cancel)
1239 g_mutex_unlock (&task->lock);
1243 /* We don't actually set task->error; g_task_return_error() doesn't
1244 * use a lock, and g_task_propagate_error() will call
1245 * g_cancellable_set_error_if_cancelled() anyway.
1247 g_mutex_unlock (&task->lock);
1248 g_task_thread_complete (task);
1252 task_thread_cancelled_disconnect_notify (gpointer task,
1255 g_object_unref (task);
1259 g_task_start_task_thread (GTask *task,
1260 GTaskThreadFunc task_func)
1262 g_mutex_init (&task->lock);
1263 g_cond_init (&task->cond);
1265 g_mutex_lock (&task->lock);
1267 task->task_func = task_func;
1269 if (task->cancellable)
1271 if (task->return_on_cancel &&
1272 g_cancellable_set_error_if_cancelled (task->cancellable,
1275 task->thread_cancelled = task->thread_complete = TRUE;
1276 g_thread_pool_push (task_pool, g_object_ref (task), NULL);
1280 g_signal_connect_data (task->cancellable, "cancelled",
1281 G_CALLBACK (task_thread_cancelled),
1282 g_object_ref (task),
1283 task_thread_cancelled_disconnect_notify, 0);
1286 g_thread_pool_push (task_pool, g_object_ref (task), &task->error);
1288 task->thread_complete = TRUE;
1289 else if (g_private_get (&task_private))
1291 /* This thread is being spawned from another GTask thread, so
1292 * bump up max-threads so we don't starve.
1294 g_mutex_lock (&task_pool_mutex);
1295 if (g_thread_pool_set_max_threads (task_pool,
1296 g_thread_pool_get_max_threads (task_pool) + 1,
1298 task->blocking_other_task = TRUE;
1299 g_mutex_unlock (&task_pool_mutex);
1304 * g_task_run_in_thread:
1306 * @task_func: a #GTaskThreadFunc
1308 * Runs @task_func in another thread. When @task_func returns, @task's
1309 * #GAsyncReadyCallback will be invoked in @task's #GMainContext.
1311 * This takes a ref on @task until the task completes.
1313 * See #GTaskThreadFunc for more details about how @task_func is handled.
1318 g_task_run_in_thread (GTask *task,
1319 GTaskThreadFunc task_func)
1321 g_return_if_fail (G_IS_TASK (task));
1323 g_object_ref (task);
1324 g_task_start_task_thread (task, task_func);
1326 /* The task may already be cancelled, or g_thread_pool_push() may
1329 if (task->thread_complete)
1331 g_mutex_unlock (&task->lock);
1332 g_task_return (task, G_TASK_RETURN_FROM_THREAD);
1335 g_mutex_unlock (&task->lock);
1337 g_object_unref (task);
1341 * g_task_run_in_thread_sync:
1343 * @task_func: a #GTaskThreadFunc
1345 * Runs @task_func in another thread, and waits for it to return or be
1346 * cancelled. You can use g_task_propagate_pointer(), etc, afterward
1347 * to get the result of @task_func.
1349 * See #GTaskThreadFunc for more details about how @task_func is handled.
1351 * Normally this is used with tasks created with a %NULL
1352 * <literal>callback</literal>, but note that even if the task does
1353 * have a callback, it will not be invoked when @task_func returns.
1358 g_task_run_in_thread_sync (GTask *task,
1359 GTaskThreadFunc task_func)
1361 g_return_if_fail (G_IS_TASK (task));
1363 g_object_ref (task);
1365 task->synchronous = TRUE;
1366 g_task_start_task_thread (task, task_func);
1368 while (!task->thread_complete)
1369 g_cond_wait (&task->cond, &task->lock);
1371 g_mutex_unlock (&task->lock);
1372 g_object_unref (task);
1376 * g_task_attach_source:
1378 * @source: the source to attach
1379 * @callback: the callback to invoke when @source triggers
1381 * A utility function for dealing with async operations where you need
1382 * to wait for a #GSource to trigger. Attaches @source to @task's
1383 * #GMainContext with @task's <link
1384 * linkend="io-priority">priority</link>, and sets @source's callback
1385 * to @callback, with @task as the callback's
1386 * <literal>user_data</literal>.
1388 * This takes a reference on @task until @source is destroyed.
1393 g_task_attach_source (GTask *task,
1395 GSourceFunc callback)
1397 g_source_set_callback (source, callback,
1398 g_object_ref (task), g_object_unref);
1399 g_source_set_priority (source, task->priority);
1400 g_source_attach (source, task->context);
1405 g_task_propagate_error (GTask *task,
1408 if (task->check_cancellable &&
1409 g_cancellable_set_error_if_cancelled (task->cancellable, error))
1411 else if (task->error)
1413 g_propagate_error (error, task->error);
1422 * g_task_return_pointer:
1424 * @result: (allow-none) (transfer full): the pointer result of a task
1426 * @result_destroy: (allow-none): a #GDestroyNotify function.
1428 * Sets @task's result to @result and completes the task. If @result
1429 * is not %NULL, then @result_destroy will be used to free @result if
1430 * the caller does not take ownership of it with
1431 * g_task_propagate_pointer().
1433 * "Completes the task" means that for an ordinary asynchronous task
1434 * it will either invoke the task's callback, or else queue that
1435 * callback to be invoked in the proper #GMainContext, or in the next
1436 * iteration of the current #GMainContext. For a task run via
1437 * g_task_run_in_thread() or g_task_run_in_thread_sync(), calling this
1438 * method will save @result to be returned to the caller later, but
1439 * the task will not actually be completed until the #GTaskThreadFunc
1442 * Note that since the task may be completed before returning from
1443 * g_task_return_pointer(), you cannot assume that @result is still
1444 * valid after calling this, unless you are still holding another
1450 g_task_return_pointer (GTask *task,
1452 GDestroyNotify result_destroy)
1454 g_return_if_fail (task->result_set == FALSE);
1456 task->result.pointer = result;
1457 task->result_destroy = result_destroy;
1459 g_task_return (task, G_TASK_RETURN_SUCCESS);
1463 * g_task_propagate_pointer:
1465 * @error: return location for a #GError
1467 * Gets the result of @task as a pointer, and transfers ownership
1468 * of that value to the caller.
1470 * If the task resulted in an error, or was cancelled, then this will
1471 * instead return %NULL and set @error.
1473 * Since this method transfers ownership of the return value (or
1474 * error) to the caller, you may only call it once.
1476 * Returns: (transfer full): the task result, or %NULL on error
1481 g_task_propagate_pointer (GTask *task,
1484 if (g_task_propagate_error (task, error))
1487 g_return_val_if_fail (task->result_set == TRUE, NULL);
1489 task->result_destroy = NULL;
1490 task->result_set = FALSE;
1491 return task->result.pointer;
1495 * g_task_return_int:
1497 * @result: the integer (#gssize) result of a task function.
1499 * Sets @task's result to @result and completes the task (see
1500 * g_task_return_pointer() for more discussion of exactly what this
1506 g_task_return_int (GTask *task,
1509 g_return_if_fail (task->result_set == FALSE);
1511 task->result.size = result;
1513 g_task_return (task, G_TASK_RETURN_SUCCESS);
1517 * g_task_propagate_int:
1519 * @error: return location for a #GError
1521 * Gets the result of @task as an integer (#gssize).
1523 * If the task resulted in an error, or was cancelled, then this will
1524 * instead return -1 and set @error.
1526 * Since this method transfers ownership of the return value (or
1527 * error) to the caller, you may only call it once.
1529 * Returns: the task result, or -1 on error
1534 g_task_propagate_int (GTask *task,
1537 if (g_task_propagate_error (task, error))
1540 g_return_val_if_fail (task->result_set == TRUE, -1);
1542 task->result_set = FALSE;
1543 return task->result.size;
1547 * g_task_return_boolean:
1549 * @result: the #gboolean result of a task function.
1551 * Sets @task's result to @result and completes the task (see
1552 * g_task_return_pointer() for more discussion of exactly what this
1558 g_task_return_boolean (GTask *task,
1561 g_return_if_fail (task->result_set == FALSE);
1563 task->result.boolean = result;
1565 g_task_return (task, G_TASK_RETURN_SUCCESS);
1569 * g_task_propagate_boolean:
1571 * @error: return location for a #GError
1573 * Gets the result of @task as a #gboolean.
1575 * If the task resulted in an error, or was cancelled, then this will
1576 * instead return %FALSE and set @error.
1578 * Since this method transfers ownership of the return value (or
1579 * error) to the caller, you may only call it once.
1581 * Returns: the task result, or %FALSE on error
1586 g_task_propagate_boolean (GTask *task,
1589 if (g_task_propagate_error (task, error))
1592 g_return_val_if_fail (task->result_set == TRUE, FALSE);
1594 task->result_set = FALSE;
1595 return task->result.boolean;
1599 * g_task_return_error:
1601 * @error: (transfer full): the #GError result of a task function.
1603 * Sets @task's result to @error (which @task assumes ownership of)
1604 * and completes the task (see g_task_return_pointer() for more
1605 * discussion of exactly what this means).
1607 * Note that since the task takes ownership of @error, and since the
1608 * task may be completed before returning from g_task_return_error(),
1609 * you cannot assume that @error is still valid after calling this.
1610 * Call g_error_copy() on the error if you need to keep a local copy
1613 * See also g_task_return_new_error().
1618 g_task_return_error (GTask *task,
1621 g_return_if_fail (task->result_set == FALSE);
1622 g_return_if_fail (error != NULL);
1624 task->error = error;
1626 g_task_return (task, G_TASK_RETURN_ERROR);
1630 * g_task_return_new_error:
1632 * @domain: a #GQuark.
1633 * @code: an error code.
1634 * @format: a string with format characters.
1635 * @...: a list of values to insert into @format.
1637 * Sets @task's result to a new #GError created from @domain, @code,
1638 * @format, and the remaining arguments, and completes the task (see
1639 * g_task_return_pointer() for more discussion of exactly what this
1642 * See also g_task_return_error().
1647 g_task_return_new_error (GTask *task,
1656 va_start (args, format);
1657 error = g_error_new_valist (domain, code, format, args);
1660 g_task_return_error (task, error);
1664 * g_task_return_error_if_cancelled:
1667 * Checks if @task's #GCancellable has been cancelled, and if so, sets
1668 * @task's error accordingly and completes the task (see
1669 * g_task_return_pointer() for more discussion of exactly what this
1672 * Return value: %TRUE if @task has been cancelled, %FALSE if not
1677 g_task_return_error_if_cancelled (GTask *task)
1679 GError *error = NULL;
1681 g_return_val_if_fail (task->result_set == FALSE, FALSE);
1683 if (g_cancellable_set_error_if_cancelled (task->cancellable, &error))
1685 /* We explicitly set task->error so this works even when
1686 * check-cancellable is not set.
1688 g_clear_error (&task->error);
1689 task->error = error;
1691 g_task_return (task, G_TASK_RETURN_ERROR);
1702 * Tests if @task resulted in an error.
1704 * Returns: %TRUE if the task resulted in an error, %FALSE otherwise.
1709 g_task_had_error (GTask *task)
1711 if (task->error != NULL)
1714 if (task->check_cancellable && g_cancellable_is_cancelled (task->cancellable))
1722 * @result: (type Gio.AsyncResult): A #GAsyncResult
1723 * @source_object: (allow-none) (type GObject): the source object
1724 * expected to be associated with the task
1726 * Checks that @result is a #GTask, and that @source_object is its
1727 * source object (or that @source_object is %NULL and @result has no
1728 * source object). This can be used in g_return_if_fail() checks.
1730 * Return value: %TRUE if @result and @source_object are valid, %FALSE
1736 g_task_is_valid (gpointer result,
1737 gpointer source_object)
1739 if (!G_IS_TASK (result))
1742 return G_TASK (result)->source_object == source_object;
1746 g_task_compare_priority (gconstpointer a,
1750 const GTask *ta = a;
1751 const GTask *tb = b;
1752 gboolean a_cancelled, b_cancelled;
1754 /* Tasks that are causing other tasks to block have higher
1757 if (ta->blocking_other_task && !tb->blocking_other_task)
1759 else if (tb->blocking_other_task && !ta->blocking_other_task)
1762 /* Let already-cancelled tasks finish right away */
1763 a_cancelled = (ta->check_cancellable &&
1764 g_cancellable_is_cancelled (ta->cancellable));
1765 b_cancelled = (tb->check_cancellable &&
1766 g_cancellable_is_cancelled (tb->cancellable));
1767 if (a_cancelled && !b_cancelled)
1769 else if (b_cancelled && !a_cancelled)
1772 /* Lower priority == run sooner == negative return value */
1773 return ta->priority - tb->priority;
1777 g_task_thread_pool_init (void)
1779 task_pool = g_thread_pool_new (g_task_thread_pool_thread, NULL,
1781 g_assert (task_pool != NULL);
1783 g_thread_pool_set_sort_function (task_pool, g_task_compare_priority, NULL);
1787 g_task_thread_pool_resort (void)
1789 g_thread_pool_set_sort_function (task_pool, g_task_compare_priority, NULL);
1793 g_task_class_init (GTaskClass *klass)
1795 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
1797 gobject_class->finalize = g_task_finalize;
1801 g_task_get_user_data (GAsyncResult *res)
1803 return G_TASK (res)->callback_data;
1807 g_task_is_tagged (GAsyncResult *res,
1808 gpointer source_tag)
1810 return G_TASK (res)->source_tag == source_tag;
1814 g_task_async_result_iface_init (GAsyncResultIface *iface)
1816 iface->get_user_data = g_task_get_user_data;
1817 iface->get_source_object = g_task_ref_source_object;
1818 iface->is_tagged = g_task_is_tagged;