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);
293 * <title>Asynchronous operations from synchronous ones</title>
295 * You can use g_task_run_in_thread() to turn a synchronous
296 * operation into an asynchronous one, by running it in a thread
297 * which will then dispatch the result back to the caller's
298 * #GMainContext when it completes.
301 * Running a task in a thread:
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);
372 * <title>Adding cancellability to uncancellable tasks</title>
374 * Finally, g_task_run_in_thread() and g_task_run_in_thread_sync()
375 * can be used to turn an uncancellable operation into a
376 * cancellable one. If you call g_task_set_return_on_cancel(),
377 * passing %TRUE, then if the task's #GCancellable is cancelled,
378 * it will return control back to the caller immediately, while
379 * allowing the task thread to continue running in the background
380 * (and simply discarding its result when it finally does finish).
381 * Provided that the task thread is careful about how it uses
382 * locks and other externally-visible resources, this allows you
383 * to make "GLib-friendly" asynchronous and cancellable
384 * synchronous variants of blocking APIs.
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);
480 * <title>Porting from <literal>GSimpleAsyncResult</literal></title>
482 * #GTask's API attempts to be simpler than #GSimpleAsyncResult's
487 * You can save task-specific data with g_task_set_task_data(), and
488 * retrieve it later with g_task_get_task_data(). This replaces the
489 * abuse of g_simple_async_result_set_op_res_gpointer() for the same
490 * purpose with #GSimpleAsyncResult.
493 * In addition to the task data, #GTask also keeps track of the
494 * <link linkend="io-priority">priority</link>, #GCancellable, and
495 * #GMainContext associated with the task, so tasks that consist of
496 * a chain of simpler asynchronous operations will have easy access
497 * to those values when starting each sub-task.
500 * g_task_return_error_if_cancelled() provides simplified
501 * handling for cancellation. In addition, cancellation
502 * overrides any other #GTask return value by default, like
503 * #GSimpleAsyncResult does when
504 * g_simple_async_result_set_check_cancellable() is called.
505 * (You can use g_task_set_check_cancellable() to turn off that
506 * behavior.) On the other hand, g_task_run_in_thread()
507 * guarantees that it will always run your
508 * <literal>task_func</literal>, even if the task's #GCancellable
509 * is already cancelled before the task gets a chance to run;
510 * you can start your <literal>task_func</literal> with a
511 * g_task_return_error_if_cancelled() check if you need the
515 * The "return" methods (eg, g_task_return_pointer())
516 * automatically cause the task to be "completed" as well, and
517 * there is no need to worry about the "complete" vs "complete
518 * in idle" distinction. (#GTask automatically figures out
519 * whether the task's callback can be invoked directly, or
520 * if it needs to be sent to another #GMainContext, or delayed
521 * until the next iteration of the current #GMainContext.)
524 * The "finish" functions for #GTask-based operations are generally
525 * much simpler than #GSimpleAsyncResult ones, normally consisting
526 * of only a single call to g_task_propagate_pointer() or the like.
527 * Since g_task_propagate_pointer() "steals" the return value from
528 * the #GTask, it is not necessary to juggle pointers around to
529 * prevent it from being freed twice.
532 * With #GSimpleAsyncResult, it was common to call
533 * g_simple_async_result_propagate_error() from the
534 * <literal>_finish()</literal> wrapper function, and have
535 * virtual method implementations only deal with successful
536 * returns. This behavior is deprecated, because it makes it
537 * difficult for a subclass to chain to a parent class's async
538 * methods. Instead, the wrapper function should just be a
539 * simple wrapper, and the virtual method should call an
540 * appropriate <literal>g_task_propagate_</literal> function.
541 * Note that wrapper methods can now use
542 * g_async_result_legacy_propagate_error() to do old-style
543 * #GSimpleAsyncResult error-returning behavior, and
544 * g_async_result_is_tagged() to check if a result is tagged as
545 * having come from the <literal>_async()</literal> wrapper
546 * function (for "short-circuit" results, such as when passing
547 * 0 to g_input_stream_read_async()).
556 * The opaque object representing a synchronous or asynchronous task
561 GObject parent_instance;
563 gpointer source_object;
567 GDestroyNotify task_data_destroy;
569 GMainContext *context;
570 guint64 creation_time;
572 GCancellable *cancellable;
573 gboolean check_cancellable;
575 GAsyncReadyCallback callback;
576 gpointer callback_data;
578 GTaskThreadFunc task_func;
581 gboolean return_on_cancel;
582 gboolean thread_cancelled;
583 gboolean synchronous;
584 gboolean thread_complete;
585 gboolean blocking_other_task;
593 GDestroyNotify result_destroy;
597 #define G_TASK_IS_THREADED(task) ((task)->task_func != NULL)
601 GObjectClass parent_class;
604 static void g_task_thread_pool_resort (void);
606 static void g_task_async_result_iface_init (GAsyncResultIface *iface);
607 static void g_task_thread_pool_init (void);
609 G_DEFINE_TYPE_WITH_CODE (GTask, g_task, G_TYPE_OBJECT,
610 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_RESULT,
611 g_task_async_result_iface_init);
612 g_task_thread_pool_init ();)
614 static GThreadPool *task_pool;
615 static GMutex task_pool_mutex;
616 static GPrivate task_private = G_PRIVATE_INIT (NULL);
619 g_task_init (GTask *task)
621 task->check_cancellable = TRUE;
625 g_task_finalize (GObject *object)
627 GTask *task = G_TASK (object);
629 g_clear_object (&task->source_object);
630 g_clear_object (&task->cancellable);
633 g_main_context_unref (task->context);
635 if (task->task_data_destroy)
636 task->task_data_destroy (task->task_data);
638 if (task->result_destroy && task->result.pointer)
639 task->result_destroy (task->result.pointer);
642 g_error_free (task->error);
644 if (G_TASK_IS_THREADED (task))
646 g_mutex_clear (&task->lock);
647 g_cond_clear (&task->cond);
650 G_OBJECT_CLASS (g_task_parent_class)->finalize (object);
655 * @source_object: (allow-none) (type GObject): the #GObject that owns
656 * this task, or %NULL.
657 * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore.
658 * @callback: (scope async): a #GAsyncReadyCallback.
659 * @callback_data: (closure): user data passed to @callback.
661 * Creates a #GTask acting on @source_object, which will eventually be
662 * used to invoke @callback in the current <link
663 * linkend="g-main-context-push-thread-default">thread-default main
666 * Call this in the "start" method of your asynchronous method, and
667 * pass the #GTask around throughout the asynchronous operation. You
668 * can use g_task_set_task_data() to attach task-specific data to the
669 * object, which you can retrieve later via g_task_get_task_data().
671 * By default, if @cancellable is cancelled, then the return value of
672 * the task will always be %G_IO_ERROR_CANCELLED, even if the task had
673 * already completed before the cancellation. This allows for
674 * simplified handling in cases where cancellation may imply that
675 * other objects that the task depends on have been destroyed. If you
676 * do not want this behavior, you can use
677 * g_task_set_check_cancellable() to change it.
684 g_task_new (gpointer source_object,
685 GCancellable *cancellable,
686 GAsyncReadyCallback callback,
687 gpointer callback_data)
692 task = g_object_new (G_TYPE_TASK, NULL);
693 task->source_object = source_object ? g_object_ref (source_object) : NULL;
694 task->cancellable = cancellable ? g_object_ref (cancellable) : NULL;
695 task->callback = callback;
696 task->callback_data = callback_data;
697 task->context = g_main_context_ref_thread_default ();
699 source = g_main_current_source ();
701 task->creation_time = g_source_get_time (source);
707 * g_task_report_error:
708 * @source_object: (allow-none) (type GObject): the #GObject that owns
709 * this task, or %NULL.
710 * @callback: (scope async): a #GAsyncReadyCallback.
711 * @callback_data: (closure): user data passed to @callback.
712 * @source_tag: an opaque pointer indicating the source of this task
713 * @error: (transfer full): error to report
715 * Creates a #GTask and then immediately calls g_task_return_error()
716 * on it. Use this in the wrapper function of an asynchronous method
717 * when you want to avoid even calling the virtual method. You can
718 * then use g_async_result_is_tagged() in the finish method wrapper to
719 * check if the result there is tagged as having been created by the
720 * wrapper method, and deal with it appropriately if so.
722 * See also g_task_report_new_error().
727 g_task_report_error (gpointer source_object,
728 GAsyncReadyCallback callback,
729 gpointer callback_data,
735 task = g_task_new (source_object, NULL, callback, callback_data);
736 g_task_set_source_tag (task, source_tag);
737 g_task_return_error (task, error);
738 g_object_unref (task);
742 * g_task_report_new_error:
743 * @source_object: (allow-none) (type GObject): the #GObject that owns
744 * this task, or %NULL.
745 * @callback: (scope async): a #GAsyncReadyCallback.
746 * @callback_data: (closure): user data passed to @callback.
747 * @source_tag: an opaque pointer indicating the source of this task
748 * @domain: a #GQuark.
749 * @code: an error code.
750 * @format: a string with format characters.
751 * @...: a list of values to insert into @format.
753 * Creates a #GTask and then immediately calls
754 * g_task_return_new_error() on it. Use this in the wrapper function
755 * of an asynchronous method when you want to avoid even calling the
756 * virtual method. You can then use g_async_result_is_tagged() in the
757 * finish method wrapper to check if the result there is tagged as
758 * having been created by the wrapper method, and deal with it
759 * appropriately if so.
761 * See also g_task_report_error().
766 g_task_report_new_error (gpointer source_object,
767 GAsyncReadyCallback callback,
768 gpointer callback_data,
778 va_start (ap, format);
779 error = g_error_new_valist (domain, code, format, ap);
782 g_task_report_error (source_object, callback, callback_data,
787 * g_task_set_task_data:
789 * @task_data: (allow-none): task-specific data
790 * @task_data_destroy: (allow-none): #GDestroyNotify for @task_data
792 * Sets @task's task data (freeing the existing task data, if any).
797 g_task_set_task_data (GTask *task,
799 GDestroyNotify task_data_destroy)
801 if (task->task_data_destroy)
802 task->task_data_destroy (task->task_data);
804 task->task_data = task_data;
805 task->task_data_destroy = task_data_destroy;
809 * g_task_set_priority:
811 * @priority: the <link linkend="io-priority">priority</link>
814 * Sets @task's priority. If you do not call this, it will default to
815 * %G_PRIORITY_DEFAULT.
817 * This will affect the priority of #GSources created with
818 * g_task_attach_source() and the scheduling of tasks run in threads,
819 * and can also be explicitly retrieved later via
820 * g_task_get_priority().
825 g_task_set_priority (GTask *task,
828 task->priority = priority;
832 * g_task_set_check_cancellable:
834 * @check_cancellable: whether #GTask will check the state of
835 * its #GCancellable for you.
837 * Sets or clears @task's check-cancellable flag. If this is %TRUE
838 * (the default), then g_task_propagate_pointer(), etc, and
839 * g_task_had_error() will check the task's #GCancellable first, and
840 * if it has been cancelled, then they will consider the task to have
841 * returned an "Operation was cancelled" error
842 * (%G_IO_ERROR_CANCELLED), regardless of any other error or return
843 * value the task may have had.
845 * If @check_cancellable is %FALSE, then the #GTask will not check the
846 * cancellable itself, and it is up to @task's owner to do this (eg,
847 * via g_task_return_error_if_cancelled()).
849 * If you are using g_task_set_return_on_cancel() as well, then
850 * you must leave check-cancellable set %TRUE.
855 g_task_set_check_cancellable (GTask *task,
856 gboolean check_cancellable)
858 g_return_if_fail (check_cancellable || !task->return_on_cancel);
860 task->check_cancellable = check_cancellable;
863 static void g_task_thread_complete (GTask *task);
866 * g_task_set_return_on_cancel:
868 * @return_on_cancel: whether the task returns automatically when
871 * Sets or clears @task's return-on-cancel flag. This is only
872 * meaningful for tasks run via g_task_run_in_thread() or
873 * g_task_run_in_thread_sync().
875 * If @return_on_cancel is %TRUE, then cancelling @task's
876 * #GCancellable will immediately cause it to return, as though the
877 * task's #GTaskThreadFunc had called
878 * g_task_return_error_if_cancelled() and then returned.
880 * This allows you to create a cancellable wrapper around an
881 * uninterruptable function. The #GTaskThreadFunc just needs to be
882 * careful that it does not modify any externally-visible state after
883 * it has been cancelled. To do that, the thread should call
884 * g_task_set_return_on_cancel() again to (atomically) set
885 * return-on-cancel %FALSE before making externally-visible changes;
886 * if the task gets cancelled before the return-on-cancel flag could
887 * be changed, g_task_set_return_on_cancel() will indicate this by
890 * You can disable and re-enable this flag multiple times if you wish.
891 * If the task's #GCancellable is cancelled while return-on-cancel is
892 * %FALSE, then calling g_task_set_return_on_cancel() to set it %TRUE
893 * again will cause the task to be cancelled at that point.
895 * If the task's #GCancellable is already cancelled before you call
896 * g_task_run_in_thread()/g_task_run_in_thread_sync(), then the
897 * #GTaskThreadFunc will still be run (for consistency), but the task
898 * will also be completed right away.
900 * Returns: %TRUE if @task's return-on-cancel flag was changed to
901 * match @return_on_cancel. %FALSE if @task has already been
907 g_task_set_return_on_cancel (GTask *task,
908 gboolean return_on_cancel)
910 g_return_val_if_fail (task->check_cancellable || !return_on_cancel, FALSE);
912 if (!G_TASK_IS_THREADED (task))
914 task->return_on_cancel = return_on_cancel;
918 g_mutex_lock (&task->lock);
919 if (task->thread_cancelled)
921 if (return_on_cancel && !task->return_on_cancel)
923 g_mutex_unlock (&task->lock);
924 g_task_thread_complete (task);
927 g_mutex_unlock (&task->lock);
930 task->return_on_cancel = return_on_cancel;
931 g_mutex_unlock (&task->lock);
937 * g_task_set_source_tag:
939 * @source_tag: an opaque pointer indicating the source of this task
941 * Sets @task's source tag. You can use this to tag a task return
942 * value with a particular pointer (usually a pointer to the function
943 * doing the tagging) and then later check it using
944 * g_task_get_source_tag() (or g_async_result_is_tagged()) in the
945 * task's "finish" function, to figure out if the response came from a
951 g_task_set_source_tag (GTask *task,
954 task->source_tag = source_tag;
958 * g_task_get_source_object:
961 * Gets the source object from @task. Like
962 * g_async_result_get_source_object(), but does not ref the object.
964 * Returns: (transfer none) (type GObject): @task's source object, or %NULL
969 g_task_get_source_object (GTask *task)
971 return task->source_object;
975 g_task_ref_source_object (GAsyncResult *res)
977 GTask *task = G_TASK (res);
979 if (task->source_object)
980 return g_object_ref (task->source_object);
986 * g_task_get_task_data:
989 * Gets @task's <literal>task_data</literal>.
991 * Returns: (transfer none): @task's <literal>task_data</literal>.
996 g_task_get_task_data (GTask *task)
998 return task->task_data;
1002 * g_task_get_priority:
1005 * Gets @task's priority
1007 * Returns: @task's priority
1012 g_task_get_priority (GTask *task)
1014 return task->priority;
1018 * g_task_get_context:
1021 * Gets the #GMainContext that @task will return its result in (that
1022 * is, the context that was the <link
1023 * linkend="g-main-context-push-thread-default">thread-default main
1024 * context</link> at the point when @task was created).
1026 * This will always return a non-%NULL value, even if the task's
1027 * context is the default #GMainContext.
1029 * Returns: (transfer none): @task's #GMainContext
1034 g_task_get_context (GTask *task)
1036 return task->context;
1040 * g_task_get_cancellable:
1043 * Gets @task's #GCancellable
1045 * Returns: (transfer none): @task's #GCancellable
1050 g_task_get_cancellable (GTask *task)
1052 return task->cancellable;
1056 * g_task_get_check_cancellable:
1059 * Gets @task's check-cancellable flag. See
1060 * g_task_set_check_cancellable() for more details.
1065 g_task_get_check_cancellable (GTask *task)
1067 return task->check_cancellable;
1071 * g_task_get_return_on_cancel:
1074 * Gets @task's return-on-cancel flag. See
1075 * g_task_set_return_on_cancel() for more details.
1080 g_task_get_return_on_cancel (GTask *task)
1082 return task->return_on_cancel;
1086 * g_task_get_source_tag:
1089 * Gets @task's source tag. See g_task_set_source_tag().
1091 * Return value: (transfer none): @task's source tag
1096 g_task_get_source_tag (GTask *task)
1098 return task->source_tag;
1103 g_task_return_now (GTask *task)
1105 g_main_context_push_thread_default (task->context);
1106 task->callback (task->source_object,
1107 G_ASYNC_RESULT (task),
1108 task->callback_data);
1109 g_main_context_pop_thread_default (task->context);
1113 complete_in_idle_cb (gpointer task)
1115 g_task_return_now (task);
1116 g_object_unref (task);
1121 G_TASK_RETURN_SUCCESS,
1122 G_TASK_RETURN_ERROR,
1123 G_TASK_RETURN_FROM_THREAD
1127 g_task_return (GTask *task,
1128 GTaskReturnType type)
1132 if (type == G_TASK_RETURN_SUCCESS)
1133 task->result_set = TRUE;
1135 if (task->synchronous || !task->callback)
1138 /* Normally we want to invoke the task's callback when its return
1139 * value is set. But if the task is running in a thread, then we
1140 * want to wait until after the task_func returns, to simplify
1141 * locking/refcounting/etc.
1143 if (G_TASK_IS_THREADED (task) && type != G_TASK_RETURN_FROM_THREAD)
1146 g_object_ref (task);
1148 /* See if we can complete the task immediately. First, we have to be
1149 * running inside the task's thread/GMainContext.
1151 source = g_main_current_source ();
1152 if (source && g_source_get_context (source) == task->context)
1154 /* Second, we can only complete immediately if this is not the
1155 * same iteration of the main loop that the task was created in.
1157 if (g_source_get_time (source) > task->creation_time)
1159 g_task_return_now (task);
1160 g_object_unref (task);
1165 /* Otherwise, complete in the next iteration */
1166 source = g_idle_source_new ();
1167 g_task_attach_source (task, source, complete_in_idle_cb);
1168 g_source_unref (source);
1175 * @source_object: (type GObject): @task's source object
1176 * @task_data: @task's task data
1177 * @cancellable: @task's #GCancellable, or %NULL
1179 * The prototype for a task function to be run in a thread via
1180 * g_task_run_in_thread() or g_task_run_in_thread_sync().
1182 * If the return-on-cancel flag is set on @task, and @cancellable gets
1183 * cancelled, then the #GTask will be completed immediately (as though
1184 * g_task_return_error_if_cancelled() had been called), without
1185 * waiting for the task function to complete. However, the task
1186 * function will continue running in its thread in the background. The
1187 * function therefore needs to be careful about how it uses
1188 * externally-visible state in this case. See
1189 * g_task_set_return_on_cancel() for more details.
1191 * Other than in that case, @task will be completed when the
1192 * #GTaskThreadFunc returns, not when it calls a
1193 * <literal>g_task_return_</literal> function.
1198 static void task_thread_cancelled (GCancellable *cancellable,
1199 gpointer user_data);
1202 g_task_thread_complete (GTask *task)
1204 g_mutex_lock (&task->lock);
1205 if (task->thread_complete)
1207 /* The task belatedly completed after having been cancelled
1208 * (or was cancelled in the midst of being completed).
1210 g_mutex_unlock (&task->lock);
1214 task->thread_complete = TRUE;
1216 if (task->blocking_other_task)
1218 g_mutex_lock (&task_pool_mutex);
1219 g_thread_pool_set_max_threads (task_pool,
1220 g_thread_pool_get_max_threads (task_pool) - 1,
1222 g_mutex_unlock (&task_pool_mutex);
1224 g_mutex_unlock (&task->lock);
1226 if (task->cancellable)
1227 g_signal_handlers_disconnect_by_func (task->cancellable, task_thread_cancelled, task);
1229 if (task->synchronous)
1230 g_cond_signal (&task->cond);
1232 g_task_return (task, G_TASK_RETURN_FROM_THREAD);
1236 g_task_thread_pool_thread (gpointer thread_data,
1239 GTask *task = thread_data;
1241 g_private_set (&task_private, task);
1243 task->task_func (task, task->source_object, task->task_data,
1245 g_task_thread_complete (task);
1247 g_private_set (&task_private, NULL);
1248 g_object_unref (task);
1252 task_thread_cancelled (GCancellable *cancellable,
1255 GTask *task = user_data;
1257 g_task_thread_pool_resort ();
1259 g_mutex_lock (&task->lock);
1260 task->thread_cancelled = TRUE;
1262 if (!task->return_on_cancel)
1264 g_mutex_unlock (&task->lock);
1268 /* We don't actually set task->error; g_task_return_error() doesn't
1269 * use a lock, and g_task_propagate_error() will call
1270 * g_cancellable_set_error_if_cancelled() anyway.
1272 g_mutex_unlock (&task->lock);
1273 g_task_thread_complete (task);
1277 task_thread_cancelled_disconnect_notify (gpointer task,
1280 g_object_unref (task);
1284 g_task_start_task_thread (GTask *task,
1285 GTaskThreadFunc task_func)
1287 g_mutex_init (&task->lock);
1288 g_cond_init (&task->cond);
1290 g_mutex_lock (&task->lock);
1292 task->task_func = task_func;
1294 if (task->cancellable)
1296 if (task->return_on_cancel &&
1297 g_cancellable_set_error_if_cancelled (task->cancellable,
1300 task->thread_cancelled = task->thread_complete = TRUE;
1301 g_thread_pool_push (task_pool, g_object_ref (task), NULL);
1305 g_signal_connect_data (task->cancellable, "cancelled",
1306 G_CALLBACK (task_thread_cancelled),
1307 g_object_ref (task),
1308 task_thread_cancelled_disconnect_notify, 0);
1311 g_thread_pool_push (task_pool, g_object_ref (task), &task->error);
1313 task->thread_complete = TRUE;
1314 else if (g_private_get (&task_private))
1316 /* This thread is being spawned from another GTask thread, so
1317 * bump up max-threads so we don't starve.
1319 g_mutex_lock (&task_pool_mutex);
1320 if (g_thread_pool_set_max_threads (task_pool,
1321 g_thread_pool_get_max_threads (task_pool) + 1,
1323 task->blocking_other_task = TRUE;
1324 g_mutex_unlock (&task_pool_mutex);
1329 * g_task_run_in_thread:
1331 * @task_func: a #GTaskThreadFunc
1333 * Runs @task_func in another thread. When @task_func returns, @task's
1334 * #GAsyncReadyCallback will be invoked in @task's #GMainContext.
1336 * This takes a ref on @task until the task completes.
1338 * See #GTaskThreadFunc for more details about how @task_func is handled.
1343 g_task_run_in_thread (GTask *task,
1344 GTaskThreadFunc task_func)
1346 g_return_if_fail (G_IS_TASK (task));
1348 g_object_ref (task);
1349 g_task_start_task_thread (task, task_func);
1351 /* The task may already be cancelled, or g_thread_pool_push() may
1354 if (task->thread_complete)
1356 g_mutex_unlock (&task->lock);
1357 g_task_return (task, G_TASK_RETURN_FROM_THREAD);
1360 g_mutex_unlock (&task->lock);
1362 g_object_unref (task);
1366 * g_task_run_in_thread_sync:
1368 * @task_func: a #GTaskThreadFunc
1370 * Runs @task_func in another thread, and waits for it to return or be
1371 * cancelled. You can use g_task_propagate_pointer(), etc, afterward
1372 * to get the result of @task_func.
1374 * See #GTaskThreadFunc for more details about how @task_func is handled.
1376 * Normally this is used with tasks created with a %NULL
1377 * <literal>callback</literal>, but note that even if the task does
1378 * have a callback, it will not be invoked when @task_func returns.
1383 g_task_run_in_thread_sync (GTask *task,
1384 GTaskThreadFunc task_func)
1386 g_return_if_fail (G_IS_TASK (task));
1388 g_object_ref (task);
1390 task->synchronous = TRUE;
1391 g_task_start_task_thread (task, task_func);
1393 while (!task->thread_complete)
1394 g_cond_wait (&task->cond, &task->lock);
1396 g_mutex_unlock (&task->lock);
1397 g_object_unref (task);
1401 * g_task_attach_source:
1403 * @source: the source to attach
1404 * @callback: the callback to invoke when @source triggers
1406 * A utility function for dealing with async operations where you need
1407 * to wait for a #GSource to trigger. Attaches @source to @task's
1408 * #GMainContext with @task's <link
1409 * linkend="io-priority">priority</link>, and sets @source's callback
1410 * to @callback, with @task as the callback's
1411 * <literal>user_data</literal>.
1413 * This takes a reference on @task until @source is destroyed.
1418 g_task_attach_source (GTask *task,
1420 GSourceFunc callback)
1422 g_source_set_callback (source, callback,
1423 g_object_ref (task), g_object_unref);
1424 g_source_set_priority (source, task->priority);
1425 g_source_attach (source, task->context);
1430 g_task_propagate_error (GTask *task,
1433 if (task->check_cancellable &&
1434 g_cancellable_set_error_if_cancelled (task->cancellable, error))
1436 else if (task->error)
1438 g_propagate_error (error, task->error);
1447 * g_task_return_pointer:
1449 * @result: (allow-none) (transfer full): the pointer result of a task
1451 * @result_destroy: (allow-none): a #GDestroyNotify function.
1453 * Sets @task's result to @result and completes the task. If @result
1454 * is not %NULL, then @result_destroy will be used to free @result if
1455 * the caller does not take ownership of it with
1456 * g_task_propagate_pointer().
1458 * "Completes the task" means that for an ordinary asynchronous task
1459 * it will either invoke the task's callback, or else queue that
1460 * callback to be invoked in the proper #GMainContext, or in the next
1461 * iteration of the current #GMainContext. For a task run via
1462 * g_task_run_in_thread() or g_task_run_in_thread_sync(), calling this
1463 * method will save @result to be returned to the caller later, but
1464 * the task will not actually be completed until the #GTaskThreadFunc
1467 * Note that since the task may be completed before returning from
1468 * g_task_return_pointer(), you cannot assume that @result is still
1469 * valid after calling this, unless you are still holding another
1475 g_task_return_pointer (GTask *task,
1477 GDestroyNotify result_destroy)
1479 g_return_if_fail (task->result_set == FALSE);
1481 task->result.pointer = result;
1482 task->result_destroy = result_destroy;
1484 g_task_return (task, G_TASK_RETURN_SUCCESS);
1488 * g_task_propagate_pointer:
1490 * @error: return location for a #GError
1492 * Gets the result of @task as a pointer, and transfers ownership
1493 * of that value to the caller.
1495 * If the task resulted in an error, or was cancelled, then this will
1496 * instead return %NULL and set @error.
1498 * Since this method transfers ownership of the return value (or
1499 * error) to the caller, you may only call it once.
1501 * Returns: (transfer full): the task result, or %NULL on error
1506 g_task_propagate_pointer (GTask *task,
1509 if (g_task_propagate_error (task, error))
1512 g_return_val_if_fail (task->result_set == TRUE, NULL);
1514 task->result_destroy = NULL;
1515 task->result_set = FALSE;
1516 return task->result.pointer;
1520 * g_task_return_int:
1522 * @result: the integer (#gssize) result of a task function.
1524 * Sets @task's result to @result and completes the task (see
1525 * g_task_return_pointer() for more discussion of exactly what this
1531 g_task_return_int (GTask *task,
1534 g_return_if_fail (task->result_set == FALSE);
1536 task->result.size = result;
1538 g_task_return (task, G_TASK_RETURN_SUCCESS);
1542 * g_task_propagate_int:
1544 * @error: return location for a #GError
1546 * Gets the result of @task as an integer (#gssize).
1548 * If the task resulted in an error, or was cancelled, then this will
1549 * instead return -1 and set @error.
1551 * Since this method transfers ownership of the return value (or
1552 * error) to the caller, you may only call it once.
1554 * Returns: the task result, or -1 on error
1559 g_task_propagate_int (GTask *task,
1562 if (g_task_propagate_error (task, error))
1565 g_return_val_if_fail (task->result_set == TRUE, -1);
1567 task->result_set = FALSE;
1568 return task->result.size;
1572 * g_task_return_boolean:
1574 * @result: the #gboolean result of a task function.
1576 * Sets @task's result to @result and completes the task (see
1577 * g_task_return_pointer() for more discussion of exactly what this
1583 g_task_return_boolean (GTask *task,
1586 g_return_if_fail (task->result_set == FALSE);
1588 task->result.boolean = result;
1590 g_task_return (task, G_TASK_RETURN_SUCCESS);
1594 * g_task_propagate_boolean:
1596 * @error: return location for a #GError
1598 * Gets the result of @task as a #gboolean.
1600 * If the task resulted in an error, or was cancelled, then this will
1601 * instead return %FALSE and set @error.
1603 * Since this method transfers ownership of the return value (or
1604 * error) to the caller, you may only call it once.
1606 * Returns: the task result, or %FALSE on error
1611 g_task_propagate_boolean (GTask *task,
1614 if (g_task_propagate_error (task, error))
1617 g_return_val_if_fail (task->result_set == TRUE, FALSE);
1619 task->result_set = FALSE;
1620 return task->result.boolean;
1624 * g_task_return_error:
1626 * @error: (transfer full): the #GError result of a task function.
1628 * Sets @task's result to @error (which @task assumes ownership of)
1629 * and completes the task (see g_task_return_pointer() for more
1630 * discussion of exactly what this means).
1632 * Note that since the task takes ownership of @error, and since the
1633 * task may be completed before returning from g_task_return_error(),
1634 * you cannot assume that @error is still valid after calling this.
1635 * Call g_error_copy() on the error if you need to keep a local copy
1638 * See also g_task_return_new_error().
1643 g_task_return_error (GTask *task,
1646 g_return_if_fail (task->result_set == FALSE);
1647 g_return_if_fail (error != NULL);
1649 task->error = error;
1651 g_task_return (task, G_TASK_RETURN_ERROR);
1655 * g_task_return_new_error:
1657 * @domain: a #GQuark.
1658 * @code: an error code.
1659 * @format: a string with format characters.
1660 * @...: a list of values to insert into @format.
1662 * Sets @task's result to a new #GError created from @domain, @code,
1663 * @format, and the remaining arguments, and completes the task (see
1664 * g_task_return_pointer() for more discussion of exactly what this
1667 * See also g_task_return_error().
1672 g_task_return_new_error (GTask *task,
1681 va_start (args, format);
1682 error = g_error_new_valist (domain, code, format, args);
1685 g_task_return_error (task, error);
1689 * g_task_return_error_if_cancelled:
1692 * Checks if @task's #GCancellable has been cancelled, and if so, sets
1693 * @task's error accordingly and completes the task (see
1694 * g_task_return_pointer() for more discussion of exactly what this
1697 * Return value: %TRUE if @task has been cancelled, %FALSE if not
1702 g_task_return_error_if_cancelled (GTask *task)
1704 GError *error = NULL;
1706 g_return_val_if_fail (task->result_set == FALSE, FALSE);
1708 if (g_cancellable_set_error_if_cancelled (task->cancellable, &error))
1710 /* We explicitly set task->error so this works even when
1711 * check-cancellable is not set.
1713 g_clear_error (&task->error);
1714 task->error = error;
1716 g_task_return (task, G_TASK_RETURN_ERROR);
1727 * Tests if @task resulted in an error.
1729 * Returns: %TRUE if the task resulted in an error, %FALSE otherwise.
1734 g_task_had_error (GTask *task)
1736 if (task->error != NULL)
1739 if (task->check_cancellable && g_cancellable_is_cancelled (task->cancellable))
1747 * @result: (type Gio.AsyncResult): A #GAsyncResult
1748 * @source_object: (allow-none) (type GObject): the source object
1749 * expected to be associated with the task
1751 * Checks that @result is a #GTask, and that @source_object is its
1752 * source object (or that @source_object is %NULL and @result has no
1753 * source object). This can be used in g_return_if_fail() checks.
1755 * Return value: %TRUE if @result and @source_object are valid, %FALSE
1761 g_task_is_valid (gpointer result,
1762 gpointer source_object)
1764 if (!G_IS_TASK (result))
1767 return G_TASK (result)->source_object == source_object;
1771 g_task_compare_priority (gconstpointer a,
1775 const GTask *ta = a;
1776 const GTask *tb = b;
1777 gboolean a_cancelled, b_cancelled;
1779 /* Tasks that are causing other tasks to block have higher
1782 if (ta->blocking_other_task && !tb->blocking_other_task)
1784 else if (tb->blocking_other_task && !ta->blocking_other_task)
1787 /* Let already-cancelled tasks finish right away */
1788 a_cancelled = (ta->check_cancellable &&
1789 g_cancellable_is_cancelled (ta->cancellable));
1790 b_cancelled = (tb->check_cancellable &&
1791 g_cancellable_is_cancelled (tb->cancellable));
1792 if (a_cancelled && !b_cancelled)
1794 else if (b_cancelled && !a_cancelled)
1797 /* Lower priority == run sooner == negative return value */
1798 return ta->priority - tb->priority;
1802 g_task_thread_pool_init (void)
1804 task_pool = g_thread_pool_new (g_task_thread_pool_thread, NULL,
1806 g_assert (task_pool != NULL);
1808 g_thread_pool_set_sort_function (task_pool, g_task_compare_priority, NULL);
1812 g_task_thread_pool_resort (void)
1814 g_thread_pool_set_sort_function (task_pool, g_task_compare_priority, NULL);
1818 g_task_class_init (GTaskClass *klass)
1820 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
1822 gobject_class->finalize = g_task_finalize;
1826 g_task_get_user_data (GAsyncResult *res)
1828 return G_TASK (res)->callback_data;
1832 g_task_is_tagged (GAsyncResult *res,
1833 gpointer source_tag)
1835 return G_TASK (res)->source_tag == source_tag;
1839 g_task_async_result_iface_init (GAsyncResultIface *iface)
1841 iface->get_user_data = g_task_get_user_data;
1842 iface->get_source_object = g_task_ref_source_object;
1843 iface->is_tagged = g_task_is_tagged;