GTask

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:

1 typedef struct {
2   CakeFrostingType frosting;
3   char *message;
4 } DecorationData;
5 
6 static void
7 decoration_data_free (DecorationData *decoration)
8 {
9   g_free (decoration->message);
10   g_slice_free (DecorationData, decoration);
11 }
12 
13 static void
14 baked_cb (Cake     *cake,
15           gpointer  user_data)
16 {
17   GTask *task = user_data;
18   DecorationData *decoration = g_task_get_task_data (task);
19   GError *error = NULL;
20 
21   if (cake == NULL)
22     {
23       g_task_return_new_error (task, BAKER_ERROR, BAKER_ERROR_NO_FLOUR,
24                                "Go to the supermarket");
25       g_object_unref (task);
26       return;
27     }
28 
29   if (!cake_decorate (cake, decoration->frosting, decoration->message, &error))
30     {
31       g_object_unref (cake);
32       // g_task_return_error() takes ownership of error
33       g_task_return_error (task, error);
34       g_object_unref (task);
35       return;
36     }
37 
38   g_task_return_pointer (task, cake, g_object_unref);
39   g_object_unref (task);
40 }
41 
42 void
43 baker_bake_cake_async (Baker               *self,
44                        guint                radius,
45                        CakeFlavor           flavor,
46                        CakeFrostingType     frosting,
47                        const char          *message,
48                        GCancellable        *cancellable,
49                        GAsyncReadyCallback  callback,
50                        gpointer             user_data)
51 {
52   GTask *task;
53   DecorationData *decoration;
54   Cake  *cake;
55 
56   task = g_task_new (self, cancellable, callback, user_data);
57   if (radius < 3)
58     {
59       g_task_return_new_error (task, BAKER_ERROR, BAKER_ERROR_TOO_SMALL,
60                                "%ucm radius cakes are silly",
61                                radius);
62       g_object_unref (task);
63       return;
64     }
65 
66   cake = _baker_get_cached_cake (self, radius, flavor, frosting, message);
67   if (cake != NULL)
68     {
69       // _baker_get_cached_cake() returns a reffed cake
70       g_task_return_pointer (task, cake, g_object_unref);
71       g_object_unref (task);
72       return;
73     }
74 
75   decoration = g_slice_new (DecorationData);
76   decoration->frosting = frosting;
77   decoration->message = g_strdup (message);
78   g_task_set_task_data (task, decoration, (GDestroyNotify) decoration_data_free);
79 
80   _baker_begin_cake (self, radius, flavor, cancellable, baked_cb, task);
81 }
82 
83 Cake *
84 baker_bake_cake_finish (Baker         *self,
85                         GAsyncResult  *result,
86                         GError       **error)
87 {
88   g_return_val_if_fail (g_task_is_valid (result, self), NULL);
89 
90   return g_task_propagate_pointer (G_TASK (result), error);
91 }

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:

1 typedef struct {
2   Cake *cake;
3   CakeFrostingType frosting;
4   char *message;
5 } BakingData;
6 
7 static void
8 decoration_data_free (BakingData *bd)
9 {
10   if (bd->cake)
11     g_object_unref (bd->cake);
12   g_free (bd->message);
13   g_slice_free (BakingData, bd);
14 }
15 
16 static void
17 decorated_cb (Cake         *cake,
18               GAsyncResult *result,
19               gpointer      user_data)
20 {
21   GTask *task = user_data;
22   GError *error = NULL;
23 
24   if (!cake_decorate_finish (cake, result, &error))
25     {
26       g_object_unref (cake);
27       g_task_return_error (task, error);
28       g_object_unref (task);
29       return;
30     }
31 
32   // baking_data_free() will drop its ref on the cake, so we have to
33   // take another here to give to the caller.
34   g_task_return_pointer (task, g_object_ref (cake), g_object_unref);
35   g_object_unref (task);
36 }
37 
38 static gboolean
39 decorator_ready (gpointer user_data)
40 {
41   GTask *task = user_data;
42   BakingData *bd = g_task_get_task_data (task);
43 
44   cake_decorate_async (bd->cake, bd->frosting, bd->message,
45                        g_task_get_cancellable (task),
46                        decorated_cb, task);
47 
48   return G_SOURCE_REMOVE;
49 }
50 
51 static void
52 baked_cb (Cake     *cake,
53           gpointer  user_data)
54 {
55   GTask *task = user_data;
56   BakingData *bd = g_task_get_task_data (task);
57   GError *error = NULL;
58 
59   if (cake == NULL)
60     {
61       g_task_return_new_error (task, BAKER_ERROR, BAKER_ERROR_NO_FLOUR,
62                                "Go to the supermarket");
63       g_object_unref (task);
64       return;
65     }
66 
67   bd->cake = cake;
68 
69   // Bail out now if the user has already cancelled
70   if (g_task_return_error_if_cancelled (task))
71     {
72       g_object_unref (task);
73       return;
74     }
75 
76   if (cake_decorator_available (cake))
77     decorator_ready (task);
78   else
79     {
80       GSource *source;
81 
82       source = cake_decorator_wait_source_new (cake);
83       // Attach @source to @task’s GMainContext and have it call
84       // decorator_ready() when it is ready.
85       g_task_attach_source (task, source, decorator_ready);
86       g_source_unref (source);
87     }
88 }
89 
90 void
91 baker_bake_cake_async (Baker               *self,
92                        guint                radius,
93                        CakeFlavor           flavor,
94                        CakeFrostingType     frosting,
95                        const char          *message,
96                        gint                 priority,
97                        GCancellable        *cancellable,
98                        GAsyncReadyCallback  callback,
99                        gpointer             user_data)
100 {
101   GTask *task;
102   BakingData *bd;
103 
104   task = g_task_new (self, cancellable, callback, user_data);
105   g_task_set_priority (task, priority);
106 
107   bd = g_slice_new0 (BakingData);
108   bd->frosting = frosting;
109   bd->message = g_strdup (message);
110   g_task_set_task_data (task, bd, (GDestroyNotify) baking_data_free);
111 
112   _baker_begin_cake (self, radius, flavor, cancellable, baked_cb, task);
113 }
114 
115 Cake *
116 baker_bake_cake_finish (Baker         *self,
117                         GAsyncResult  *result,
118                         GError       **error)
119 {
120   g_return_val_if_fail (g_task_is_valid (result, self), NULL);
121 
122   return g_task_propagate_pointer (G_TASK (result), error);
123 }

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:

1 typedef struct {
2   guint radius;
3   CakeFlavor flavor;
4   CakeFrostingType frosting;
5   char *message;
6 } CakeData;
7 
8 static void
9 cake_data_free (CakeData *cake_data)
10 {
11   g_free (cake_data->message);
12   g_slice_free (CakeData, cake_data);
13 }
14 
15 static void
16 bake_cake_thread (GTask         *task,
17                   gpointer       source_object,
18                   gpointer       task_data,
19                   GCancellable  *cancellable)
20 {
21   Baker *self = source_object;
22   CakeData *cake_data = task_data;
23   Cake *cake;
24   GError *error = NULL;
25 
26   cake = bake_cake (baker, cake_data->radius, cake_data->flavor,
27                     cake_data->frosting, cake_data->message,
28                     cancellable, &error);
29   if (cake)
30     g_task_return_pointer (task, cake, g_object_unref);
31   else
32     g_task_return_error (task, error);
33 }
34 
35 void
36 baker_bake_cake_async (Baker               *self,
37                        guint                radius,
38                        CakeFlavor           flavor,
39                        CakeFrostingType     frosting,
40                        const char          *message,
41                        GCancellable        *cancellable,
42                        GAsyncReadyCallback  callback,
43                        gpointer             user_data)
44 {
45   CakeData *cake_data;
46   GTask *task;
47 
48   cake_data = g_slice_new (CakeData);
49   cake_data->radius = radius;
50   cake_data->flavor = flavor;
51   cake_data->frosting = frosting;
52   cake_data->message = g_strdup (message);
53   task = g_task_new (self, cancellable, callback, user_data);
54   g_task_set_task_data (task, cake_data, (GDestroyNotify) cake_data_free);
55   g_task_run_in_thread (task, bake_cake_thread);
56   g_object_unref (task);
57 }
58 
59 Cake *
60 baker_bake_cake_finish (Baker         *self,
61                         GAsyncResult  *result,
62                         GError       **error)
63 {
64   g_return_val_if_fail (g_task_is_valid (result, self), NULL);
65 
66   return g_task_propagate_pointer (G_TASK (result), error);
67 }

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:

1 static void
2 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 add
22   // the cake to the cake cache. Likewise, we don’t  want to have the
23   // task get cancelled in the middle of updating the cache.
24   // g_task_set_return_on_cancel() will return %TRUE here if it managed
25   // to disable return-on-cancel, or %FALSE if the task was cancelled
26   // before it could.
27   if (g_task_set_return_on_cancel (task, FALSE))
28     {
29       // If the caller cancels at this point, their
30       // GAsyncReadyCallback won’t be invoked until we return,
31       // so we don’t have to worry that this code will run at
32       // the same time as that code does. But if there were
33       // 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 void
41 baker_bake_cake_async (Baker               *self,
42                        guint                radius,
43                        CakeFlavor           flavor,
44                        CakeFrostingType     frosting,
45                        const char          *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                       const char          *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 }

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:

  • 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
struct GTask