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 * Here is an example for using GTask as a GAsyncResult:
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);
150 * <title>Chained asynchronous operations</title>
152 * #GTask also tries to simplify asynchronous operations that
153 * internally chain together several smaller asynchronous
154 * operations. g_task_get_cancellable(), g_task_get_context(), and
155 * g_task_get_priority() allow you to get back the task's
156 * #GCancellable, #GMainContext, and <link
157 * linkend="io-priority">I/O priority</link> when starting a new
158 * subtask, so you don't have to keep track of them yourself.
159 * g_task_attach_source() simplifies the case of waiting for a
160 * source to fire (automatically using the correct #GMainContext
164 * Here is an example for chained asynchronous operations:
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.
302 * Running a task in a thread:
307 * CakeFrostingType frosting;
312 * cake_data_free (CakeData *cake_data)
314 * g_free (cake_data->message);
315 * g_slice_free (CakeData, cake_data);
319 * bake_cake_thread (GTask *task,
320 * gpointer source_object,
321 * gpointer task_data,
322 * GCancellable *cancellable)
324 * Baker *self = source_object;
325 * CakeData *cake_data = task_data;
327 * GError *error = NULL;
329 * cake = bake_cake (baker, cake_data->radius, cake_data->flavor,
330 * cake_data->frosting, cake_data->message,
331 * cancellable, &error);
333 * g_task_return_pointer (task, cake, g_object_unref);
335 * g_task_return_error (task, error);
339 * baker_bake_cake_async (Baker *self,
342 * CakeFrostingType frosting,
343 * const char *message,
344 * GCancellable *cancellable,
345 * GAsyncReadyCallback callback,
346 * gpointer user_data)
348 * CakeData *cake_data;
351 * cake_data = g_slice_new (CakeData);
352 * cake_data->radius = radius;
353 * cake_data->flavor = flavor;
354 * cake_data->frosting = frosting;
355 * cake_data->message = g_strdup (message);
356 * task = g_task_new (self, cancellable, callback, user_data);
357 * g_task_set_task_data (task, cake_data, (GDestroyNotify) cake_data_free);
358 * g_task_run_in_thread (task, bake_cake_thread);
362 * baker_bake_cake_finish (Baker *self,
363 * GAsyncResult *result,
366 * g_return_val_if_fail (g_task_is_valid (result, self), NULL);
368 * return g_task_propagate_pointer (G_TASK (result), error);
374 * <title>Adding cancellability to uncancellable tasks</title>
376 * Finally, g_task_run_in_thread() and g_task_run_in_thread_sync()
377 * can be used to turn an uncancellable operation into a
378 * cancellable one. If you call g_task_set_return_on_cancel(),
379 * passing %TRUE, then if the task's #GCancellable is cancelled,
380 * it will return control back to the caller immediately, while
381 * allowing the task thread to continue running in the background
382 * (and simply discarding its result when it finally does finish).
383 * Provided that the task thread is careful about how it uses
384 * locks and other externally-visible resources, this allows you
385 * to make "GLib-friendly" asynchronous and cancellable
386 * synchronous variants of blocking APIs.
392 * bake_cake_thread (GTask *task,
393 * gpointer source_object,
394 * gpointer task_data,
395 * GCancellable *cancellable)
397 * Baker *self = source_object;
398 * CakeData *cake_data = task_data;
400 * GError *error = NULL;
402 * cake = bake_cake (baker, cake_data->radius, cake_data->flavor,
403 * cake_data->frosting, cake_data->message,
407 * g_task_return_error (task, error);
411 * /* If the task has already been cancelled, then we don't
412 * * want to add the cake to the cake cache. Likewise, we don't
413 * * want to have the task get cancelled in the middle of
414 * * updating the cache. g_task_set_return_on_cancel() will
415 * * return %TRUE here if it managed to disable return-on-cancel,
416 * * or %FALSE if the task was cancelled before it could.
418 * if (g_task_set_return_on_cancel (task, FALSE))
420 * /* If the caller cancels at this point, their
421 * * GAsyncReadyCallback won't be invoked until we return,
422 * * so we don't have to worry that this code will run at
423 * * the same time as that code does. But if there were
424 * * other functions that might look at the cake cache,
425 * * then we'd probably need a GMutex here as well.
427 * baker_add_cake_to_cache (baker, cake);
428 * g_task_return_pointer (task, cake, g_object_unref);
433 * baker_bake_cake_async (Baker *self,
436 * CakeFrostingType frosting,
437 * const char *message,
438 * GCancellable *cancellable,
439 * GAsyncReadyCallback callback,
440 * gpointer user_data)
442 * CakeData *cake_data;
445 * cake_data = g_slice_new (CakeData);
448 * task = g_task_new (self, cancellable, callback, user_data);
449 * g_task_set_task_data (task, cake_data, (GDestroyNotify) cake_data_free);
450 * g_task_set_return_on_cancel (task, TRUE);
451 * g_task_run_in_thread (task, bake_cake_thread);
455 * baker_bake_cake_sync (Baker *self,
458 * CakeFrostingType frosting,
459 * const char *message,
460 * GCancellable *cancellable,
463 * CakeData *cake_data;
467 * cake_data = g_slice_new (CakeData);
470 * task = g_task_new (self, cancellable, NULL, NULL);
471 * g_task_set_task_data (task, cake_data, (GDestroyNotify) cake_data_free);
472 * g_task_set_return_on_cancel (task, TRUE);
473 * g_task_run_in_thread_sync (task, bake_cake_thread);
475 * cake = g_task_propagate_pointer (task, error);
476 * g_object_unref (task);
483 * <title>Porting from <literal>GSimpleAsyncResult</literal></title>
485 * #GTask's API attempts to be simpler than #GSimpleAsyncResult's
490 * You can save task-specific data with g_task_set_task_data(), and
491 * retrieve it later with g_task_get_task_data(). This replaces the
492 * abuse of g_simple_async_result_set_op_res_gpointer() for the same
493 * purpose with #GSimpleAsyncResult.
496 * In addition to the task data, #GTask also keeps track of the
497 * <link linkend="io-priority">priority</link>, #GCancellable, and
498 * #GMainContext associated with the task, so tasks that consist of
499 * a chain of simpler asynchronous operations will have easy access
500 * to those values when starting each sub-task.
503 * g_task_return_error_if_cancelled() provides simplified
504 * handling for cancellation. In addition, cancellation
505 * overrides any other #GTask return value by default, like
506 * #GSimpleAsyncResult does when
507 * g_simple_async_result_set_check_cancellable() is called.
508 * (You can use g_task_set_check_cancellable() to turn off that
509 * behavior.) On the other hand, g_task_run_in_thread()
510 * guarantees that it will always run your
511 * <literal>task_func</literal>, even if the task's #GCancellable
512 * is already cancelled before the task gets a chance to run;
513 * you can start your <literal>task_func</literal> with a
514 * g_task_return_error_if_cancelled() check if you need the
518 * The "return" methods (eg, g_task_return_pointer())
519 * automatically cause the task to be "completed" as well, and
520 * there is no need to worry about the "complete" vs "complete
521 * in idle" distinction. (#GTask automatically figures out
522 * whether the task's callback can be invoked directly, or
523 * if it needs to be sent to another #GMainContext, or delayed
524 * until the next iteration of the current #GMainContext.)
527 * The "finish" functions for #GTask-based operations are generally
528 * much simpler than #GSimpleAsyncResult ones, normally consisting
529 * of only a single call to g_task_propagate_pointer() or the like.
530 * Since g_task_propagate_pointer() "steals" the return value from
531 * the #GTask, it is not necessary to juggle pointers around to
532 * prevent it from being freed twice.
535 * With #GSimpleAsyncResult, it was common to call
536 * g_simple_async_result_propagate_error() from the
537 * <literal>_finish()</literal> wrapper function, and have
538 * virtual method implementations only deal with successful
539 * returns. This behavior is deprecated, because it makes it
540 * difficult for a subclass to chain to a parent class's async
541 * methods. Instead, the wrapper function should just be a
542 * simple wrapper, and the virtual method should call an
543 * appropriate <literal>g_task_propagate_</literal> function.
544 * Note that wrapper methods can now use
545 * g_async_result_legacy_propagate_error() to do old-style
546 * #GSimpleAsyncResult error-returning behavior, and
547 * g_async_result_is_tagged() to check if a result is tagged as
548 * having come from the <literal>_async()</literal> wrapper
549 * function (for "short-circuit" results, such as when passing
550 * 0 to g_input_stream_read_async()).
559 * The opaque object representing a synchronous or asynchronous task
564 GObject parent_instance;
566 gpointer source_object;
570 GDestroyNotify task_data_destroy;
572 GMainContext *context;
573 guint64 creation_time;
575 GCancellable *cancellable;
576 gboolean check_cancellable;
578 GAsyncReadyCallback callback;
579 gpointer callback_data;
581 GTaskThreadFunc task_func;
584 gboolean return_on_cancel;
585 gboolean thread_cancelled;
586 gboolean synchronous;
587 gboolean thread_complete;
588 gboolean blocking_other_task;
596 GDestroyNotify result_destroy;
600 #define G_TASK_IS_THREADED(task) ((task)->task_func != NULL)
604 GObjectClass parent_class;
607 static void g_task_thread_pool_resort (void);
609 static void g_task_async_result_iface_init (GAsyncResultIface *iface);
610 static void g_task_thread_pool_init (void);
612 G_DEFINE_TYPE_WITH_CODE (GTask, g_task, G_TYPE_OBJECT,
613 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_RESULT,
614 g_task_async_result_iface_init);
615 g_task_thread_pool_init ();)
617 static GThreadPool *task_pool;
618 static GMutex task_pool_mutex;
619 static GPrivate task_private = G_PRIVATE_INIT (NULL);
622 g_task_init (GTask *task)
624 task->check_cancellable = TRUE;
628 g_task_finalize (GObject *object)
630 GTask *task = G_TASK (object);
632 g_clear_object (&task->source_object);
633 g_clear_object (&task->cancellable);
636 g_main_context_unref (task->context);
638 if (task->task_data_destroy)
639 task->task_data_destroy (task->task_data);
641 if (task->result_destroy && task->result.pointer)
642 task->result_destroy (task->result.pointer);
645 g_error_free (task->error);
647 if (G_TASK_IS_THREADED (task))
649 g_mutex_clear (&task->lock);
650 g_cond_clear (&task->cond);
653 G_OBJECT_CLASS (g_task_parent_class)->finalize (object);
658 * @source_object: (allow-none) (type GObject): the #GObject that owns
659 * this task, or %NULL.
660 * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore.
661 * @callback: (scope async): a #GAsyncReadyCallback.
662 * @callback_data: (closure): user data passed to @callback.
664 * Creates a #GTask acting on @source_object, which will eventually be
665 * used to invoke @callback in the current <link
666 * linkend="g-main-context-push-thread-default">thread-default main
669 * Call this in the "start" method of your asynchronous method, and
670 * pass the #GTask around throughout the asynchronous operation. You
671 * can use g_task_set_task_data() to attach task-specific data to the
672 * object, which you can retrieve later via g_task_get_task_data().
674 * By default, if @cancellable is cancelled, then the return value of
675 * the task will always be %G_IO_ERROR_CANCELLED, even if the task had
676 * already completed before the cancellation. This allows for
677 * simplified handling in cases where cancellation may imply that
678 * other objects that the task depends on have been destroyed. If you
679 * do not want this behavior, you can use
680 * g_task_set_check_cancellable() to change it.
687 g_task_new (gpointer source_object,
688 GCancellable *cancellable,
689 GAsyncReadyCallback callback,
690 gpointer callback_data)
695 task = g_object_new (G_TYPE_TASK, NULL);
696 task->source_object = source_object ? g_object_ref (source_object) : NULL;
697 task->cancellable = cancellable ? g_object_ref (cancellable) : NULL;
698 task->callback = callback;
699 task->callback_data = callback_data;
700 task->context = g_main_context_ref_thread_default ();
702 source = g_main_current_source ();
704 task->creation_time = g_source_get_time (source);
710 * g_task_report_error:
711 * @source_object: (allow-none) (type GObject): the #GObject that owns
712 * this task, or %NULL.
713 * @callback: (scope async): a #GAsyncReadyCallback.
714 * @callback_data: (closure): user data passed to @callback.
715 * @source_tag: an opaque pointer indicating the source of this task
716 * @error: (transfer full): error to report
718 * Creates a #GTask and then immediately calls g_task_return_error()
719 * on it. Use this in the wrapper function of an asynchronous method
720 * when you want to avoid even calling the virtual method. You can
721 * then use g_async_result_is_tagged() in the finish method wrapper to
722 * check if the result there is tagged as having been created by the
723 * wrapper method, and deal with it appropriately if so.
725 * See also g_task_report_new_error().
730 g_task_report_error (gpointer source_object,
731 GAsyncReadyCallback callback,
732 gpointer callback_data,
738 task = g_task_new (source_object, NULL, callback, callback_data);
739 g_task_set_source_tag (task, source_tag);
740 g_task_return_error (task, error);
741 g_object_unref (task);
745 * g_task_report_new_error:
746 * @source_object: (allow-none) (type GObject): the #GObject that owns
747 * this task, or %NULL.
748 * @callback: (scope async): a #GAsyncReadyCallback.
749 * @callback_data: (closure): user data passed to @callback.
750 * @source_tag: an opaque pointer indicating the source of this task
751 * @domain: a #GQuark.
752 * @code: an error code.
753 * @format: a string with format characters.
754 * @...: a list of values to insert into @format.
756 * Creates a #GTask and then immediately calls
757 * g_task_return_new_error() on it. Use this in the wrapper function
758 * of an asynchronous method when you want to avoid even calling the
759 * virtual method. You can then use g_async_result_is_tagged() in the
760 * finish method wrapper to check if the result there is tagged as
761 * having been created by the wrapper method, and deal with it
762 * appropriately if so.
764 * See also g_task_report_error().
769 g_task_report_new_error (gpointer source_object,
770 GAsyncReadyCallback callback,
771 gpointer callback_data,
781 va_start (ap, format);
782 error = g_error_new_valist (domain, code, format, ap);
785 g_task_report_error (source_object, callback, callback_data,
790 * g_task_set_task_data:
792 * @task_data: (allow-none): task-specific data
793 * @task_data_destroy: (allow-none): #GDestroyNotify for @task_data
795 * Sets @task's task data (freeing the existing task data, if any).
800 g_task_set_task_data (GTask *task,
802 GDestroyNotify task_data_destroy)
804 if (task->task_data_destroy)
805 task->task_data_destroy (task->task_data);
807 task->task_data = task_data;
808 task->task_data_destroy = task_data_destroy;
812 * g_task_set_priority:
814 * @priority: the <link linkend="io-priority">priority</link>
817 * Sets @task's priority. If you do not call this, it will default to
818 * %G_PRIORITY_DEFAULT.
820 * This will affect the priority of #GSources created with
821 * g_task_attach_source() and the scheduling of tasks run in threads,
822 * and can also be explicitly retrieved later via
823 * g_task_get_priority().
828 g_task_set_priority (GTask *task,
831 task->priority = priority;
835 * g_task_set_check_cancellable:
837 * @check_cancellable: whether #GTask will check the state of
838 * its #GCancellable for you.
840 * Sets or clears @task's check-cancellable flag. If this is %TRUE
841 * (the default), then g_task_propagate_pointer(), etc, and
842 * g_task_had_error() will check the task's #GCancellable first, and
843 * if it has been cancelled, then they will consider the task to have
844 * returned an "Operation was cancelled" error
845 * (%G_IO_ERROR_CANCELLED), regardless of any other error or return
846 * value the task may have had.
848 * If @check_cancellable is %FALSE, then the #GTask will not check the
849 * cancellable itself, and it is up to @task's owner to do this (eg,
850 * via g_task_return_error_if_cancelled()).
852 * If you are using g_task_set_return_on_cancel() as well, then
853 * you must leave check-cancellable set %TRUE.
858 g_task_set_check_cancellable (GTask *task,
859 gboolean check_cancellable)
861 g_return_if_fail (check_cancellable || !task->return_on_cancel);
863 task->check_cancellable = check_cancellable;
866 static void g_task_thread_complete (GTask *task);
869 * g_task_set_return_on_cancel:
871 * @return_on_cancel: whether the task returns automatically when
874 * Sets or clears @task's return-on-cancel flag. This is only
875 * meaningful for tasks run via g_task_run_in_thread() or
876 * g_task_run_in_thread_sync().
878 * If @return_on_cancel is %TRUE, then cancelling @task's
879 * #GCancellable will immediately cause it to return, as though the
880 * task's #GTaskThreadFunc had called
881 * g_task_return_error_if_cancelled() and then returned.
883 * This allows you to create a cancellable wrapper around an
884 * uninterruptable function. The #GTaskThreadFunc just needs to be
885 * careful that it does not modify any externally-visible state after
886 * it has been cancelled. To do that, the thread should call
887 * g_task_set_return_on_cancel() again to (atomically) set
888 * return-on-cancel %FALSE before making externally-visible changes;
889 * if the task gets cancelled before the return-on-cancel flag could
890 * be changed, g_task_set_return_on_cancel() will indicate this by
893 * You can disable and re-enable this flag multiple times if you wish.
894 * If the task's #GCancellable is cancelled while return-on-cancel is
895 * %FALSE, then calling g_task_set_return_on_cancel() to set it %TRUE
896 * again will cause the task to be cancelled at that point.
898 * If the task's #GCancellable is already cancelled before you call
899 * g_task_run_in_thread()/g_task_run_in_thread_sync(), then the
900 * #GTaskThreadFunc will still be run (for consistency), but the task
901 * will also be completed right away.
903 * Returns: %TRUE if @task's return-on-cancel flag was changed to
904 * match @return_on_cancel. %FALSE if @task has already been
910 g_task_set_return_on_cancel (GTask *task,
911 gboolean return_on_cancel)
913 g_return_val_if_fail (task->check_cancellable || !return_on_cancel, FALSE);
915 if (!G_TASK_IS_THREADED (task))
917 task->return_on_cancel = return_on_cancel;
921 g_mutex_lock (&task->lock);
922 if (task->thread_cancelled)
924 if (return_on_cancel && !task->return_on_cancel)
926 g_mutex_unlock (&task->lock);
927 g_task_thread_complete (task);
930 g_mutex_unlock (&task->lock);
933 task->return_on_cancel = return_on_cancel;
934 g_mutex_unlock (&task->lock);
940 * g_task_set_source_tag:
942 * @source_tag: an opaque pointer indicating the source of this task
944 * Sets @task's source tag. You can use this to tag a task return
945 * value with a particular pointer (usually a pointer to the function
946 * doing the tagging) and then later check it using
947 * g_task_get_source_tag() (or g_async_result_is_tagged()) in the
948 * task's "finish" function, to figure out if the response came from a
954 g_task_set_source_tag (GTask *task,
957 task->source_tag = source_tag;
961 * g_task_get_source_object:
964 * Gets the source object from @task. Like
965 * g_async_result_get_source_object(), but does not ref the object.
967 * Returns: (transfer none) (type GObject): @task's source object, or %NULL
972 g_task_get_source_object (GTask *task)
974 return task->source_object;
978 g_task_ref_source_object (GAsyncResult *res)
980 GTask *task = G_TASK (res);
982 if (task->source_object)
983 return g_object_ref (task->source_object);
989 * g_task_get_task_data:
992 * Gets @task's <literal>task_data</literal>.
994 * Returns: (transfer none): @task's <literal>task_data</literal>.
999 g_task_get_task_data (GTask *task)
1001 return task->task_data;
1005 * g_task_get_priority:
1008 * Gets @task's priority
1010 * Returns: @task's priority
1015 g_task_get_priority (GTask *task)
1017 return task->priority;
1021 * g_task_get_context:
1024 * Gets the #GMainContext that @task will return its result in (that
1025 * is, the context that was the <link
1026 * linkend="g-main-context-push-thread-default">thread-default main
1027 * context</link> at the point when @task was created).
1029 * This will always return a non-%NULL value, even if the task's
1030 * context is the default #GMainContext.
1032 * Returns: (transfer none): @task's #GMainContext
1037 g_task_get_context (GTask *task)
1039 return task->context;
1043 * g_task_get_cancellable:
1046 * Gets @task's #GCancellable
1048 * Returns: (transfer none): @task's #GCancellable
1053 g_task_get_cancellable (GTask *task)
1055 return task->cancellable;
1059 * g_task_get_check_cancellable:
1062 * Gets @task's check-cancellable flag. See
1063 * g_task_set_check_cancellable() for more details.
1068 g_task_get_check_cancellable (GTask *task)
1070 return task->check_cancellable;
1074 * g_task_get_return_on_cancel:
1077 * Gets @task's return-on-cancel flag. See
1078 * g_task_set_return_on_cancel() for more details.
1083 g_task_get_return_on_cancel (GTask *task)
1085 return task->return_on_cancel;
1089 * g_task_get_source_tag:
1092 * Gets @task's source tag. See g_task_set_source_tag().
1094 * Return value: (transfer none): @task's source tag
1099 g_task_get_source_tag (GTask *task)
1101 return task->source_tag;
1106 g_task_return_now (GTask *task)
1108 g_main_context_push_thread_default (task->context);
1109 task->callback (task->source_object,
1110 G_ASYNC_RESULT (task),
1111 task->callback_data);
1112 g_main_context_pop_thread_default (task->context);
1116 complete_in_idle_cb (gpointer task)
1118 g_task_return_now (task);
1119 g_object_unref (task);
1124 G_TASK_RETURN_SUCCESS,
1125 G_TASK_RETURN_ERROR,
1126 G_TASK_RETURN_FROM_THREAD
1130 g_task_return (GTask *task,
1131 GTaskReturnType type)
1135 if (type == G_TASK_RETURN_SUCCESS)
1136 task->result_set = TRUE;
1138 if (task->synchronous || !task->callback)
1141 /* Normally we want to invoke the task's callback when its return
1142 * value is set. But if the task is running in a thread, then we
1143 * want to wait until after the task_func returns, to simplify
1144 * locking/refcounting/etc.
1146 if (G_TASK_IS_THREADED (task) && type != G_TASK_RETURN_FROM_THREAD)
1149 g_object_ref (task);
1151 /* See if we can complete the task immediately. First, we have to be
1152 * running inside the task's thread/GMainContext.
1154 source = g_main_current_source ();
1155 if (source && g_source_get_context (source) == task->context)
1157 /* Second, we can only complete immediately if this is not the
1158 * same iteration of the main loop that the task was created in.
1160 if (g_source_get_time (source) > task->creation_time)
1162 g_task_return_now (task);
1163 g_object_unref (task);
1168 /* Otherwise, complete in the next iteration */
1169 source = g_idle_source_new ();
1170 g_task_attach_source (task, source, complete_in_idle_cb);
1171 g_source_unref (source);
1178 * @source_object: (type GObject): @task's source object
1179 * @task_data: @task's task data
1180 * @cancellable: @task's #GCancellable, or %NULL
1182 * The prototype for a task function to be run in a thread via
1183 * g_task_run_in_thread() or g_task_run_in_thread_sync().
1185 * If the return-on-cancel flag is set on @task, and @cancellable gets
1186 * cancelled, then the #GTask will be completed immediately (as though
1187 * g_task_return_error_if_cancelled() had been called), without
1188 * waiting for the task function to complete. However, the task
1189 * function will continue running in its thread in the background. The
1190 * function therefore needs to be careful about how it uses
1191 * externally-visible state in this case. See
1192 * g_task_set_return_on_cancel() for more details.
1194 * Other than in that case, @task will be completed when the
1195 * #GTaskThreadFunc returns, not when it calls a
1196 * <literal>g_task_return_</literal> function.
1201 static void task_thread_cancelled (GCancellable *cancellable,
1202 gpointer user_data);
1205 g_task_thread_complete (GTask *task)
1207 g_mutex_lock (&task->lock);
1208 if (task->thread_complete)
1210 /* The task belatedly completed after having been cancelled
1211 * (or was cancelled in the midst of being completed).
1213 g_mutex_unlock (&task->lock);
1217 task->thread_complete = TRUE;
1219 if (task->blocking_other_task)
1221 g_mutex_lock (&task_pool_mutex);
1222 g_thread_pool_set_max_threads (task_pool,
1223 g_thread_pool_get_max_threads (task_pool) - 1,
1225 g_mutex_unlock (&task_pool_mutex);
1227 g_mutex_unlock (&task->lock);
1229 if (task->cancellable)
1230 g_signal_handlers_disconnect_by_func (task->cancellable, task_thread_cancelled, task);
1232 if (task->synchronous)
1233 g_cond_signal (&task->cond);
1235 g_task_return (task, G_TASK_RETURN_FROM_THREAD);
1239 g_task_thread_pool_thread (gpointer thread_data,
1242 GTask *task = thread_data;
1244 g_private_set (&task_private, task);
1246 task->task_func (task, task->source_object, task->task_data,
1248 g_task_thread_complete (task);
1250 g_private_set (&task_private, NULL);
1251 g_object_unref (task);
1255 task_thread_cancelled (GCancellable *cancellable,
1258 GTask *task = user_data;
1260 g_task_thread_pool_resort ();
1262 g_mutex_lock (&task->lock);
1263 task->thread_cancelled = TRUE;
1265 if (!task->return_on_cancel)
1267 g_mutex_unlock (&task->lock);
1271 /* We don't actually set task->error; g_task_return_error() doesn't
1272 * use a lock, and g_task_propagate_error() will call
1273 * g_cancellable_set_error_if_cancelled() anyway.
1275 g_mutex_unlock (&task->lock);
1276 g_task_thread_complete (task);
1280 task_thread_cancelled_disconnect_notify (gpointer task,
1283 g_object_unref (task);
1287 g_task_start_task_thread (GTask *task,
1288 GTaskThreadFunc task_func)
1290 g_mutex_init (&task->lock);
1291 g_cond_init (&task->cond);
1293 g_mutex_lock (&task->lock);
1295 task->task_func = task_func;
1297 if (task->cancellable)
1299 if (task->return_on_cancel &&
1300 g_cancellable_set_error_if_cancelled (task->cancellable,
1303 task->thread_cancelled = task->thread_complete = TRUE;
1304 g_thread_pool_push (task_pool, g_object_ref (task), NULL);
1308 g_signal_connect_data (task->cancellable, "cancelled",
1309 G_CALLBACK (task_thread_cancelled),
1310 g_object_ref (task),
1311 task_thread_cancelled_disconnect_notify, 0);
1314 g_thread_pool_push (task_pool, g_object_ref (task), &task->error);
1316 task->thread_complete = TRUE;
1317 else if (g_private_get (&task_private))
1319 /* This thread is being spawned from another GTask thread, so
1320 * bump up max-threads so we don't starve.
1322 g_mutex_lock (&task_pool_mutex);
1323 if (g_thread_pool_set_max_threads (task_pool,
1324 g_thread_pool_get_max_threads (task_pool) + 1,
1326 task->blocking_other_task = TRUE;
1327 g_mutex_unlock (&task_pool_mutex);
1332 * g_task_run_in_thread:
1334 * @task_func: a #GTaskThreadFunc
1336 * Runs @task_func in another thread. When @task_func returns, @task's
1337 * #GAsyncReadyCallback will be invoked in @task's #GMainContext.
1339 * This takes a ref on @task until the task completes.
1341 * See #GTaskThreadFunc for more details about how @task_func is handled.
1346 g_task_run_in_thread (GTask *task,
1347 GTaskThreadFunc task_func)
1349 g_return_if_fail (G_IS_TASK (task));
1351 g_object_ref (task);
1352 g_task_start_task_thread (task, task_func);
1354 /* The task may already be cancelled, or g_thread_pool_push() may
1357 if (task->thread_complete)
1359 g_mutex_unlock (&task->lock);
1360 g_task_return (task, G_TASK_RETURN_FROM_THREAD);
1363 g_mutex_unlock (&task->lock);
1365 g_object_unref (task);
1369 * g_task_run_in_thread_sync:
1371 * @task_func: a #GTaskThreadFunc
1373 * Runs @task_func in another thread, and waits for it to return or be
1374 * cancelled. You can use g_task_propagate_pointer(), etc, afterward
1375 * to get the result of @task_func.
1377 * See #GTaskThreadFunc for more details about how @task_func is handled.
1379 * Normally this is used with tasks created with a %NULL
1380 * <literal>callback</literal>, but note that even if the task does
1381 * have a callback, it will not be invoked when @task_func returns.
1386 g_task_run_in_thread_sync (GTask *task,
1387 GTaskThreadFunc task_func)
1389 g_return_if_fail (G_IS_TASK (task));
1391 g_object_ref (task);
1393 task->synchronous = TRUE;
1394 g_task_start_task_thread (task, task_func);
1396 while (!task->thread_complete)
1397 g_cond_wait (&task->cond, &task->lock);
1399 g_mutex_unlock (&task->lock);
1400 g_object_unref (task);
1404 * g_task_attach_source:
1406 * @source: the source to attach
1407 * @callback: the callback to invoke when @source triggers
1409 * A utility function for dealing with async operations where you need
1410 * to wait for a #GSource to trigger. Attaches @source to @task's
1411 * #GMainContext with @task's <link
1412 * linkend="io-priority">priority</link>, and sets @source's callback
1413 * to @callback, with @task as the callback's
1414 * <literal>user_data</literal>.
1416 * This takes a reference on @task until @source is destroyed.
1421 g_task_attach_source (GTask *task,
1423 GSourceFunc callback)
1425 g_source_set_callback (source, callback,
1426 g_object_ref (task), g_object_unref);
1427 g_source_set_priority (source, task->priority);
1428 g_source_attach (source, task->context);
1433 g_task_propagate_error (GTask *task,
1436 if (task->check_cancellable &&
1437 g_cancellable_set_error_if_cancelled (task->cancellable, error))
1439 else if (task->error)
1441 g_propagate_error (error, task->error);
1450 * g_task_return_pointer:
1452 * @result: (allow-none) (transfer full): the pointer result of a task
1454 * @result_destroy: (allow-none): a #GDestroyNotify function.
1456 * Sets @task's result to @result and completes the task. If @result
1457 * is not %NULL, then @result_destroy will be used to free @result if
1458 * the caller does not take ownership of it with
1459 * g_task_propagate_pointer().
1461 * "Completes the task" means that for an ordinary asynchronous task
1462 * it will either invoke the task's callback, or else queue that
1463 * callback to be invoked in the proper #GMainContext, or in the next
1464 * iteration of the current #GMainContext. For a task run via
1465 * g_task_run_in_thread() or g_task_run_in_thread_sync(), calling this
1466 * method will save @result to be returned to the caller later, but
1467 * the task will not actually be completed until the #GTaskThreadFunc
1470 * Note that since the task may be completed before returning from
1471 * g_task_return_pointer(), you cannot assume that @result is still
1472 * valid after calling this, unless you are still holding another
1478 g_task_return_pointer (GTask *task,
1480 GDestroyNotify result_destroy)
1482 g_return_if_fail (task->result_set == FALSE);
1484 task->result.pointer = result;
1485 task->result_destroy = result_destroy;
1487 g_task_return (task, G_TASK_RETURN_SUCCESS);
1491 * g_task_propagate_pointer:
1493 * @error: return location for a #GError
1495 * Gets the result of @task as a pointer, and transfers ownership
1496 * of that value to the caller.
1498 * If the task resulted in an error, or was cancelled, then this will
1499 * instead return %NULL and set @error.
1501 * Since this method transfers ownership of the return value (or
1502 * error) to the caller, you may only call it once.
1504 * Returns: (transfer full): the task result, or %NULL on error
1509 g_task_propagate_pointer (GTask *task,
1512 if (g_task_propagate_error (task, error))
1515 g_return_val_if_fail (task->result_set == TRUE, NULL);
1517 task->result_destroy = NULL;
1518 task->result_set = FALSE;
1519 return task->result.pointer;
1523 * g_task_return_int:
1525 * @result: the integer (#gssize) result of a task function.
1527 * Sets @task's result to @result and completes the task (see
1528 * g_task_return_pointer() for more discussion of exactly what this
1534 g_task_return_int (GTask *task,
1537 g_return_if_fail (task->result_set == FALSE);
1539 task->result.size = result;
1541 g_task_return (task, G_TASK_RETURN_SUCCESS);
1545 * g_task_propagate_int:
1547 * @error: return location for a #GError
1549 * Gets the result of @task as an integer (#gssize).
1551 * If the task resulted in an error, or was cancelled, then this will
1552 * instead return -1 and set @error.
1554 * Since this method transfers ownership of the return value (or
1555 * error) to the caller, you may only call it once.
1557 * Returns: the task result, or -1 on error
1562 g_task_propagate_int (GTask *task,
1565 if (g_task_propagate_error (task, error))
1568 g_return_val_if_fail (task->result_set == TRUE, -1);
1570 task->result_set = FALSE;
1571 return task->result.size;
1575 * g_task_return_boolean:
1577 * @result: the #gboolean result of a task function.
1579 * Sets @task's result to @result and completes the task (see
1580 * g_task_return_pointer() for more discussion of exactly what this
1586 g_task_return_boolean (GTask *task,
1589 g_return_if_fail (task->result_set == FALSE);
1591 task->result.boolean = result;
1593 g_task_return (task, G_TASK_RETURN_SUCCESS);
1597 * g_task_propagate_boolean:
1599 * @error: return location for a #GError
1601 * Gets the result of @task as a #gboolean.
1603 * If the task resulted in an error, or was cancelled, then this will
1604 * instead return %FALSE and set @error.
1606 * Since this method transfers ownership of the return value (or
1607 * error) to the caller, you may only call it once.
1609 * Returns: the task result, or %FALSE on error
1614 g_task_propagate_boolean (GTask *task,
1617 if (g_task_propagate_error (task, error))
1620 g_return_val_if_fail (task->result_set == TRUE, FALSE);
1622 task->result_set = FALSE;
1623 return task->result.boolean;
1627 * g_task_return_error:
1629 * @error: (transfer full): the #GError result of a task function.
1631 * Sets @task's result to @error (which @task assumes ownership of)
1632 * and completes the task (see g_task_return_pointer() for more
1633 * discussion of exactly what this means).
1635 * Note that since the task takes ownership of @error, and since the
1636 * task may be completed before returning from g_task_return_error(),
1637 * you cannot assume that @error is still valid after calling this.
1638 * Call g_error_copy() on the error if you need to keep a local copy
1641 * See also g_task_return_new_error().
1646 g_task_return_error (GTask *task,
1649 g_return_if_fail (task->result_set == FALSE);
1650 g_return_if_fail (error != NULL);
1652 task->error = error;
1654 g_task_return (task, G_TASK_RETURN_ERROR);
1658 * g_task_return_new_error:
1660 * @domain: a #GQuark.
1661 * @code: an error code.
1662 * @format: a string with format characters.
1663 * @...: a list of values to insert into @format.
1665 * Sets @task's result to a new #GError created from @domain, @code,
1666 * @format, and the remaining arguments, and completes the task (see
1667 * g_task_return_pointer() for more discussion of exactly what this
1670 * See also g_task_return_error().
1675 g_task_return_new_error (GTask *task,
1684 va_start (args, format);
1685 error = g_error_new_valist (domain, code, format, args);
1688 g_task_return_error (task, error);
1692 * g_task_return_error_if_cancelled:
1695 * Checks if @task's #GCancellable has been cancelled, and if so, sets
1696 * @task's error accordingly and completes the task (see
1697 * g_task_return_pointer() for more discussion of exactly what this
1700 * Return value: %TRUE if @task has been cancelled, %FALSE if not
1705 g_task_return_error_if_cancelled (GTask *task)
1707 GError *error = NULL;
1709 g_return_val_if_fail (task->result_set == FALSE, FALSE);
1711 if (g_cancellable_set_error_if_cancelled (task->cancellable, &error))
1713 /* We explicitly set task->error so this works even when
1714 * check-cancellable is not set.
1716 g_clear_error (&task->error);
1717 task->error = error;
1719 g_task_return (task, G_TASK_RETURN_ERROR);
1730 * Tests if @task resulted in an error.
1732 * Returns: %TRUE if the task resulted in an error, %FALSE otherwise.
1737 g_task_had_error (GTask *task)
1739 if (task->error != NULL)
1742 if (task->check_cancellable && g_cancellable_is_cancelled (task->cancellable))
1750 * @result: (type Gio.AsyncResult): A #GAsyncResult
1751 * @source_object: (allow-none) (type GObject): the source object
1752 * expected to be associated with the task
1754 * Checks that @result is a #GTask, and that @source_object is its
1755 * source object (or that @source_object is %NULL and @result has no
1756 * source object). This can be used in g_return_if_fail() checks.
1758 * Return value: %TRUE if @result and @source_object are valid, %FALSE
1764 g_task_is_valid (gpointer result,
1765 gpointer source_object)
1767 if (!G_IS_TASK (result))
1770 return G_TASK (result)->source_object == source_object;
1774 g_task_compare_priority (gconstpointer a,
1778 const GTask *ta = a;
1779 const GTask *tb = b;
1780 gboolean a_cancelled, b_cancelled;
1782 /* Tasks that are causing other tasks to block have higher
1785 if (ta->blocking_other_task && !tb->blocking_other_task)
1787 else if (tb->blocking_other_task && !ta->blocking_other_task)
1790 /* Let already-cancelled tasks finish right away */
1791 a_cancelled = (ta->check_cancellable &&
1792 g_cancellable_is_cancelled (ta->cancellable));
1793 b_cancelled = (tb->check_cancellable &&
1794 g_cancellable_is_cancelled (tb->cancellable));
1795 if (a_cancelled && !b_cancelled)
1797 else if (b_cancelled && !a_cancelled)
1800 /* Lower priority == run sooner == negative return value */
1801 return ta->priority - tb->priority;
1805 g_task_thread_pool_init (void)
1807 task_pool = g_thread_pool_new (g_task_thread_pool_thread, NULL,
1809 g_assert (task_pool != NULL);
1811 g_thread_pool_set_sort_function (task_pool, g_task_compare_priority, NULL);
1815 g_task_thread_pool_resort (void)
1817 g_thread_pool_set_sort_function (task_pool, g_task_compare_priority, NULL);
1821 g_task_class_init (GTaskClass *klass)
1823 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
1825 gobject_class->finalize = g_task_finalize;
1829 g_task_get_user_data (GAsyncResult *res)
1831 return G_TASK (res)->callback_data;
1835 g_task_is_tagged (GAsyncResult *res,
1836 gpointer source_tag)
1838 return G_TASK (res)->source_tag == source_tag;
1842 g_task_async_result_iface_init (GAsyncResultIface *iface)
1844 iface->get_user_data = g_task_get_user_data;
1845 iface->get_source_object = g_task_ref_source_object;
1846 iface->is_tagged = g_task_is_tagged;