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, write to the
17 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18 * Boston, MA 02111-1307, USA.
25 #include "gasyncresult.h"
26 #include "gcancellable.h"
30 * @short_description: Cancellable synchronous or asynchronous task and result
32 * @see_also: #GAsyncResult
35 * A #GTask represents and manages a cancellable "task".
38 * <title>Asynchronous operations</title>
40 * The most common usage of #GTask is as a #GAsyncResult, to
41 * manage data during an asynchronous operation. You call
42 * g_task_new() in the "start" method, followed by
43 * g_task_set_task_data() and the like if you need to keep some
44 * additional data associated with the task, and then pass the
45 * task object around through your asynchronous operation.
46 * Eventually, you will call a method such as
47 * g_task_return_pointer() or g_task_return_error(), which will
48 * save the value you give it and then invoke the task's callback
49 * function (waiting until the next next iteration of the main
50 * loop first, if necessary). The caller will pass the #GTask back
51 * to the operation's finish function (as a #GAsyncResult), and
52 * you can use g_task_propagate_pointer() or the like to extract
55 * <example id="gtask-async"><title>GTask as a GAsyncResult</title>
58 * CakeFrostingType frosting;
63 * decoration_data_free (DecorationData *decoration)
65 * g_free (decoration->message);
66 * g_slice_free (DecorationData, decoration);
70 * baked_cb (Cake *cake,
73 * GTask *task = user_data;
74 * DecorationData *decoration = g_task_get_task_data (task);
75 * GError *error = NULL;
79 * g_task_return_new_error (task, BAKER_ERROR, BAKER_ERROR_NO_FLOUR,
80 * "Go to the supermarket");
81 * g_object_unref (task);
85 * if (!cake_decorate (cake, decoration->frosting, decoration->message, &error))
87 * g_object_unref (cake);
88 * /* g_task_return_error() takes ownership of error */
89 * g_task_return_error (task, error);
90 * g_object_unref (task);
94 * g_task_return_pointer (result, cake, g_object_unref);
95 * g_object_unref (task);
99 * baker_bake_cake_async (Baker *self,
102 * CakeFrostingType frosting,
103 * const char *message,
104 * GCancellable *cancellable,
105 * GAsyncReadyCallback callback,
106 * gpointer user_data)
109 * DecorationData *decoration;
112 * task = g_task_new (self, cancellable, callback, user_data);
115 * g_task_return_new_error (task, BAKER_ERROR, BAKER_ERROR_TOO_SMALL,
116 * "%ucm radius cakes are silly",
118 * g_object_unref (task);
122 * cake = _baker_get_cached_cake (self, radius, flavor, frosting, message);
125 * /* _baker_get_cached_cake() returns a reffed cake */
126 * g_task_return_pointer (task, cake, g_object_unref);
127 * g_object_unref (task);
131 * decoration = g_slice_new (DecorationData);
132 * decoration->frosting = frosting;
133 * decoration->message = g_strdup (message);
134 * g_task_set_task_data (task, decoration, (GDestroyNotify) decoration_data_free);
136 * _baker_begin_cake (self, radius, flavor, cancellable, baked_cb, task);
140 * baker_bake_cake_finish (Baker *self,
141 * GAsyncResult *result,
144 * g_return_val_if_fail (g_task_is_valid (result, self), NULL);
146 * return g_task_propagate_pointer (G_TASK (result), error);
152 * <title>Chained asynchronous operations</title>
154 * #GTask also tries to simplify asynchronous operations that
155 * internally chain together several smaller asynchronous
156 * operations. g_task_get_cancellable(), g_task_get_context(), and
157 * g_task_get_priority() allow you to get back the task's
158 * #GCancellable, #GMainContext, and <link
159 * linkend="io-priority">I/O priority</link> when starting a new
160 * subtask, so you don't have to keep track of them yourself.
161 * g_task_attach_source() simplifies the case of waiting for a
162 * source to fire (automatically using the correct #GMainContext
165 * <example id="gtask-chained"><title>Chained asynchronous operations</title>
169 * CakeFrostingType frosting;
174 * decoration_data_free (BakingData *bd)
177 * g_object_unref (bd->cake);
178 * g_free (bd->message);
179 * g_slice_free (BakingData, bd);
183 * decorated_cb (Cake *cake,
184 * GAsyncResult *result,
185 * gpointer user_data)
187 * GTask *task = user_data;
188 * GError *error = NULL;
190 * if (!cake_decorate_finish (cake, result, &error))
192 * g_object_unref (cake);
193 * g_task_return_error (task, error);
194 * g_object_unref (task);
198 * /* baking_data_free() will drop its ref on the cake, so
199 * * we have to take another here to give to the caller.
201 * g_task_return_pointer (result, g_object_ref (cake), g_object_unref);
202 * g_object_unref (task);
206 * decorator_ready (gpointer user_data)
208 * GTask *task = user_data;
209 * BakingData *bd = g_task_get_task_data (task);
211 * cake_decorate_async (bd->cake, bd->frosting, bd->message,
212 * g_task_get_cancellable (task),
213 * decorated_cb, task);
217 * baked_cb (Cake *cake,
218 * gpointer user_data)
220 * GTask *task = user_data;
221 * BakingData *bd = g_task_get_task_data (task);
222 * GError *error = NULL;
226 * g_task_return_new_error (task, BAKER_ERROR, BAKER_ERROR_NO_FLOUR,
227 * "Go to the supermarket");
228 * g_object_unref (task);
234 * /* Bail out now if the user has already cancelled */
235 * if (g_task_return_error_if_cancelled (g_task_get_cancellable (task)))
237 * g_object_unref (task);
241 * if (cake_decorator_available (cake))
242 * decorator_ready (task);
247 * source = cake_decorator_wait_source_new (cake);
248 * /* Attach @source to @task's GMainContext and have it call
249 * * decorator_ready() when it is ready.
251 * g_task_attach_source (task, source,
252 * G_CALLBACK (decorator_ready));
253 * g_source_unref (source);
258 * baker_bake_cake_async (Baker *self,
261 * CakeFrostingType frosting,
262 * const char *message,
264 * GCancellable *cancellable,
265 * GAsyncReadyCallback callback,
266 * gpointer user_data)
271 * task = g_task_new (self, cancellable, callback, user_data);
272 * g_task_set_priority (task, priority);
274 * bd = g_slice_new0 (BakingData);
275 * bd->frosting = frosting;
276 * bd->message = g_strdup (message);
277 * g_task_set_task_data (task, bd, (GDestroyNotify) baking_data_free);
279 * _baker_begin_cake (self, radius, flavor, cancellable, baked_cb, task);
283 * baker_bake_cake_finish (Baker *self,
284 * GAsyncResult *result,
287 * g_return_val_if_fail (g_task_is_valid (result, self), NULL);
289 * return g_task_propagate_pointer (G_TASK (result), error);
295 * <title>Asynchronous operations from synchronous ones</title>
297 * You can use g_task_run_in_thread() to turn a synchronous
298 * operation into an asynchronous one, by running it in a thread
299 * which will then dispatch the result back to the caller's
300 * #GMainContext when it completes.
302 * <example id="gtask-run-in-thread"><title>g_task_run_in_thread()</title>
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.
388 * <example id="gtask-cancellable"><title>g_task_set_return_on_cancel()</title>
391 * bake_cake_thread (GTask *task,
392 * gpointer source_object,
393 * gpointer task_data,
394 * GCancellable *cancellable)
396 * Baker *self = source_object;
397 * CakeData *cake_data = task_data;
399 * GError *error = NULL;
401 * cake = bake_cake (baker, cake_data->radius, cake_data->flavor,
402 * cake_data->frosting, cake_data->message,
406 * g_task_return_error (task, error);
410 * /* If the task has already been cancelled, then we don't
411 * * want to add the cake to the cake cache. Likewise, we don't
412 * * want to have the task get cancelled in the middle of
413 * * updating the cache. g_task_set_return_on_cancel() will
414 * * return %TRUE here if it managed to disable return-on-cancel,
415 * * or %FALSE if the task was cancelled before it could.
417 * if (g_task_set_return_on_cancel (task, FALSE))
419 * /* If the caller cancels at this point, their
420 * * GAsyncReadyCallback won't be invoked until we return,
421 * * so we don't have to worry that this code will run at
422 * * the same time as that code does. But if there were
423 * * other functions that might look at the cake cache,
424 * * then we'd probably need a GMutex here as well.
426 * baker_add_cake_to_cache (baker, cake);
427 * g_task_return_pointer (task, cake, g_object_unref);
432 * baker_bake_cake_async (Baker *self,
435 * CakeFrostingType frosting,
436 * const char *message,
437 * GCancellable *cancellable,
438 * GAsyncReadyCallback callback,
439 * gpointer user_data)
441 * CakeData *cake_data;
444 * cake_data = g_slice_new (CakeData);
447 * task = g_task_new (self, cancellable, callback, user_data);
448 * g_task_set_task_data (task, cake_data, (GDestroyNotify) cake_data_free);
449 * g_task_set_return_on_cancel (task, TRUE);
450 * g_task_run_in_thread (task, bake_cake_thread);
454 * baker_bake_cake_sync (Baker *self,
457 * CakeFrostingType frosting,
458 * const char *message,
459 * GCancellable *cancellable,
462 * CakeData *cake_data;
466 * cake_data = g_slice_new (CakeData);
469 * task = g_task_new (self, cancellable, NULL, NULL);
470 * g_task_set_task_data (task, cake_data, (GDestroyNotify) cake_data_free);
471 * g_task_set_return_on_cancel (task, TRUE);
472 * g_task_run_in_thread_sync (task, bake_cake_thread);
474 * cake = g_task_propagate_pointer (task, error);
475 * g_object_unref (task);
482 * <title>Porting from <literal>GSimpleAsyncResult</literal></title>
484 * #GTask's API attempts to be simpler than #GSimpleAsyncResult's
489 * You can save task-specific data with g_task_set_task_data(), and
490 * retrieve it later with g_task_get_task_data(). This replaces the
491 * abuse of g_simple_async_result_set_op_res_gpointer() for the same
492 * purpose with #GSimpleAsyncResult.
495 * In addition to the task data, #GTask also keeps track of the
496 * <link linkend="io-priority">priority</link>, #GCancellable, and
497 * #GMainContext associated with the task, so tasks that consist of
498 * a chain of simpler asynchronous operations will have easy access
499 * to those values when starting each sub-task.
502 * g_task_return_error_if_cancelled() provides simplified
503 * handling for cancellation. In addition, cancellation
504 * overrides any other #GTask return value by default, like
505 * #GSimpleAsyncResult does when
506 * g_simple_async_result_set_check_cancellable() is called.
507 * (You can use g_task_set_check_cancellable() to turn off that
508 * behavior.) On the other hand, g_task_run_in_thread()
509 * guarantees that it will always run your
510 * <literal>task_func</literal>, even if the task's #GCancellable
511 * is already cancelled before the task gets a chance to run;
512 * you can start your <literal>task_func</literal> with a
513 * g_task_return_error_if_cancelled() check if you need the
517 * The "return" methods (eg, g_task_return_pointer())
518 * automatically cause the task to be "completed" as well, and
519 * there is no need to worry about the "complete" vs "complete
520 * in idle" distinction. (#GTask automatically figures out
521 * whether the task's callback can be invoked directly, or
522 * if it needs to be sent to another #GMainContext, or delayed
523 * until the next iteration of the current #GMainContext.)
526 * The "finish" functions for #GTask-based operations are generally
527 * much simpler than #GSimpleAsyncResult ones, normally consisting
528 * of only a single call to g_task_propagate_pointer() or the like.
529 * Since g_task_propagate_pointer() "steals" the return value from
530 * the #GTask, it is not necessary to juggle pointers around to
531 * prevent it from being freed twice.
534 * With #GSimpleAsyncResult, it was common to call
535 * g_simple_async_result_propagate_error() from the
536 * <literal>_finish()</literal> wrapper function, and have
537 * virtual method implementations only deal with successful
538 * returns. This behavior is deprecated, because it makes it
539 * difficult for a subclass to chain to a parent class's async
540 * methods. Instead, the wrapper function should just be a
541 * simple wrapper, and the virtual method should call an
542 * appropriate <literal>g_task_propagate_</literal> function.
543 * Note that wrapper methods can now use
544 * g_async_result_legacy_propagate_error() to do old-style
545 * #GSimpleAsyncResult error-returning behavior, and
546 * g_async_result_is_tagged() to check if a result is tagged as
547 * having come from the <literal>_async()</literal> wrapper
548 * function (for "short-circuit" results, such as when passing
549 * 0 to g_input_stream_read_async()).
558 * The opaque object representing a synchronous or asynchronous task
563 GObject parent_instance;
565 gpointer source_object;
569 GDestroyNotify task_data_destroy;
571 GMainContext *context;
572 guint64 creation_time;
574 GCancellable *cancellable;
575 gboolean check_cancellable;
577 GAsyncReadyCallback callback;
578 gpointer callback_data;
580 GTaskThreadFunc task_func;
583 gboolean return_on_cancel;
584 gboolean thread_cancelled;
585 gboolean synchronous;
586 gboolean thread_complete;
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;
618 g_task_init (GTask *task)
620 task->check_cancellable = TRUE;
624 g_task_finalize (GObject *object)
626 GTask *task = G_TASK (object);
628 g_clear_object (&task->source_object);
629 g_clear_object (&task->cancellable);
632 g_main_context_unref (task->context);
634 if (task->task_data_destroy)
635 task->task_data_destroy (task->task_data);
637 if (task->result_destroy && task->result.pointer)
638 task->result_destroy (task->result.pointer);
640 if (G_TASK_IS_THREADED (task))
642 g_mutex_clear (&task->lock);
643 g_cond_clear (&task->cond);
646 G_OBJECT_CLASS (g_task_parent_class)->finalize (object);
651 * @source_object: (allow-none) (type GObject): the #GObject that owns
652 * this task, or %NULL.
653 * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore.
654 * @callback: (scope async): a #GAsyncReadyCallback.
655 * @callback_data: (closure): user data passed to @callback.
657 * Creates a #GTask acting on @source_object, which will eventually be
658 * used to invoke @callback in the current <link
659 * linkend="g-main-context-push-thread-default">thread-default main
662 * Call this in the "start" method of your asynchronous method, and
663 * pass the #GTask around throughout the asynchronous operation. You
664 * can use g_task_set_task_data() to attach task-specific data to the
665 * object, which you can retrieve later via g_task_get_task_data().
667 * By default, if @cancellable is cancelled, then the return value of
668 * the task will always be %G_IO_ERROR_CANCELLED, even if the task had
669 * already completed before the cancellation. This allows for
670 * simplified handling in cases where cancellation may imply that
671 * other objects that the task depends on have been destroyed. If you
672 * do not want this behavior, you can use
673 * g_task_set_check_cancellable() to change it.
680 g_task_new (gpointer source_object,
681 GCancellable *cancellable,
682 GAsyncReadyCallback callback,
683 gpointer callback_data)
688 task = g_object_new (G_TYPE_TASK, NULL);
689 task->source_object = source_object ? g_object_ref (source_object) : NULL;
690 task->cancellable = cancellable ? g_object_ref (cancellable) : NULL;
691 task->callback = callback;
692 task->callback_data = callback_data;
693 task->context = g_main_context_ref_thread_default ();
695 source = g_main_current_source ();
697 task->creation_time = g_source_get_time (source);
703 * g_task_report_error:
704 * @source_object: (allow-none) (type GObject): the #GObject that owns
705 * this task, or %NULL.
706 * @callback: (scope async): a #GAsyncReadyCallback.
707 * @callback_data: (closure): user data passed to @callback.
708 * @source_tag: an opaque pointer indicating the source of this task
709 * @error: (transfer full): error to report
711 * Creates a #GTask and then immediately calls g_task_return_error()
712 * on it. Use this in the wrapper function of an asynchronous method
713 * when you want to avoid even calling the virtual method. You can
714 * then use g_async_result_is_tagged() in the finish method wrapper to
715 * check if the result there is tagged as having been created by the
716 * wrapper method, and deal with it appropriately if so.
718 * See also g_task_report_new_error().
723 g_task_report_error (gpointer source_object,
724 GAsyncReadyCallback callback,
725 gpointer callback_data,
731 task = g_task_new (source_object, NULL, callback, callback_data);
732 g_task_set_source_tag (task, source_tag);
733 g_task_return_error (task, error);
734 g_object_unref (task);
738 * g_task_report_new_error:
739 * @source_object: (allow-none) (type GObject): the #GObject that owns
740 * this task, or %NULL.
741 * @callback: (scope async): a #GAsyncReadyCallback.
742 * @callback_data: (closure): user data passed to @callback.
743 * @source_tag: an opaque pointer indicating the source of this task
744 * @domain: a #GQuark.
745 * @code: an error code.
746 * @format: a string with format characters.
747 * @...: a list of values to insert into @format.
749 * Creates a #GTask and then immediately calls
750 * g_task_return_new_error() on it. Use this in the wrapper function
751 * of an asynchronous method when you want to avoid even calling the
752 * virtual method. You can then use g_async_result_is_tagged() in the
753 * finish method wrapper to check if the result there is tagged as
754 * having been created by the wrapper method, and deal with it
755 * appropriately if so.
757 * See also g_task_report_error().
762 g_task_report_new_error (gpointer source_object,
763 GAsyncReadyCallback callback,
764 gpointer callback_data,
774 va_start (ap, format);
775 error = g_error_new_valist (domain, code, format, ap);
778 g_task_report_error (source_object, callback, callback_data,
783 * g_task_set_task_data:
785 * @task_data: (allow-none): task-specific data
786 * @task_data_destroy: (allow-none): #GDestroyNotify for @task_data
788 * Sets @task's task data (freeing the existing task data, if any).
793 g_task_set_task_data (GTask *task,
795 GDestroyNotify task_data_destroy)
797 if (task->task_data_destroy)
798 task->task_data_destroy (task->task_data);
800 task->task_data = task_data;
801 task->task_data_destroy = task_data_destroy;
805 * g_task_set_priority:
807 * @priority: the <link linkend="io-priority">priority</link>
810 * Sets @task's priority. If you do not call this, it will default to
811 * %G_PRIORITY_DEFAULT.
813 * This will affect the priority of #GSources created with
814 * g_task_attach_source() and the scheduling of tasks run in threads,
815 * and can also be explicitly retrieved later via
816 * g_task_get_priority().
821 g_task_set_priority (GTask *task,
824 task->priority = priority;
828 * g_task_set_check_cancellable:
830 * @check_cancellable: whether #GTask will check the state of
831 * its #GCancellable for you.
833 * Sets or clears @task's check-cancellable flag. If this is %TRUE
834 * (the default), then g_task_propagate_pointer(), etc, and
835 * g_task_had_error() will check the task's #GCancellable first, and
836 * if it has been cancelled, then they will consider the task to have
837 * returned an "Operation was cancelled" error
838 * (%G_IO_ERROR_CANCELLED), regardless of any other error or return
839 * value the task may have had.
841 * If @check_cancellable is %FALSE, then the #GTask will not check the
842 * cancellable itself, and it is up to @task's owner to do this (eg,
843 * via g_task_return_error_if_cancelled()).
845 * If you are using g_task_set_return_on_cancel() as well, then
846 * you must leave check-cancellable set %TRUE.
851 g_task_set_check_cancellable (GTask *task,
852 gboolean check_cancellable)
854 g_return_if_fail (check_cancellable || !task->return_on_cancel);
856 task->check_cancellable = check_cancellable;
859 static void g_task_thread_complete (GTask *task);
862 * g_task_set_return_on_cancel:
864 * @return_on_cancel: whether the task returns automatically when
867 * Sets or clears @task's return-on-cancel flag. This is only
868 * meaningful for tasks run via g_task_run_in_thread() or
869 * g_task_run_in_thread_sync().
871 * If @return_on_cancel is %TRUE, then cancelling @task's
872 * #GCancellable will immediately cause it to return, as though the
873 * task's #GTaskThreadFunc had called
874 * g_task_return_error_if_cancelled() and then returned.
876 * This allows you to create a cancellable wrapper around an
877 * uninterruptable function. The #GTaskThreadFunc just needs to be
878 * careful that it does not modify any externally-visible state after
879 * it has been cancelled. To do that, the thread should call
880 * g_task_set_return_on_cancel() again to (atomically) set
881 * return-on-cancel %FALSE before making externally-visible changes;
882 * if the task gets cancelled before the return-on-cancel flag could
883 * be changed, g_task_set_return_on_cancel() will indicate this by
886 * You can disable and re-enable this flag multiple times if you wish.
887 * If the task's #GCancellable is cancelled while return-on-cancel is
888 * %FALSE, then calling g_task_set_return_on_cancel() to set it %TRUE
889 * again will cause the task to be cancelled at that point.
891 * If the task's #GCancellable is already cancelled before you call
892 * g_task_run_in_thread()/g_task_run_in_thread_sync(), then the
893 * #GTaskThreadFunc will still be run (for consistency), but the task
894 * will also be completed right away.
896 * Returns: %TRUE if @task's return-on-cancel flag was changed to
897 * match @return_on_cancel. %FALSE if @task has already been
903 g_task_set_return_on_cancel (GTask *task,
904 gboolean return_on_cancel)
906 g_return_val_if_fail (task->check_cancellable || !return_on_cancel, FALSE);
908 if (!G_TASK_IS_THREADED (task))
910 task->return_on_cancel = return_on_cancel;
914 g_mutex_lock (&task->lock);
915 if (task->thread_cancelled)
917 if (return_on_cancel && !task->return_on_cancel)
919 g_mutex_unlock (&task->lock);
920 g_task_thread_complete (task);
923 g_mutex_unlock (&task->lock);
926 task->return_on_cancel = return_on_cancel;
927 g_mutex_unlock (&task->lock);
933 * g_task_set_source_tag:
935 * @source_tag: an opaque pointer indicating the source of this task
937 * Sets @task's source tag. You can use this to tag a task return
938 * value with a particular pointer (usually a pointer to the function
939 * doing the tagging) and then later check it using
940 * g_task_get_source_tag() (or g_async_result_is_tagged()) in the
941 * task's "finish" function, to figure out if the response came from a
947 g_task_set_source_tag (GTask *task,
950 task->source_tag = source_tag;
954 * g_task_get_source_object:
957 * Gets the source object from @task. Like
958 * g_async_result_get_source_object(), but does not ref the object.
960 * Returns: (transfer none) (type GObject): @task's source object, or %NULL
965 g_task_get_source_object (GTask *task)
967 return task->source_object;
971 g_task_ref_source_object (GAsyncResult *res)
973 GTask *task = G_TASK (res);
975 if (task->source_object)
976 return g_object_ref (task->source_object);
982 * g_task_get_task_data:
985 * Gets @task's <literal>task_data</literal>.
987 * Returns: (transfer none): @task's <literal>task_data</literal>.
992 g_task_get_task_data (GTask *task)
994 return task->task_data;
998 * g_task_get_priority:
1001 * Gets @task's priority
1003 * Returns: @task's priority
1008 g_task_get_priority (GTask *task)
1010 return task->priority;
1014 * g_task_get_context:
1017 * Gets the #GMainContext that @task will return its result in (that
1018 * is, the context that was the <link
1019 * linkend="g-main-context-push-thread-default">thread-default main
1020 * context</link> at the point when @task was created).
1022 * This will always return a non-%NULL value, even if the task's
1023 * context is the default #GMainContext.
1025 * Returns: (transfer none): @task's #GMainContext
1030 g_task_get_context (GTask *task)
1032 return task->context;
1036 * g_task_get_cancellable:
1039 * Gets @task's #GCancellable
1041 * Returns: (transfer none): @task's #GCancellable
1046 g_task_get_cancellable (GTask *task)
1048 return task->cancellable;
1052 * g_task_get_check_cancellable:
1055 * Gets @task's check-cancellable flag. See
1056 * g_task_set_check_cancellable() for more details.
1061 g_task_get_check_cancellable (GTask *task)
1063 return task->check_cancellable;
1067 * g_task_get_return_on_cancel:
1070 * Gets @task's return-on-cancel flag. See
1071 * g_task_set_return_on_cancel() for more details.
1076 g_task_get_return_on_cancel (GTask *task)
1078 return task->return_on_cancel;
1082 * g_task_get_source_tag:
1085 * Gets @task's source tag. See g_task_set_source_tag().
1087 * Return value: (transfer none): @task's source tag
1092 g_task_get_source_tag (GTask *task)
1094 return task->source_tag;
1099 g_task_return_now (GTask *task)
1101 g_main_context_push_thread_default (task->context);
1102 task->callback (task->source_object,
1103 G_ASYNC_RESULT (task),
1104 task->callback_data);
1105 g_main_context_pop_thread_default (task->context);
1109 complete_in_idle_cb (gpointer task)
1111 g_task_return_now (task);
1112 g_object_unref (task);
1117 G_TASK_RETURN_SUCCESS,
1118 G_TASK_RETURN_ERROR,
1119 G_TASK_RETURN_FROM_THREAD
1123 g_task_return (GTask *task,
1124 GTaskReturnType type)
1128 if (type == G_TASK_RETURN_SUCCESS)
1129 task->result_set = TRUE;
1131 if (task->synchronous || !task->callback)
1134 /* Normally we want to invoke the task's callback when its return
1135 * value is set. But if the task is running in a thread, then we
1136 * want to wait until after the task_func returns, to simplify
1137 * locking/refcounting/etc.
1139 if (G_TASK_IS_THREADED (task) && type != G_TASK_RETURN_FROM_THREAD)
1142 g_object_ref (task);
1144 /* See if we can complete the task immediately. First, we have to be
1145 * running inside the task's thread/GMainContext.
1147 source = g_main_current_source ();
1148 if (source && g_source_get_context (source) == task->context)
1150 /* Second, we can only complete immediately if this is not the
1151 * same iteration of the main loop that the task was created in.
1153 if (g_source_get_time (source) > task->creation_time)
1155 g_task_return_now (task);
1156 g_object_unref (task);
1161 /* Otherwise, complete in the next iteration */
1162 source = g_idle_source_new ();
1163 g_task_attach_source (task, source, complete_in_idle_cb);
1164 g_source_unref (source);
1171 * @source_object: (type GObject): @task's source object
1172 * @task_data: @task's task data
1173 * @cancellable: @task's #GCancellable, or %NULL
1175 * The prototype for a task function to be run in a thread via
1176 * g_task_run_in_thread() or g_task_run_in_thread_sync().
1178 * If the return-on-cancel flag is set on @task, and @cancellable gets
1179 * cancelled, then the #GTask will be completed immediately (as though
1180 * g_task_return_error_if_cancelled() had been called), without
1181 * waiting for the task function to complete. However, the task
1182 * function will continue running in its thread in the background. The
1183 * function therefore needs to be careful about how it uses
1184 * externally-visible state in this case. See
1185 * g_task_set_return_on_cancel() for more details.
1187 * Other than in that case, @task will be completed when the
1188 * #GTaskThreadFunc returns, <emphasis>not</emphasis> when it calls
1189 * a <literal>g_task_return_</literal> function.
1194 static void task_thread_cancelled (GCancellable *cancellable,
1195 gpointer user_data);
1198 g_task_thread_complete (GTask *task)
1200 g_mutex_lock (&task->lock);
1201 if (task->thread_complete)
1203 /* The task belatedly completed after having been cancelled
1204 * (or was cancelled in the midst of being completed).
1206 g_mutex_unlock (&task->lock);
1210 task->thread_complete = TRUE;
1211 g_mutex_unlock (&task->lock);
1213 if (task->cancellable)
1214 g_signal_handlers_disconnect_by_func (task->cancellable, task_thread_cancelled, task);
1216 if (task->synchronous)
1217 g_cond_signal (&task->cond);
1219 g_task_return (task, G_TASK_RETURN_FROM_THREAD);
1223 g_task_thread_pool_thread (gpointer thread_data,
1226 GTask *task = thread_data;
1228 task->task_func (task, task->source_object, task->task_data,
1230 g_task_thread_complete (task);
1231 g_object_unref (task);
1235 task_thread_cancelled (GCancellable *cancellable,
1238 GTask *task = user_data;
1240 g_task_thread_pool_resort ();
1242 g_mutex_lock (&task->lock);
1243 task->thread_cancelled = TRUE;
1245 if (!task->return_on_cancel)
1247 g_mutex_unlock (&task->lock);
1251 /* We don't actually set task->error; g_task_return_error() doesn't
1252 * use a lock, and g_task_propagate_error() will call
1253 * g_cancellable_set_error_if_cancelled() anyway.
1255 g_mutex_unlock (&task->lock);
1256 g_task_thread_complete (task);
1260 task_thread_cancelled_disconnect_notify (gpointer task,
1263 g_object_unref (task);
1267 g_task_start_task_thread (GTask *task,
1268 GTaskThreadFunc task_func)
1270 g_mutex_init (&task->lock);
1271 g_cond_init (&task->cond);
1273 g_mutex_lock (&task->lock);
1275 task->task_func = task_func;
1277 if (task->cancellable)
1279 if (task->return_on_cancel &&
1280 g_cancellable_set_error_if_cancelled (task->cancellable,
1283 task->thread_cancelled = task->thread_complete = TRUE;
1284 g_thread_pool_push (task_pool, g_object_ref (task), NULL);
1288 g_signal_connect_data (task->cancellable, "cancelled",
1289 G_CALLBACK (task_thread_cancelled),
1290 g_object_ref (task),
1291 task_thread_cancelled_disconnect_notify, 0);
1294 g_thread_pool_push (task_pool, g_object_ref (task), &task->error);
1296 task->thread_complete = TRUE;
1300 * g_task_run_in_thread:
1302 * @task_func: a #GTaskThreadFunc
1304 * Runs @task_func in another thread. When @task_func returns, @task's
1305 * #GAsyncReadyCallback will be invoked in @task's #GMainContext.
1307 * This takes a ref on @task until the task completes.
1309 * See #GTaskThreadFunc for more details about how @task_func is handled.
1314 g_task_run_in_thread (GTask *task,
1315 GTaskThreadFunc task_func)
1317 g_return_if_fail (G_IS_TASK (task));
1319 g_object_ref (task);
1320 g_task_start_task_thread (task, task_func);
1322 /* The task may already be cancelled, or g_thread_pool_push() may
1325 if (task->thread_complete)
1327 g_mutex_unlock (&task->lock);
1328 g_task_return (task, G_TASK_RETURN_FROM_THREAD);
1331 g_mutex_unlock (&task->lock);
1333 g_object_unref (task);
1337 * g_task_run_in_thread_sync:
1339 * @task_func: a #GTaskThreadFunc
1341 * Runs @task_func in another thread, and waits for it to return or be
1342 * cancelled. You can use g_task_propagate_pointer(), etc, afterward
1343 * to get the result of @task_func.
1345 * See #GTaskThreadFunc for more details about how @task_func is handled.
1347 * Normally this is used with tasks created with a %NULL
1348 * <literal>callback</literal>, but note that even if the task does
1349 * have a callback, it will not be invoked when @task_func returns.
1354 g_task_run_in_thread_sync (GTask *task,
1355 GTaskThreadFunc task_func)
1357 g_return_if_fail (G_IS_TASK (task));
1359 g_object_ref (task);
1361 task->synchronous = TRUE;
1362 g_task_start_task_thread (task, task_func);
1364 while (!task->thread_complete)
1365 g_cond_wait (&task->cond, &task->lock);
1367 g_mutex_unlock (&task->lock);
1368 g_object_unref (task);
1372 * g_task_attach_source:
1374 * @source: the source to attach
1375 * @callback: the callback to invoke when @source triggers
1377 * A utility function for dealing with async operations where you need
1378 * to wait for a #GSource to trigger. Attaches @source to @task's
1379 * #GMainContext with @task's <link
1380 * linkend="io-priority">priority</link>, and sets @source's callback
1381 * to @callback, with @task as the callback's
1382 * <literal>user_data</literal>.
1384 * This takes a reference on @task until @source is destroyed.
1389 g_task_attach_source (GTask *task,
1391 GSourceFunc callback)
1393 g_source_set_callback (source, callback,
1394 g_object_ref (task), g_object_unref);
1395 g_source_set_priority (source, task->priority);
1396 g_source_attach (source, task->context);
1401 g_task_propagate_error (GTask *task,
1404 if (task->check_cancellable &&
1405 g_cancellable_set_error_if_cancelled (task->cancellable, error))
1407 else if (task->error)
1409 g_propagate_error (error, task->error);
1418 * g_task_return_pointer:
1420 * @result: (allow-none) (transfer full): the pointer result of a task
1422 * @result_destroy: (allow-none): a #GDestroyNotify function.
1424 * Sets @task's result to @result and completes the task. If @result
1425 * is not %NULL, then @result_destroy will be used to free @result if
1426 * the caller does not take ownership of it with
1427 * g_task_propagate_pointer().
1429 * "Completes the task" means that for an ordinary asynchronous task
1430 * it will either invoke the task's callback, or else queue that
1431 * callback to be invoked in the proper #GMainContext, or in the next
1432 * iteration of the current #GMainContext. For a task run via
1433 * g_task_run_in_thread() or g_task_run_in_thread_sync(), calling this
1434 * method will save @result to be returned to the caller later, but
1435 * the task will not actually be completed until the #GTaskThreadFunc
1438 * Note that since the task may be completed before returning from
1439 * g_task_return_pointer(), you cannot assume that @result is still
1440 * valid after calling this, unless you are still holding another
1446 g_task_return_pointer (GTask *task,
1448 GDestroyNotify result_destroy)
1450 g_return_if_fail (task->result_set == FALSE);
1452 task->result.pointer = result;
1453 task->result_destroy = result_destroy;
1455 g_task_return (task, G_TASK_RETURN_SUCCESS);
1459 * g_task_propagate_pointer:
1461 * @error: return location for a #GError
1463 * Gets the result of @task as a pointer, and transfers ownership
1464 * of that value to the caller.
1466 * If the task resulted in an error, or was cancelled, then this will
1467 * instead return %NULL and set @error.
1469 * Since this method transfers ownership of the return value (or
1470 * error) to the caller, you may only call it once.
1472 * Returns: (transfer full): the task result, or %NULL on error
1477 g_task_propagate_pointer (GTask *task,
1480 if (g_task_propagate_error (task, error))
1483 g_return_val_if_fail (task->result_set == TRUE, NULL);
1485 task->result_destroy = NULL;
1486 task->result_set = FALSE;
1487 return task->result.pointer;
1491 * g_task_return_int:
1493 * @result: the integer (#gssize) result of a task function.
1495 * Sets @task's result to @result and completes the task (see
1496 * g_task_return_pointer() for more discussion of exactly what this
1502 g_task_return_int (GTask *task,
1505 g_return_if_fail (task->result_set == FALSE);
1507 task->result.size = result;
1509 g_task_return (task, G_TASK_RETURN_SUCCESS);
1513 * g_task_propagate_int:
1515 * @error: return location for a #GError
1517 * Gets the result of @task as an integer (#gssize).
1519 * If the task resulted in an error, or was cancelled, then this will
1520 * instead return -1 and set @error.
1522 * Since this method transfers ownership of the return value (or
1523 * error) to the caller, you may only call it once.
1525 * Returns: the task result, or -1 on error
1530 g_task_propagate_int (GTask *task,
1533 if (g_task_propagate_error (task, error))
1536 g_return_val_if_fail (task->result_set == TRUE, -1);
1538 task->result_set = FALSE;
1539 return task->result.size;
1543 * g_task_return_boolean:
1545 * @result: the #gboolean result of a task function.
1547 * Sets @task's result to @result and completes the task (see
1548 * g_task_return_pointer() for more discussion of exactly what this
1554 g_task_return_boolean (GTask *task,
1557 g_return_if_fail (task->result_set == FALSE);
1559 task->result.boolean = result;
1561 g_task_return (task, G_TASK_RETURN_SUCCESS);
1565 * g_task_propagate_boolean:
1567 * @error: return location for a #GError
1569 * Gets the result of @task as a #gboolean.
1571 * If the task resulted in an error, or was cancelled, then this will
1572 * instead return %FALSE and set @error.
1574 * Since this method transfers ownership of the return value (or
1575 * error) to the caller, you may only call it once.
1577 * Returns: the task result, or %FALSE on error
1582 g_task_propagate_boolean (GTask *task,
1585 if (g_task_propagate_error (task, error))
1588 g_return_val_if_fail (task->result_set == TRUE, FALSE);
1590 task->result_set = FALSE;
1591 return task->result.boolean;
1595 * g_task_return_error:
1597 * @error: (transfer full): the #GError result of a task function.
1599 * Sets @task's result to @error (which @task assumes ownership of)
1600 * and completes the task (see g_task_return_pointer() for more
1601 * discussion of exactly what this means).
1603 * Note that since the task takes ownership of @error, and since the
1604 * task may be completed before returning from g_task_return_error(),
1605 * you cannot assume that @error is still valid after calling this.
1606 * Call g_error_copy() on the error if you need to keep a local copy
1609 * See also g_task_return_new_error().
1614 g_task_return_error (GTask *task,
1617 g_return_if_fail (task->result_set == FALSE);
1618 g_return_if_fail (error != NULL);
1620 task->error = error;
1622 g_task_return (task, G_TASK_RETURN_ERROR);
1626 * g_task_return_new_error:
1628 * @domain: a #GQuark.
1629 * @code: an error code.
1630 * @format: a string with format characters.
1631 * @...: a list of values to insert into @format.
1633 * Sets @task's result to a new #GError created from @domain, @code,
1634 * @format, and the remaining arguments, and completes the task (see
1635 * g_task_return_pointer() for more discussion of exactly what this
1638 * See also g_task_return_error().
1643 g_task_return_new_error (GTask *task,
1652 va_start (args, format);
1653 error = g_error_new_valist (domain, code, format, args);
1656 g_task_return_error (task, error);
1660 * g_task_return_error_if_cancelled:
1663 * Checks if @task's #GCancellable has been cancelled, and if so, sets
1664 * @task's error accordingly and completes the task (see
1665 * g_task_return_pointer() for more discussion of exactly what this
1668 * Return value: %TRUE if @task has been cancelled, %FALSE if not
1673 g_task_return_error_if_cancelled (GTask *task)
1675 GError *error = NULL;
1677 g_return_val_if_fail (task->result_set == FALSE, FALSE);
1679 if (g_cancellable_set_error_if_cancelled (task->cancellable, &error))
1681 /* We explicitly set task->error so this works even when
1682 * check-cancellable is not set.
1684 g_clear_error (&task->error);
1685 task->error = error;
1687 g_task_return (task, G_TASK_RETURN_ERROR);
1698 * Tests if @task resulted in an error.
1700 * Returns: %TRUE if the task resulted in an error, %FALSE otherwise.
1705 g_task_had_error (GTask *task)
1707 if (task->error != NULL)
1710 if (task->check_cancellable && g_cancellable_is_cancelled (task->cancellable))
1718 * @result: (type Gio.AsyncResult): A #GAsyncResult
1719 * @source_object: (allow-none) (type GObject): the source object
1720 * expected to be associated with the task
1722 * Checks that @result is a #GTask, and that @source_object is its
1723 * source object (or that @source_object is %NULL and @result has no
1724 * source object). This can be used in g_return_if_fail() checks.
1726 * Return value: %TRUE if @result and @source_object are valid, %FALSE
1732 g_task_is_valid (gpointer result,
1733 gpointer source_object)
1735 if (!G_IS_TASK (result))
1738 return G_TASK (result)->source_object == source_object;
1742 g_task_compare_priority (gconstpointer a,
1746 const GTask *ta = a;
1747 const GTask *tb = b;
1748 gboolean a_cancelled, b_cancelled;
1750 a_cancelled = (ta->check_cancellable &&
1751 g_cancellable_is_cancelled (ta->cancellable));
1752 b_cancelled = (tb->check_cancellable &&
1753 g_cancellable_is_cancelled (tb->cancellable));
1755 /* Let already-cancelled tasks finish right away */
1756 if (a_cancelled && !b_cancelled)
1758 else if (b_cancelled && !a_cancelled)
1761 /* Lower priority == run sooner == negative return value */
1762 return ta->priority - tb->priority;
1766 g_task_thread_pool_init (void)
1768 task_pool = g_thread_pool_new (g_task_thread_pool_thread, NULL,
1770 g_assert (task_pool != NULL);
1772 g_thread_pool_set_sort_function (task_pool, g_task_compare_priority, NULL);
1776 g_task_thread_pool_resort (void)
1778 g_thread_pool_set_sort_function (task_pool, g_task_compare_priority, NULL);
1782 g_task_class_init (GTaskClass *klass)
1784 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
1786 gobject_class->finalize = g_task_finalize;
1790 g_task_get_user_data (GAsyncResult *res)
1792 return G_TASK (res)->callback_data;
1796 g_task_is_tagged (GAsyncResult *res,
1797 gpointer source_tag)
1799 return G_TASK (res)->source_tag == source_tag;
1803 g_task_async_result_iface_init (GAsyncResultIface *iface)
1805 iface->get_user_data = g_task_get_user_data;
1806 iface->get_source_object = g_task_ref_source_object;
1807 iface->is_tagged = g_task_is_tagged;