Does anyone know, in the new Swift async/await
stuff, is there any difference between TaskGroup async
and spawn
, or are they pure synonyms? (If they are synonyms, I rather like spawn
better. async
looks like we're opening an async
block, and that's not what we're doing at all.)
https://developer.apple.com/documentation/swift/taskgroup/3814850-async
https://developer.apple.com/documentation/swift/taskgroup/3814884-spawn
All child tasks added to a task group start running automatically and concurrently. We cannot control when a child task finishes its execution. Therefore, we should not use a task group if we want the child tasks to finish in a specific order. A task group only returns when all of its child tasks finish their execution.
Apple introduced task groups in Swift 5.5 as one of the essential parts in the Swift concurrency framework. As the name implies, a task group is a collection of child tasks that run concurrently, and it only returns when all of its child tasks finish executing.
A group that contains dynamically created child tasks. To create a task group, call the withTaskGroup (of:returning:body:) method. Don’t use a task group from outside the task where you created it.
As the name implies, a task group is a collection of child tasks that run concurrently, and it only returns when all of its child tasks finish executing. In this article, I would like to show you how to create a task group, add child tasks to a task group, and gather results from all the child tasks.
SE-0304, tells us that spawn
was renamed async
as part of the second review:
TaskGroup.spawn
andTaskGroup.spawnUnlessCancelled
have been renamed toTaskGroup.async
andTaskGroup.asyncUnlessCancelled
which are to be their final names. This aligns the naming with the renamedasync let
as the word signifying creation of a child task.
The portion in italics has subsequently been removed and the third review has renamed it again:
- renamed
TaskGroup.async
andTaskGroup.asyncUnlessCancelled
toTaskGroup.addTask
andTaskGroup.addTaskUnlessCancelled
. The fundamental behavior here is that we're adding a task to the group. add by itself does not suffice, because we aren't adding a value (accessible vianext()
), we are adding a task whose value will be accessible vianext()
. It also parallels the use ofTask { ... }
to create top-level tasks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With