Unstructured Concurrency

Is there a way to create a child task instance, run in a way that the parent task doesn't have to wait for the child task instance to finish execution in order to continue execution :thinking:

See Task.init(priority:operation:)

Task {
    // go!
}

According to the documentation, all parent tasks must wait for every child tasks to finish before exiting.

You’re looking for Task.detached

That's a bit different from your original post:

Task.init won't block the parent until all the children are complete. The parent task will resume doing its thing. It just happens that it'll hang around until the child tasks are also done.

If you truly need a top-level task, Task.detached will do that, as Frederick pointed out

Something similar to Golang concurrency pattern where the main goroutine exits without waiting for any child goroutine.

package main

import ( "fmt" ) 

func main() {  
  go func() { 
     fmt.Println("this shouldnt be printed")
   }() 
  fmt.Println("Program exits here") 
}

The output is
Program exits here

Whereas in Swift

import Foundation 
 
Task.init { 
   print("this shouldnt be printed") 
} 
print("Program exits here")

The output is

Program exits here 
this shouldnt be printed //problem 

Both those examples are racy; Maybe you'll get both things printed, maybe not.

I don't think you have any guarantees if that "this shouldnt be printed" won't be printed; you just happen to have "luck" with scheduling and it didn't. For all intents and purposes a goroutine is concurrent and can run at any time, including in parallel with the rest of your main function.


Back to the question to be precise in the answer though:

  • Can you create a child task without waiting? No. They're structured concurrency and MUST be awaited on by design.
  • Can you create a task without waiting on it? Sure, that's the Task.init and Task.detached APIs people have linked above.
    • These are not "child tasks" and therefore the documentation is right that "all parent tasks must wait for every child tasks to finish before exiting."
7 Likes

Thanks for the clarifications

2 Likes