Hacker News new | ask | show | jobs
by charcircuit 1083 days ago
>In regular threaded programming, cancellation is a bit more painful

No, it isn't. Nothing is stopping your threading library from implementing the same thing. It just turns out it is a bad idea to kill threads at random points in time because they may own things like locks. Or in the case of async await doing something that is thought to be atomic.

2 comments

You're describing exactly why it's painful for threads. If you only cancel co-routines at yield points (which unless you do dark magic is the only time you can cancel them) is always safe.

A co-routine that yields in the middle of an atomic operation is an oxymoron. Anything can happen before you're scheduled again.

Well each time you use the await keyword you are saying its a safe point to exit, which is more predictable than killing at random points. Holding locks across await points is an anti-pattern, and Rust at least can give a hint if you try to do that. Async/await implementations will also generally allow you to run cleanup code on cancellation (but the exact mechanism depends on the language).

In the end, its about expressing a state machine in a more concise implicit way, which is a suitable level of abstraction for most use cases.