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
34 * A #GTask represents and manages a cancellable "task".
37 * <title>Asynchronous operations</title>
39 * The most common usage of #GTask is as a #GAsyncResult, to
40 * manage data during an asynchronous operation. You call
41 * g_task_new() in the "start" method, followed by
42 * g_task_set_task_data() and the like if you need to keep some
43 * additional data associated with the task, and then pass the
44 * task object around through your asynchronous operation.
45 * Eventually, you will call a method such as
46 * g_task_return_pointer() or g_task_return_error(), which will
47 * save the value you give it and then invoke the task's callback
48 * function (waiting until the next iteration of the main
49 * loop first, if necessary). The caller will pass the #GTask back
50 * to the operation's finish function (as a #GAsyncResult), and
51 * you can use g_task_propagate_pointer() or the like to extract
54 * <example id="gtask-async"><title>GTask as a GAsyncResult</title>
57 * CakeFrostingType frosting;
62 * decoration_data_free (DecorationData *decoration)
64 * g_free (decoration->message);
65 * g_slice_free (DecorationData, decoration);
69 * baked_cb (Cake *cake,
72 * GTask *task = user_data;
73 * DecorationData *decoration = g_task_get_task_data (task);
74 * GError *error = NULL;
78 * g_task_return_new_error (task, BAKER_ERROR, BAKER_ERROR_NO_FLOUR,
79 * "Go to the supermarket");
80 * g_object_unref (task);
84 * if (!cake_decorate (cake, decoration->frosting, decoration->message, &error))
86 * g_object_unref (cake);
87 * /* g_task_return_error() takes ownership of error */
88 * g_task_return_error (task, error);
89 * g_object_unref (task);
93 * g_task_return_pointer (task, cake, g_object_unref);
94 * g_object_unref (task);
98 * baker_bake_cake_async (Baker *self,
101 * CakeFrostingType frosting,
102 * const char *message,
103 * GCancellable *cancellable,
104 * GAsyncReadyCallback callback,
105 * gpointer user_data)
108 * DecorationData *decoration;
111 * task = g_task_new (self, cancellable, callback, user_data);
114 * g_task_return_new_error (task, BAKER_ERROR, BAKER_ERROR_TOO_SMALL,
115 * "%ucm radius cakes are silly",
117 * g_object_unref (task);
121 * cake = _baker_get_cached_cake (self, radius, flavor, frosting, message);
124 * /* _baker_get_cached_cake() returns a reffed cake */
125 * g_task_return_pointer (task, cake, g_object_unref);
126 * g_object_unref (task);
130 * decoration = g_slice_new (DecorationData);
131 * decoration->frosting = frosting;
132 * decoration->message = g_strdup (message);
133 * g_task_set_task_data (task, decoration, (GDestroyNotify) decoration_data_free);
135 * _baker_begin_cake (self, radius, flavor, cancellable, baked_cb, task);
139 * baker_bake_cake_finish (Baker *self,
140 * GAsyncResult *result,
143 * g_return_val_if_fail (g_task_is_valid (result, self), NULL);
145 * return g_task_propagate_pointer (G_TASK (result), error);
151 * <title>Chained asynchronous operations</title>
153 * #GTask also tries to simplify asynchronous operations that
154 * internally chain together several smaller asynchronous
155 * operations. g_task_get_cancellable(), g_task_get_context(), and
156 * g_task_get_priority() allow you to get back the task's
157 * #GCancellable, #GMainContext, and <link
158 * linkend="io-priority">I/O priority</link> when starting a new
159 * subtask, so you don't have to keep track of them yourself.
160 * g_task_attach_source() simplifies the case of waiting for a
161 * source to fire (automatically using the correct #GMainContext
164 * <example id="gtask-chained"><title>Chained asynchronous operations</title>
168 * CakeFrostingType frosting;
173 * decoration_data_free (BakingData *bd)
176 * g_object_unref (bd->cake);
177 * g_free (bd->message);
178 * g_slice_free (BakingData, bd);
182 * decorated_cb (Cake *cake,
183 * GAsyncResult *result,
184 * gpointer user_data)
186 * GTask *task = user_data;
187 * GError *error = NULL;
189 * if (!cake_decorate_finish (cake, result, &error))
191 * g_object_unref (cake);
192 * g_task_return_error (task, error);
193 * g_object_unref (task);
197 * /* baking_data_free() will drop its ref on the cake, so
198 * * we have to take another here to give to the caller.
200 * g_task_return_pointer (result, g_object_ref (cake), g_object_unref);
201 * g_object_unref (task);
205 * decorator_ready (gpointer user_data)
207 * GTask *task = user_data;
208 * BakingData *bd = g_task_get_task_data (task);
210 * cake_decorate_async (bd->cake, bd->frosting, bd->message,
211 * g_task_get_cancellable (task),
212 * decorated_cb, task);
216 * baked_cb (Cake *cake,
217 * gpointer user_data)
219 * GTask *task = user_data;
220 * BakingData *bd = g_task_get_task_data (task);
221 * GError *error = NULL;
225 * g_task_return_new_error (task, BAKER_ERROR, BAKER_ERROR_NO_FLOUR,
226 * "Go to the supermarket");
227 * g_object_unref (task);
233 * /* Bail out now if the user has already cancelled */
234 * if (g_task_return_error_if_cancelled (task))
236 * g_object_unref (task);
240 * if (cake_decorator_available (cake))
241 * decorator_ready (task);
246 * source = cake_decorator_wait_source_new (cake);
247 * /* Attach @source to @task's GMainContext and have it call
248 * * decorator_ready() when it is ready.
250 * g_task_attach_source (task, source,
251 * G_CALLBACK (decorator_ready));
252 * g_source_unref (source);
257 * baker_bake_cake_async (Baker *self,
260 * CakeFrostingType frosting,
261 * const char *message,
263 * GCancellable *cancellable,
264 * GAsyncReadyCallback callback,
265 * gpointer user_data)
270 * task = g_task_new (self, cancellable, callback, user_data);
271 * g_task_set_priority (task, priority);
273 * bd = g_slice_new0 (BakingData);
274 * bd->frosting = frosting;
275 * bd->message = g_strdup (message);
276 * g_task_set_task_data (task, bd, (GDestroyNotify) baking_data_free);
278 * _baker_begin_cake (self, radius, flavor, cancellable, baked_cb, task);
282 * baker_bake_cake_finish (Baker *self,
283 * GAsyncResult *result,
286 * g_return_val_if_fail (g_task_is_valid (result, self), NULL);
288 * return g_task_propagate_pointer (G_TASK (result), error);
294 * <title>Asynchronous operations from synchronous ones</title>
296 * You can use g_task_run_in_thread() to turn a synchronous
297 * operation into an asynchronous one, by running it in a thread
298 * which will then dispatch the result back to the caller's
299 * #GMainContext when it completes.
301 * <example id="gtask-run-in-thread"><title>g_task_run_in_thread()</title>
306 * CakeFrostingType frosting;
311 * cake_data_free (CakeData *cake_data)
313 * g_free (cake_data->message);
314 * g_slice_free (CakeData, cake_data);
318 * bake_cake_thread (GTask *task,
319 * gpointer source_object,
320 * gpointer task_data,
321 * GCancellable *cancellable)
323 * Baker *self = source_object;
324 * CakeData *cake_data = task_data;
326 * GError *error = NULL;
328 * cake = bake_cake (baker, cake_data->radius, cake_data->flavor,
329 * cake_data->frosting, cake_data->message,
330 * cancellable, &error);
332 * g_task_return_pointer (task, cake, g_object_unref);
334 * g_task_return_error (task, error);
338 * baker_bake_cake_async (Baker *self,
341 * CakeFrostingType frosting,
342 * const char *message,
343 * GCancellable *cancellable,
344 * GAsyncReadyCallback callback,
345 * gpointer user_data)
347 * CakeData *cake_data;
350 * cake_data = g_slice_new (CakeData);
351 * cake_data->radius = radius;
352 * cake_data->flavor = flavor;
353 * cake_data->frosting = frosting;
354 * cake_data->message = g_strdup (message);
355 * task = g_task_new (self, cancellable, callback, user_data);
356 * g_task_set_task_data (task, cake_data, (GDestroyNotify) cake_data_free);
357 * g_task_run_in_thread (task, bake_cake_thread);
361 * baker_bake_cake_finish (Baker *self,
362 * GAsyncResult *result,
365 * g_return_val_if_fail (g_task_is_valid (result, self), NULL);
367 * return g_task_propagate_pointer (G_TASK (result), error);
373 * <title>Adding cancellability to uncancellable tasks</title>
375 * Finally, g_task_run_in_thread() and g_task_run_in_thread_sync()
376 * can be used to turn an uncancellable operation into a
377 * cancellable one. If you call g_task_set_return_on_cancel(),
378 * passing %TRUE, then if the task's #GCancellable is cancelled,
379 * it will return control back to the caller immediately, while
380 * allowing the task thread to continue running in the background
381 * (and simply discarding its result when it finally does finish).
382 * Provided that the task thread is careful about how it uses
383 * locks and other externally-visible resources, this allows you
384 * to make "GLib-friendly" asynchronous and cancellable
385 * synchronous variants of blocking APIs.
387 * <example id="gtask-cancellable"><title>g_task_set_return_on_cancel()</title>
390 * bake_cake_thread (GTask *task,
391 * gpointer source_object,
392 * gpointer task_data,
393 * GCancellable *cancellable)
395 * Baker *self = source_object;
396 * CakeData *cake_data = task_data;
398 * GError *error = NULL;
400 * cake = bake_cake (baker, cake_data->radius, cake_data->flavor,
401 * cake_data->frosting, cake_data->message,
405 * g_task_return_error (task, error);
409 * /* If the task has already been cancelled, then we don't
410 * * want to add the cake to the cake cache. Likewise, we don't
411 * * want to have the task get cancelled in the middle of
412 * * updating the cache. g_task_set_return_on_cancel() will
413 * * return %TRUE here if it managed to disable return-on-cancel,
414 * * or %FALSE if the task was cancelled before it could.
416 * if (g_task_set_return_on_cancel (task, FALSE))
418 * /* If the caller cancels at this point, their
419 * * GAsyncReadyCallback won't be invoked until we return,
420 * * so we don't have to worry that this code will run at
421 * * the same time as that code does. But if there were
422 * * other functions that might look at the cake cache,
423 * * then we'd probably need a GMutex here as well.
425 * baker_add_cake_to_cache (baker, cake);
426 * g_task_return_pointer (task, cake, g_object_unref);
431 * baker_bake_cake_async (Baker *self,
434 * CakeFrostingType frosting,
435 * const char *message,
436 * GCancellable *cancellable,
437 * GAsyncReadyCallback callback,
438 * gpointer user_data)
440 * CakeData *cake_data;
443 * cake_data = g_slice_new (CakeData);
446 * task = g_task_new (self, cancellable, callback, user_data);
447 * g_task_set_task_data (task, cake_data, (GDestroyNotify) cake_data_free);
448 * g_task_set_return_on_cancel (task, TRUE);
449 * g_task_run_in_thread (task, bake_cake_thread);
453 * baker_bake_cake_sync (Baker *self,
456 * CakeFrostingType frosting,
457 * const char *message,
458 * GCancellable *cancellable,
461 * CakeData *cake_data;
465 * cake_data = g_slice_new (CakeData);
468 * task = g_task_new (self, cancellable, NULL, NULL);
469 * g_task_set_task_data (task, cake_data, (GDestroyNotify) cake_data_free);
470 * g_task_set_return_on_cancel (task, TRUE);
471 * g_task_run_in_thread_sync (task, bake_cake_thread);
473 * cake = g_task_propagate_pointer (task, error);
474 * g_object_unref (task);
481 * <title>Porting from <literal>GSimpleAsyncResult</literal></title>
483 * #GTask's API attempts to be simpler than #GSimpleAsyncResult's
488 * You can save task-specific data with g_task_set_task_data(), and
489 * retrieve it later with g_task_get_task_data(). This replaces the
490 * abuse of g_simple_async_result_set_op_res_gpointer() for the same
491 * purpose with #GSimpleAsyncResult.
494 * In addition to the task data, #GTask also keeps track of the
495 * <link linkend="io-priority">priority</link>, #GCancellable, and
496 * #GMainContext associated with the task, so tasks that consist of
497 * a chain of simpler asynchronous operations will have easy access
498 * to those values when starting each sub-task.
501 * g_task_return_error_if_cancelled() provides simplified
502 * handling for cancellation. In addition, cancellation
503 * overrides any other #GTask return value by default, like
504 * #GSimpleAsyncResult does when
505 * g_simple_async_result_set_check_cancellable() is called.
506 * (You can use g_task_set_check_cancellable() to turn off that
507 * behavior.) On the other hand, g_task_run_in_thread()
508 * guarantees that it will always run your
509 * <literal>task_func</literal>, even if the task's #GCancellable
510 * is already cancelled before the task gets a chance to run;
511 * you can start your <literal>task_func</literal> with a
512 * g_task_return_error_if_cancelled() check if you need the
516 * The "return" methods (eg, g_task_return_pointer())
517 * automatically cause the task to be "completed" as well, and
518 * there is no need to worry about the "complete" vs "complete
519 * in idle" distinction. (#GTask automatically figures out
520 * whether the task's callback can be invoked directly, or
521 * if it needs to be sent to another #GMainContext, or delayed
522 * until the next iteration of the current #GMainContext.)
525 * The "finish" functions for #GTask-based operations are generally
526 * much simpler than #GSimpleAsyncResult ones, normally consisting
527 * of only a single call to g_task_propagate_pointer() or the like.
528 * Since g_task_propagate_pointer() "steals" the return value from
529 * the #GTask, it is not necessary to juggle pointers around to
530 * prevent it from being freed twice.
533 * With #GSimpleAsyncResult, it was common to call
534 * g_simple_async_result_propagate_error() from the
535 * <literal>_finish()</literal> wrapper function, and have
536 * virtual method implementations only deal with successful
537 * returns. This behavior is deprecated, because it makes it
538 * difficult for a subclass to chain to a parent class's async
539 * methods. Instead, the wrapper function should just be a
540 * simple wrapper, and the virtual method should call an
541 * appropriate <literal>g_task_propagate_</literal> function.
542 * Note that wrapper methods can now use
543 * g_async_result_legacy_propagate_error() to do old-style
544 * #GSimpleAsyncResult error-returning behavior, and
545 * g_async_result_is_tagged() to check if a result is tagged as
546 * having come from the <literal>_async()</literal> wrapper
547 * function (for "short-circuit" results, such as when passing
548 * 0 to g_input_stream_read_async()).
557 * The opaque object representing a synchronous or asynchronous task
562 GObject parent_instance;
564 gpointer source_object;
568 GDestroyNotify task_data_destroy;
570 GMainContext *context;
571 guint64 creation_time;
573 GCancellable *cancellable;
574 gboolean check_cancellable;
576 GAsyncReadyCallback callback;
577 gpointer callback_data;
579 GTaskThreadFunc task_func;
582 gboolean return_on_cancel;
583 gboolean thread_cancelled;
584 gboolean synchronous;
585 gboolean thread_complete;
586 gboolean blocking_other_task;
594 GDestroyNotify result_destroy;
598 #define G_TASK_IS_THREADED(task) ((task)->task_func != NULL)
602 GObjectClass parent_class;
605 static void g_task_thread_pool_resort (void);
607 static void g_task_async_result_iface_init (GAsyncResultIface *iface);
608 static void g_task_thread_pool_init (void);
610 G_DEFINE_TYPE_WITH_CODE (GTask, g_task, G_TYPE_OBJECT,
611 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_RESULT,
612 g_task_async_result_iface_init);
613 g_task_thread_pool_init ();)
615 static GThreadPool *task_pool;
616 static GMutex task_pool_mutex;
617 static GPrivate task_private = G_PRIVATE_INIT (NULL);
620 g_task_init (GTask *task)
622 task->check_cancellable = TRUE;
626 g_task_finalize (GObject *object)
628 GTask *task = G_TASK (object);
630 g_clear_object (&task->source_object);
631 g_clear_object (&task->cancellable);
634 g_main_context_unref (task->context);
636 if (task->task_data_destroy)
637 task->task_data_destroy (task->task_data);
639 if (task->result_destroy && task->result.pointer)
640 task->result_destroy (task->result.pointer);
643 g_error_free (task->error);
645 if (G_TASK_IS_THREADED (task))
647 g_mutex_clear (&task->lock);
648 g_cond_clear (&task->cond);
651 G_OBJECT_CLASS (g_task_parent_class)->finalize (object);
656 * @source_object: (allow-none) (type GObject): the #GObject that owns
657 * this task, or %NULL.
658 * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore.
659 * @callback: (scope async): a #GAsyncReadyCallback.
660 * @callback_data: (closure): user data passed to @callback.
662 * Creates a #GTask acting on @source_object, which will eventually be
663 * used to invoke @callback in the current <link
664 * linkend="g-main-context-push-thread-default">thread-default main
667 * Call this in the "start" method of your asynchronous method, and
668 * pass the #GTask around throughout the asynchronous operation. You
669 * can use g_task_set_task_data() to attach task-specific data to the
670 * object, which you can retrieve later via g_task_get_task_data().
672 * By default, if @cancellable is cancelled, then the return value of
673 * the task will always be %G_IO_ERROR_CANCELLED, even if the task had
674 * already completed before the cancellation. This allows for
675 * simplified handling in cases where cancellation may imply that
676 * other objects that the task depends on have been destroyed. If you
677 * do not want this behavior, you can use
678 * g_task_set_check_cancellable() to change it.
685 g_task_new (gpointer source_object,
686 GCancellable *cancellable,
687 GAsyncReadyCallback callback,
688 gpointer callback_data)
693 task = g_object_new (G_TYPE_TASK, NULL);
694 task->source_object = source_object ? g_object_ref (source_object) : NULL;
695 task->cancellable = cancellable ? g_object_ref (cancellable) : NULL;
696 task->callback = callback;
697 task->callback_data = callback_data;
698 task->context = g_main_context_ref_thread_default ();
700 source = g_main_current_source ();
702 task->creation_time = g_source_get_time (source);
708 * g_task_report_error:
709 * @source_object: (allow-none) (type GObject): the #GObject that owns
710 * this task, or %NULL.
711 * @callback: (scope async): a #GAsyncReadyCallback.
712 * @callback_data: (closure): user data passed to @callback.
713 * @source_tag: an opaque pointer indicating the source of this task
714 * @error: (transfer full): error to report
716 * Creates a #GTask and then immediately calls g_task_return_error()
717 * on it. Use this in the wrapper function of an asynchronous method
718 * when you want to avoid even calling the virtual method. You can
719 * then use g_async_result_is_tagged() in the finish method wrapper to
720 * check if the result there is tagged as having been created by the
721 * wrapper method, and deal with it appropriately if so.
723 * See also g_task_report_new_error().
728 g_task_report_error (gpointer source_object,
729 GAsyncReadyCallback callback,
730 gpointer callback_data,
736 task = g_task_new (source_object, NULL, callback, callback_data);
737 g_task_set_source_tag (task, source_tag);
738 g_task_return_error (task, error);
739 g_object_unref (task);
743 * g_task_report_new_error:
744 * @source_object: (allow-none) (type GObject): the #GObject that owns
745 * this task, or %NULL.
746 * @callback: (scope async): a #GAsyncReadyCallback.
747 * @callback_data: (closure): user data passed to @callback.
748 * @source_tag: an opaque pointer indicating the source of this task
749 * @domain: a #GQuark.
750 * @code: an error code.
751 * @format: a string with format characters.
752 * @...: a list of values to insert into @format.
754 * Creates a #GTask and then immediately calls
755 * g_task_return_new_error() on it. Use this in the wrapper function
756 * of an asynchronous method when you want to avoid even calling the
757 * virtual method. You can then use g_async_result_is_tagged() in the
758 * finish method wrapper to check if the result there is tagged as
759 * having been created by the wrapper method, and deal with it
760 * appropriately if so.
762 * See also g_task_report_error().
767 g_task_report_new_error (gpointer source_object,
768 GAsyncReadyCallback callback,
769 gpointer callback_data,
779 va_start (ap, format);
780 error = g_error_new_valist (domain, code, format, ap);
783 g_task_report_error (source_object, callback, callback_data,
788 * g_task_set_task_data:
790 * @task_data: (allow-none): task-specific data
791 * @task_data_destroy: (allow-none): #GDestroyNotify for @task_data
793 * Sets @task's task data (freeing the existing task data, if any).
798 g_task_set_task_data (GTask *task,
800 GDestroyNotify task_data_destroy)
802 if (task->task_data_destroy)
803 task->task_data_destroy (task->task_data);
805 task->task_data = task_data;
806 task->task_data_destroy = task_data_destroy;
810 * g_task_set_priority:
812 * @priority: the <link linkend="io-priority">priority</link>
815 * Sets @task's priority. If you do not call this, it will default to
816 * %G_PRIORITY_DEFAULT.
818 * This will affect the priority of #GSources created with
819 * g_task_attach_source() and the scheduling of tasks run in threads,
820 * and can also be explicitly retrieved later via
821 * g_task_get_priority().
826 g_task_set_priority (GTask *task,
829 task->priority = priority;
833 * g_task_set_check_cancellable:
835 * @check_cancellable: whether #GTask will check the state of
836 * its #GCancellable for you.
838 * Sets or clears @task's check-cancellable flag. If this is %TRUE
839 * (the default), then g_task_propagate_pointer(), etc, and
840 * g_task_had_error() will check the task's #GCancellable first, and
841 * if it has been cancelled, then they will consider the task to have
842 * returned an "Operation was cancelled" error
843 * (%G_IO_ERROR_CANCELLED), regardless of any other error or return
844 * value the task may have had.
846 * If @check_cancellable is %FALSE, then the #GTask will not check the
847 * cancellable itself, and it is up to @task's owner to do this (eg,
848 * via g_task_return_error_if_cancelled()).
850 * If you are using g_task_set_return_on_cancel() as well, then
851 * you must leave check-cancellable set %TRUE.
856 g_task_set_check_cancellable (GTask *task,
857 gboolean check_cancellable)
859 g_return_if_fail (check_cancellable || !task->return_on_cancel);
861 task->check_cancellable = check_cancellable;
864 static void g_task_thread_complete (GTask *task);
867 * g_task_set_return_on_cancel:
869 * @return_on_cancel: whether the task returns automatically when
872 * Sets or clears @task's return-on-cancel flag. This is only
873 * meaningful for tasks run via g_task_run_in_thread() or
874 * g_task_run_in_thread_sync().
876 * If @return_on_cancel is %TRUE, then cancelling @task's
877 * #GCancellable will immediately cause it to return, as though the
878 * task's #GTaskThreadFunc had called
879 * g_task_return_error_if_cancelled() and then returned.
881 * This allows you to create a cancellable wrapper around an
882 * uninterruptable function. The #GTaskThreadFunc just needs to be
883 * careful that it does not modify any externally-visible state after
884 * it has been cancelled. To do that, the thread should call
885 * g_task_set_return_on_cancel() again to (atomically) set
886 * return-on-cancel %FALSE before making externally-visible changes;
887 * if the task gets cancelled before the return-on-cancel flag could
888 * be changed, g_task_set_return_on_cancel() will indicate this by
891 * You can disable and re-enable this flag multiple times if you wish.
892 * If the task's #GCancellable is cancelled while return-on-cancel is
893 * %FALSE, then calling g_task_set_return_on_cancel() to set it %TRUE
894 * again will cause the task to be cancelled at that point.
896 * If the task's #GCancellable is already cancelled before you call
897 * g_task_run_in_thread()/g_task_run_in_thread_sync(), then the
898 * #GTaskThreadFunc will still be run (for consistency), but the task
899 * will also be completed right away.
901 * Returns: %TRUE if @task's return-on-cancel flag was changed to
902 * match @return_on_cancel. %FALSE if @task has already been
908 g_task_set_return_on_cancel (GTask *task,
909 gboolean return_on_cancel)
911 g_return_val_if_fail (task->check_cancellable || !return_on_cancel, FALSE);
913 if (!G_TASK_IS_THREADED (task))
915 task->return_on_cancel = return_on_cancel;
919 g_mutex_lock (&task->lock);
920 if (task->thread_cancelled)
922 if (return_on_cancel && !task->return_on_cancel)
924 g_mutex_unlock (&task->lock);
925 g_task_thread_complete (task);
928 g_mutex_unlock (&task->lock);
931 task->return_on_cancel = return_on_cancel;
932 g_mutex_unlock (&task->lock);
938 * g_task_set_source_tag:
940 * @source_tag: an opaque pointer indicating the source of this task
942 * Sets @task's source tag. You can use this to tag a task return
943 * value with a particular pointer (usually a pointer to the function
944 * doing the tagging) and then later check it using
945 * g_task_get_source_tag() (or g_async_result_is_tagged()) in the
946 * task's "finish" function, to figure out if the response came from a
952 g_task_set_source_tag (GTask *task,
955 task->source_tag = source_tag;
959 * g_task_get_source_object:
962 * Gets the source object from @task. Like
963 * g_async_result_get_source_object(), but does not ref the object.
965 * Returns: (transfer none) (type GObject): @task's source object, or %NULL
970 g_task_get_source_object (GTask *task)
972 return task->source_object;
976 g_task_ref_source_object (GAsyncResult *res)
978 GTask *task = G_TASK (res);
980 if (task->source_object)
981 return g_object_ref (task->source_object);
987 * g_task_get_task_data:
990 * Gets @task's <literal>task_data</literal>.
992 * Returns: (transfer none): @task's <literal>task_data</literal>.
997 g_task_get_task_data (GTask *task)
999 return task->task_data;
1003 * g_task_get_priority:
1006 * Gets @task's priority
1008 * Returns: @task's priority
1013 g_task_get_priority (GTask *task)
1015 return task->priority;
1019 * g_task_get_context:
1022 * Gets the #GMainContext that @task will return its result in (that
1023 * is, the context that was the <link
1024 * linkend="g-main-context-push-thread-default">thread-default main
1025 * context</link> at the point when @task was created).
1027 * This will always return a non-%NULL value, even if the task's
1028 * context is the default #GMainContext.
1030 * Returns: (transfer none): @task's #GMainContext
1035 g_task_get_context (GTask *task)
1037 return task->context;
1041 * g_task_get_cancellable:
1044 * Gets @task's #GCancellable
1046 * Returns: (transfer none): @task's #GCancellable
1051 g_task_get_cancellable (GTask *task)
1053 return task->cancellable;
1057 * g_task_get_check_cancellable:
1060 * Gets @task's check-cancellable flag. See
1061 * g_task_set_check_cancellable() for more details.
1066 g_task_get_check_cancellable (GTask *task)
1068 return task->check_cancellable;
1072 * g_task_get_return_on_cancel:
1075 * Gets @task's return-on-cancel flag. See
1076 * g_task_set_return_on_cancel() for more details.
1081 g_task_get_return_on_cancel (GTask *task)
1083 return task->return_on_cancel;
1087 * g_task_get_source_tag:
1090 * Gets @task's source tag. See g_task_set_source_tag().
1092 * Return value: (transfer none): @task's source tag
1097 g_task_get_source_tag (GTask *task)
1099 return task->source_tag;
1104 g_task_return_now (GTask *task)
1106 g_main_context_push_thread_default (task->context);
1107 task->callback (task->source_object,
1108 G_ASYNC_RESULT (task),
1109 task->callback_data);
1110 g_main_context_pop_thread_default (task->context);
1114 complete_in_idle_cb (gpointer task)
1116 g_task_return_now (task);
1117 g_object_unref (task);
1122 G_TASK_RETURN_SUCCESS,
1123 G_TASK_RETURN_ERROR,
1124 G_TASK_RETURN_FROM_THREAD
1128 g_task_return (GTask *task,
1129 GTaskReturnType type)
1133 if (type == G_TASK_RETURN_SUCCESS)
1134 task->result_set = TRUE;
1136 if (task->synchronous || !task->callback)
1139 /* Normally we want to invoke the task's callback when its return
1140 * value is set. But if the task is running in a thread, then we
1141 * want to wait until after the task_func returns, to simplify
1142 * locking/refcounting/etc.
1144 if (G_TASK_IS_THREADED (task) && type != G_TASK_RETURN_FROM_THREAD)
1147 g_object_ref (task);
1149 /* See if we can complete the task immediately. First, we have to be
1150 * running inside the task's thread/GMainContext.
1152 source = g_main_current_source ();
1153 if (source && g_source_get_context (source) == task->context)
1155 /* Second, we can only complete immediately if this is not the
1156 * same iteration of the main loop that the task was created in.
1158 if (g_source_get_time (source) > task->creation_time)
1160 g_task_return_now (task);
1161 g_object_unref (task);
1166 /* Otherwise, complete in the next iteration */
1167 source = g_idle_source_new ();
1168 g_task_attach_source (task, source, complete_in_idle_cb);
1169 g_source_unref (source);
1176 * @source_object: (type GObject): @task's source object
1177 * @task_data: @task's task data
1178 * @cancellable: @task's #GCancellable, or %NULL
1180 * The prototype for a task function to be run in a thread via
1181 * g_task_run_in_thread() or g_task_run_in_thread_sync().
1183 * If the return-on-cancel flag is set on @task, and @cancellable gets
1184 * cancelled, then the #GTask will be completed immediately (as though
1185 * g_task_return_error_if_cancelled() had been called), without
1186 * waiting for the task function to complete. However, the task
1187 * function will continue running in its thread in the background. The
1188 * function therefore needs to be careful about how it uses
1189 * externally-visible state in this case. See
1190 * g_task_set_return_on_cancel() for more details.
1192 * Other than in that case, @task will be completed when the
1193 * #GTaskThreadFunc returns, not when it calls a
1194 * <literal>g_task_return_</literal> function.
1199 static void task_thread_cancelled (GCancellable *cancellable,
1200 gpointer user_data);
1203 g_task_thread_complete (GTask *task)
1205 g_mutex_lock (&task->lock);
1206 if (task->thread_complete)
1208 /* The task belatedly completed after having been cancelled
1209 * (or was cancelled in the midst of being completed).
1211 g_mutex_unlock (&task->lock);
1215 task->thread_complete = TRUE;
1217 if (task->blocking_other_task)
1219 g_mutex_lock (&task_pool_mutex);
1220 g_thread_pool_set_max_threads (task_pool,
1221 g_thread_pool_get_max_threads (task_pool) - 1,
1223 g_mutex_unlock (&task_pool_mutex);
1225 g_mutex_unlock (&task->lock);
1227 if (task->cancellable)
1228 g_signal_handlers_disconnect_by_func (task->cancellable, task_thread_cancelled, task);
1230 if (task->synchronous)
1231 g_cond_signal (&task->cond);
1233 g_task_return (task, G_TASK_RETURN_FROM_THREAD);
1237 g_task_thread_pool_thread (gpointer thread_data,
1240 GTask *task = thread_data;
1242 g_private_set (&task_private, task);
1244 task->task_func (task, task->source_object, task->task_data,
1246 g_task_thread_complete (task);
1248 g_private_set (&task_private, NULL);
1249 g_object_unref (task);
1253 task_thread_cancelled (GCancellable *cancellable,
1256 GTask *task = user_data;
1258 g_task_thread_pool_resort ();
1260 g_mutex_lock (&task->lock);
1261 task->thread_cancelled = TRUE;
1263 if (!task->return_on_cancel)
1265 g_mutex_unlock (&task->lock);
1269 /* We don't actually set task->error; g_task_return_error() doesn't
1270 * use a lock, and g_task_propagate_error() will call
1271 * g_cancellable_set_error_if_cancelled() anyway.
1273 g_mutex_unlock (&task->lock);
1274 g_task_thread_complete (task);
1278 task_thread_cancelled_disconnect_notify (gpointer task,
1281 g_object_unref (task);
1285 g_task_start_task_thread (GTask *task,
1286 GTaskThreadFunc task_func)
1288 g_mutex_init (&task->lock);
1289 g_cond_init (&task->cond);
1291 g_mutex_lock (&task->lock);
1293 task->task_func = task_func;
1295 if (task->cancellable)
1297 if (task->return_on_cancel &&
1298 g_cancellable_set_error_if_cancelled (task->cancellable,
1301 task->thread_cancelled = task->thread_complete = TRUE;
1302 g_thread_pool_push (task_pool, g_object_ref (task), NULL);
1306 g_signal_connect_data (task->cancellable, "cancelled",
1307 G_CALLBACK (task_thread_cancelled),
1308 g_object_ref (task),
1309 task_thread_cancelled_disconnect_notify, 0);
1312 g_thread_pool_push (task_pool, g_object_ref (task), &task->error);
1314 task->thread_complete = TRUE;
1315 else if (g_private_get (&task_private))
1317 /* This thread is being spawned from another GTask thread, so
1318 * bump up max-threads so we don't starve.
1320 g_mutex_lock (&task_pool_mutex);
1321 if (g_thread_pool_set_max_threads (task_pool,
1322 g_thread_pool_get_max_threads (task_pool) + 1,
1324 task->blocking_other_task = TRUE;
1325 g_mutex_unlock (&task_pool_mutex);
1330 * g_task_run_in_thread:
1332 * @task_func: a #GTaskThreadFunc
1334 * Runs @task_func in another thread. When @task_func returns, @task's
1335 * #GAsyncReadyCallback will be invoked in @task's #GMainContext.
1337 * This takes a ref on @task until the task completes.
1339 * See #GTaskThreadFunc for more details about how @task_func is handled.
1344 g_task_run_in_thread (GTask *task,
1345 GTaskThreadFunc task_func)
1347 g_return_if_fail (G_IS_TASK (task));
1349 g_object_ref (task);
1350 g_task_start_task_thread (task, task_func);
1352 /* The task may already be cancelled, or g_thread_pool_push() may
1355 if (task->thread_complete)
1357 g_mutex_unlock (&task->lock);
1358 g_task_return (task, G_TASK_RETURN_FROM_THREAD);
1361 g_mutex_unlock (&task->lock);
1363 g_object_unref (task);
1367 * g_task_run_in_thread_sync:
1369 * @task_func: a #GTaskThreadFunc
1371 * Runs @task_func in another thread, and waits for it to return or be
1372 * cancelled. You can use g_task_propagate_pointer(), etc, afterward
1373 * to get the result of @task_func.
1375 * See #GTaskThreadFunc for more details about how @task_func is handled.
1377 * Normally this is used with tasks created with a %NULL
1378 * <literal>callback</literal>, but note that even if the task does
1379 * have a callback, it will not be invoked when @task_func returns.
1384 g_task_run_in_thread_sync (GTask *task,
1385 GTaskThreadFunc task_func)
1387 g_return_if_fail (G_IS_TASK (task));
1389 g_object_ref (task);
1391 task->synchronous = TRUE;
1392 g_task_start_task_thread (task, task_func);
1394 while (!task->thread_complete)
1395 g_cond_wait (&task->cond, &task->lock);
1397 g_mutex_unlock (&task->lock);
1398 g_object_unref (task);
1402 * g_task_attach_source:
1404 * @source: the source to attach
1405 * @callback: the callback to invoke when @source triggers
1407 * A utility function for dealing with async operations where you need
1408 * to wait for a #GSource to trigger. Attaches @source to @task's
1409 * #GMainContext with @task's <link
1410 * linkend="io-priority">priority</link>, and sets @source's callback
1411 * to @callback, with @task as the callback's
1412 * <literal>user_data</literal>.
1414 * This takes a reference on @task until @source is destroyed.
1419 g_task_attach_source (GTask *task,
1421 GSourceFunc callback)
1423 g_source_set_callback (source, callback,
1424 g_object_ref (task), g_object_unref);
1425 g_source_set_priority (source, task->priority);
1426 g_source_attach (source, task->context);
1431 g_task_propagate_error (GTask *task,
1434 if (task->check_cancellable &&
1435 g_cancellable_set_error_if_cancelled (task->cancellable, error))
1437 else if (task->error)
1439 g_propagate_error (error, task->error);
1448 * g_task_return_pointer:
1450 * @result: (allow-none) (transfer full): the pointer result of a task
1452 * @result_destroy: (allow-none): a #GDestroyNotify function.
1454 * Sets @task's result to @result and completes the task. If @result
1455 * is not %NULL, then @result_destroy will be used to free @result if
1456 * the caller does not take ownership of it with
1457 * g_task_propagate_pointer().
1459 * "Completes the task" means that for an ordinary asynchronous task
1460 * it will either invoke the task's callback, or else queue that
1461 * callback to be invoked in the proper #GMainContext, or in the next
1462 * iteration of the current #GMainContext. For a task run via
1463 * g_task_run_in_thread() or g_task_run_in_thread_sync(), calling this
1464 * method will save @result to be returned to the caller later, but
1465 * the task will not actually be completed until the #GTaskThreadFunc
1468 * Note that since the task may be completed before returning from
1469 * g_task_return_pointer(), you cannot assume that @result is still
1470 * valid after calling this, unless you are still holding another
1476 g_task_return_pointer (GTask *task,
1478 GDestroyNotify result_destroy)
1480 g_return_if_fail (task->result_set == FALSE);
1482 task->result.pointer = result;
1483 task->result_destroy = result_destroy;
1485 g_task_return (task, G_TASK_RETURN_SUCCESS);
1489 * g_task_propagate_pointer:
1491 * @error: return location for a #GError
1493 * Gets the result of @task as a pointer, and transfers ownership
1494 * of that value to the caller.
1496 * If the task resulted in an error, or was cancelled, then this will
1497 * instead return %NULL and set @error.
1499 * Since this method transfers ownership of the return value (or
1500 * error) to the caller, you may only call it once.
1502 * Returns: (transfer full): the task result, or %NULL on error
1507 g_task_propagate_pointer (GTask *task,
1510 if (g_task_propagate_error (task, error))
1513 g_return_val_if_fail (task->result_set == TRUE, NULL);
1515 task->result_destroy = NULL;
1516 task->result_set = FALSE;
1517 return task->result.pointer;
1521 * g_task_return_int:
1523 * @result: the integer (#gssize) result of a task function.
1525 * Sets @task's result to @result and completes the task (see
1526 * g_task_return_pointer() for more discussion of exactly what this
1532 g_task_return_int (GTask *task,
1535 g_return_if_fail (task->result_set == FALSE);
1537 task->result.size = result;
1539 g_task_return (task, G_TASK_RETURN_SUCCESS);
1543 * g_task_propagate_int:
1545 * @error: return location for a #GError
1547 * Gets the result of @task as an integer (#gssize).
1549 * If the task resulted in an error, or was cancelled, then this will
1550 * instead return -1 and set @error.
1552 * Since this method transfers ownership of the return value (or
1553 * error) to the caller, you may only call it once.
1555 * Returns: the task result, or -1 on error
1560 g_task_propagate_int (GTask *task,
1563 if (g_task_propagate_error (task, error))
1566 g_return_val_if_fail (task->result_set == TRUE, -1);
1568 task->result_set = FALSE;
1569 return task->result.size;
1573 * g_task_return_boolean:
1575 * @result: the #gboolean result of a task function.
1577 * Sets @task's result to @result and completes the task (see
1578 * g_task_return_pointer() for more discussion of exactly what this
1584 g_task_return_boolean (GTask *task,
1587 g_return_if_fail (task->result_set == FALSE);
1589 task->result.boolean = result;
1591 g_task_return (task, G_TASK_RETURN_SUCCESS);
1595 * g_task_propagate_boolean:
1597 * @error: return location for a #GError
1599 * Gets the result of @task as a #gboolean.
1601 * If the task resulted in an error, or was cancelled, then this will
1602 * instead return %FALSE and set @error.
1604 * Since this method transfers ownership of the return value (or
1605 * error) to the caller, you may only call it once.
1607 * Returns: the task result, or %FALSE on error
1612 g_task_propagate_boolean (GTask *task,
1615 if (g_task_propagate_error (task, error))
1618 g_return_val_if_fail (task->result_set == TRUE, FALSE);
1620 task->result_set = FALSE;
1621 return task->result.boolean;
1625 * g_task_return_error:
1627 * @error: (transfer full): the #GError result of a task function.
1629 * Sets @task's result to @error (which @task assumes ownership of)
1630 * and completes the task (see g_task_return_pointer() for more
1631 * discussion of exactly what this means).
1633 * Note that since the task takes ownership of @error, and since the
1634 * task may be completed before returning from g_task_return_error(),
1635 * you cannot assume that @error is still valid after calling this.
1636 * Call g_error_copy() on the error if you need to keep a local copy
1639 * See also g_task_return_new_error().
1644 g_task_return_error (GTask *task,
1647 g_return_if_fail (task->result_set == FALSE);
1648 g_return_if_fail (error != NULL);
1650 task->error = error;
1652 g_task_return (task, G_TASK_RETURN_ERROR);
1656 * g_task_return_new_error:
1658 * @domain: a #GQuark.
1659 * @code: an error code.
1660 * @format: a string with format characters.
1661 * @...: a list of values to insert into @format.
1663 * Sets @task's result to a new #GError created from @domain, @code,
1664 * @format, and the remaining arguments, and completes the task (see
1665 * g_task_return_pointer() for more discussion of exactly what this
1668 * See also g_task_return_error().
1673 g_task_return_new_error (GTask *task,
1682 va_start (args, format);
1683 error = g_error_new_valist (domain, code, format, args);
1686 g_task_return_error (task, error);
1690 * g_task_return_error_if_cancelled:
1693 * Checks if @task's #GCancellable has been cancelled, and if so, sets
1694 * @task's error accordingly and completes the task (see
1695 * g_task_return_pointer() for more discussion of exactly what this
1698 * Return value: %TRUE if @task has been cancelled, %FALSE if not
1703 g_task_return_error_if_cancelled (GTask *task)
1705 GError *error = NULL;
1707 g_return_val_if_fail (task->result_set == FALSE, FALSE);
1709 if (g_cancellable_set_error_if_cancelled (task->cancellable, &error))
1711 /* We explicitly set task->error so this works even when
1712 * check-cancellable is not set.
1714 g_clear_error (&task->error);
1715 task->error = error;
1717 g_task_return (task, G_TASK_RETURN_ERROR);
1728 * Tests if @task resulted in an error.
1730 * Returns: %TRUE if the task resulted in an error, %FALSE otherwise.
1735 g_task_had_error (GTask *task)
1737 if (task->error != NULL)
1740 if (task->check_cancellable && g_cancellable_is_cancelled (task->cancellable))
1748 * @result: (type Gio.AsyncResult): A #GAsyncResult
1749 * @source_object: (allow-none) (type GObject): the source object
1750 * expected to be associated with the task
1752 * Checks that @result is a #GTask, and that @source_object is its
1753 * source object (or that @source_object is %NULL and @result has no
1754 * source object). This can be used in g_return_if_fail() checks.
1756 * Return value: %TRUE if @result and @source_object are valid, %FALSE
1762 g_task_is_valid (gpointer result,
1763 gpointer source_object)
1765 if (!G_IS_TASK (result))
1768 return G_TASK (result)->source_object == source_object;
1772 g_task_compare_priority (gconstpointer a,
1776 const GTask *ta = a;
1777 const GTask *tb = b;
1778 gboolean a_cancelled, b_cancelled;
1780 /* Tasks that are causing other tasks to block have higher
1783 if (ta->blocking_other_task && !tb->blocking_other_task)
1785 else if (tb->blocking_other_task && !ta->blocking_other_task)
1788 /* Let already-cancelled tasks finish right away */
1789 a_cancelled = (ta->check_cancellable &&
1790 g_cancellable_is_cancelled (ta->cancellable));
1791 b_cancelled = (tb->check_cancellable &&
1792 g_cancellable_is_cancelled (tb->cancellable));
1793 if (a_cancelled && !b_cancelled)
1795 else if (b_cancelled && !a_cancelled)
1798 /* Lower priority == run sooner == negative return value */
1799 return ta->priority - tb->priority;
1803 g_task_thread_pool_init (void)
1805 task_pool = g_thread_pool_new (g_task_thread_pool_thread, NULL,
1807 g_assert (task_pool != NULL);
1809 g_thread_pool_set_sort_function (task_pool, g_task_compare_priority, NULL);
1813 g_task_thread_pool_resort (void)
1815 g_thread_pool_set_sort_function (task_pool, g_task_compare_priority, NULL);
1819 g_task_class_init (GTaskClass *klass)
1821 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
1823 gobject_class->finalize = g_task_finalize;
1827 g_task_get_user_data (GAsyncResult *res)
1829 return G_TASK (res)->callback_data;
1833 g_task_is_tagged (GAsyncResult *res,
1834 gpointer source_tag)
1836 return G_TASK (res)->source_tag == source_tag;
1840 g_task_async_result_iface_init (GAsyncResultIface *iface)
1842 iface->get_user_data = g_task_get_user_data;
1843 iface->get_source_object = g_task_ref_source_object;
1844 iface->is_tagged = g_task_is_tagged;