Why is cancellation useful, and how are cancelled tasks supposed to clean up? (async)

When we talk about async programming, the topic of “cancellation” comes up often. My understanding is, developers want to be able to start a task, have it go do stuff, and then cancel it if it takes too long. The issue I see with this is how are tasks supposed to be able to clean up after themselves, like free the memory they allocate?

Why is cancellation a required feature for async programming?

When I look at the python standard library, they don’t give me a way to cancel a thread, why should I have a way to cancel a task? The way this is typically solved is to wait on a thread-safe condition in the task for cancellation.

I am not familiar with the exact details of how cancellation is being implemented in Zig, but from my experience with other languages that use a lot of async, such as C#, the whole point of cancellation is for allowing graceful cleanup. The task would typically be alerted that cancellation is requested, and react accordingly, such as deallocate memory, close file handles, etc.

It is understandable to draw the analogy of task cancellation with killing a thread, they are conceptually akin to each other, but are very different on a technical level. When it comes to understanding async, it is usually beneficial to not try and draw parallels with threads.

Concurrency and parallelism can feel the same in practice, but it is important to remind oneself of their distinct differences. Parallelism is hiring more workers to accomplish tasks, and concurrency is your same one-man team simply learning how to multi-task.

4 Likes

One use-case for cancellation is the happy eyeballs algorithm, which in essence will try to connect to all ip addresses given by a DNS record, and when one connection is established the rest are cancelled.

3 Likes

I noticed that Cancelled was an error, perhaps one could clean up with errdefer? Just a guess, I don’t know if it is an error at the API level of the caller of await, or for the task spawned with async

2 Likes

You are on the right track here. The cancelled task will recieve an error on the next call to a Cancelable function. This is handled with regular error handling.

1 Like