If a gio.task.Task has been constructed and its callback set, it is an error to
not call g_task_return_*() on it. GLib will warn at runtime if this happens
(since 2.76).
when starting a new subtask, so you don’t have to keep track
of them yourself. gio.task.Task.attachSource simplifies the case
of waiting for a source to fire (automatically using the correct
glib.main_context.MainContext and priority).
Here is an example for chained asynchronous operations:
Finally, gio.task.Task.runInThread and
gio.task.Task.runInThreadSync can be used to turn an uncancellable
operation into a cancellable one. If you call
gio.task.Task.setReturnOnCancel, passing TRUE, then if the task’s
gio.cancellable.Cancellable is cancelled, it will return control back to the
caller immediately, while allowing the task thread to continue running in the
background (and simply discarding its result when it finally does finish).
Provided that the task thread is careful about how it uses
locks and other externally-visible resources, this allows you
to make ‘GLib-friendly’ asynchronous and cancellable
synchronous variants of blocking APIs.
Cancelling a task:
1 staticvoid2 bake_cake_thread (GTask *task,
3 gpointer source_object,
4 gpointer task_data,
5 GCancellable *cancellable)
6 {
7 Baker *self = source_object;
8 CakeData *cake_data = task_data;
9 Cake *cake;
10 GError *error = NULL;
11 12 cake = bake_cake (baker, cake_data->radius, cake_data->flavor,
13 cake_data->frosting, cake_data->message,
14 &error);
15 if (error)
16 {
17 g_task_return_error (task, error);
18 return;
19 }
20 21 // If the task has already been cancelled, then we don’t want to add22 // the cake to the cake cache. Likewise, we don’t want to have the23 // task get cancelled in the middle of updating the cache.24 // g_task_set_return_on_cancel() will return %TRUE here if it managed25 // to disable return-on-cancel, or %FALSE if the task was cancelled26 // before it could.27 if (g_task_set_return_on_cancel (task, FALSE))
28 {
29 // If the caller cancels at this point, their30 // GAsyncReadyCallback won’t be invoked until we return,31 // so we don’t have to worry that this code will run at32 // the same time as that code does. But if there were33 // other functions that might look at the cake cache,34 // then we’d probably need a GMutex here as well.35 baker_add_cake_to_cache (baker, cake);
36 g_task_return_pointer (task, cake, g_object_unref);
37 }
38 }
39 40 void41 baker_bake_cake_async (Baker *self,
42 guint radius,
43 CakeFlavor flavor,
44 CakeFrostingType frosting,
45 constchar *message,
46 GCancellable *cancellable,
47 GAsyncReadyCallback callback,
48 gpointer user_data)
49 {
50 CakeData *cake_data;
51 GTask *task;
52 53 cake_data = g_slice_new (CakeData);
54 55 ...
56 57 task = g_task_new (self, cancellable, callback, user_data);
58 g_task_set_task_data (task, cake_data, (GDestroyNotify) cake_data_free);
59 g_task_set_return_on_cancel (task, TRUE);
60 g_task_run_in_thread (task, bake_cake_thread);
61 }
62 63 Cake *
64 baker_bake_cake_sync (Baker *self,
65 guint radius,
66 CakeFlavor flavor,
67 CakeFrostingType frosting,
68 constchar *message,
69 GCancellable *cancellable,
70 GError **error)
71 {
72 CakeData *cake_data;
73 GTask *task;
74 Cake *cake;
75 76 cake_data = g_slice_new (CakeData);
77 78 ...
79 80 task = g_task_new (self, cancellable, NULL, NULL);
81 g_task_set_task_data (task, cake_data, (GDestroyNotify) cake_data_free);
82 g_task_set_return_on_cancel (task, TRUE);
83 g_task_run_in_thread_sync (task, bake_cake_thread);
84 85 cake = g_task_propagate_pointer (task, error);
86 g_object_unref (task);
87 return cake;
88 }
The ‘return’ methods (eg, gio.task.Task.returnPointer)
automatically cause the task to be ‘completed’ as well, and
there is no need to worry about the ‘complete’ vs ‘complete in idle’
distinction. (gio.task.Task automatically figures out
whether the task’s callback can be invoked directly, or
if it needs to be sent to another glib.main_context.MainContext, or delayed
until the next iteration of the current glib.main_context.MainContext.)
Due to some infelicities in the API design, there is a
thread-safety concern that users of gio.task.Task have to be aware of:
If the main thread drops its last reference to the source object
or the task data before the task is finalized, then the finalizers
of these objects may be called on the worker thread.
This is a problem if the finalizers use non-threadsafe API, and
can lead to hard-to-debug crashes. Possible workarounds include:
Clear task data in a signal handler for notify::completed
Keep iterating a main context in the main thread and defer
dropping the reference to the source object to that main
context when the task is finalized
A gio.task.Task represents and manages a cancellable ‘task’.
Asynchronous operations
The most common usage of gio.task.Task is as a gio.async_result.AsyncResult, to manage data during an asynchronous operation. You call gio.task.Task.new_ in the ‘start’ method, followed by gio.task.Task.setTaskData and the like if you need to keep some additional data associated with the task, and then pass the task object around through your asynchronous operation. Eventually, you will call a method such as gio.task.Task.returnPointer or gio.task.Task.returnError, which will save the value you give it and then invoke the task’s callback function in the thread-default main context (see glib.main_context.MainContext.pushThreadDefault) where it was created (waiting until the next iteration of the main loop first, if necessary). The caller will pass the gio.task.Task back to the operation’s finish function (as a gio.async_result.AsyncResult), and you can use gio.task.Task.propagatePointer or the like to extract the return value.
Using gio.task.Task requires the thread-default glib.main_context.MainContext from when the gio.task.Task was constructed to be running at least until the task has completed and its data has been freed.
If a gio.task.Task has been constructed and its callback set, it is an error to not call g_task_return_*() on it. GLib will warn at runtime if this happens (since 2.76).
Here is an example for using gio.task.Task as a gio.async_result.AsyncResult:
Chained asynchronous operations
gio.task.Task also tries to simplify asynchronous operations that internally chain together several smaller asynchronous operations. gio.task.Task.getCancellable, gio.task.Task.getContext, and gio.task.Task.getPriority allow you to get back the task’s gio.cancellable.Cancellable, glib.main_context.MainContext, and I/O priority
when starting a new subtask, so you don’t have to keep track of them yourself. gio.task.Task.attachSource simplifies the case of waiting for a source to fire (automatically using the correct glib.main_context.MainContext and priority).
Here is an example for chained asynchronous operations:
Asynchronous operations from synchronous ones
You can use gio.task.Task.runInThread to turn a synchronous operation into an asynchronous one, by running it in a thread. When it completes, the result will be dispatched to the thread-default main context (see glib.main_context.MainContext.pushThreadDefault) where the gio.task.Task was created.
Running a task in a thread:
Adding cancellability to uncancellable tasks
Finally, gio.task.Task.runInThread and gio.task.Task.runInThreadSync can be used to turn an uncancellable operation into a cancellable one. If you call gio.task.Task.setReturnOnCancel, passing TRUE, then if the task’s gio.cancellable.Cancellable is cancelled, it will return control back to the caller immediately, while allowing the task thread to continue running in the background (and simply discarding its result when it finally does finish). Provided that the task thread is careful about how it uses locks and other externally-visible resources, this allows you to make ‘GLib-friendly’ asynchronous and cancellable synchronous variants of blocking APIs.
Cancelling a task:
Porting from gio.simple_async_result.SimpleAsyncResult
gio.task.Task’s API attempts to be simpler than gio.simple_async_result.SimpleAsyncResult’s in several ways:
Thread-safety considerations
Due to some infelicities in the API design, there is a thread-safety concern that users of gio.task.Task have to be aware of:
If the main thread drops its last reference to the source object or the task data before the task is finalized, then the finalizers of these objects may be called on the worker thread.
This is a problem if the finalizers use non-threadsafe API, and can lead to hard-to-debug crashes. Possible workarounds include: