Home > OS >  Multiple detached tasks are not executed at the same time
Multiple detached tasks are not executed at the same time

Time:08-02

class ViewModel: ObservableObject { }

struct ContentView: View {
    @StateObject private var model = ViewModel()

    var body: some View {
        Button("Authenticate", action: doWork)
    }

    func doWork() {
        Task.detached {
            for i in 1...10_000 {
                print("In Task 1: \(i)")
            }
        }

        Task.detached {
            for i in 1...10_000 {
                print("In Task 2: \(i)")
            }
        }
    }
}

This is the code described in enter image description here

Note, that is artificially constraining the cooperative thread pool to two tasks at a time.

On an iPhone 12 Pro Max:

enter image description here

That runs six at a time.

And on an Intel 2018 MacBook Pro:

enter image description here

So, bottom line, it does run concurrently, constrained based upon the nature of the hardware on which you run it (with the exception of the simulator, which artificially constrains it even further).


FWIW, the 10,000 print statements is not a representative example because:

  • Too many synchronizations: The print statements are synchronized across threads which can skew the results. To test concurrency, you ideally want as few synchronizations taking place as possible.

  • Not enough work on each thread: A for loop of only 10,000 iterations is not enough work to properly manifest concurrency. It is quite easy that the first task could finish before the second even starts. And even if it does start interleaving at some point, you might see a couple thousand on one task, then a couple thousand on the next, etc. Do not expect a rapid interleaving of the print statements.

For these reasons, I replaced that for loop with a calculation of pi to 9 decimal places. The idea is to have some calculation/process that is sufficiently intensive to warrant concurrency and manifest the behavior we are looking for.


Perhaps needless to say, if we experience serial behavior if we:

  • move this calculation to an actor; and
  • launch with Task { ... } rather than detached task.

enter image description here

(Note, the horizontal time scale as been compressed to fit the twenty tasks on screen at the same time.)

  • Related