-1
let conc = DispatchQueue(label: "test", attributes: .concurrent)
conc.sync {
    conc.async {
        var x = 1
        for n in 1...100000 {
            x += n
        }
        print(2)
    }

    var x = 1
    for n in 1...100000 {
        x += n
    }
    print(3)
}
print(1)

Always print 3, 1, 2. Why? In my opinion it should print 1, 3, 2. Because 1 and 3 are at different threads and in this code tasks for 1, 2 and 3 goes simultaneously. Is there only one thread in Playground and in real app it would print 1, 3, 2? Could somebody explain please.

Nike Kov
  • 12,630
  • 8
  • 75
  • 122

1 Answers1

2

First of all, if you'd like to see different behaviour it would be better to run the test several times. As it is, the async part be delayed by thread creation or other initialisation.

let conc = DispatchQueue(label: "test", attributes: .concurrent)
for _ in 0...100 {
    conc.sync {
        ...
        print(3)
    }
    print(1)
}

Now you would see that 2 can be printed any time, but 3 is always printed before 1. That is because you print 3 in the sync block and the call to sync would not finish before finishing the scheduled block, also it tries to run the scheduled block on the current thread whenever possible (unless you are scheduling to Main).

As for the question itself, there are as many threads as necessary and possible within system limits.

Konstantin Oznobihin
  • 5,234
  • 24
  • 31
  • So the DispatchQueue not necessarily create new thread? In my example (unlike yours) there is a time-consuming task that holds `print(3)` for 8 seconds. And after that it prints `3` and then `1`. I can't understand why DispatchQueue not creating parallel thread for printing `1` while big task is processing. – Nike Kov May 20 '21 at 15:55
  • @NikKov I just omitted the rest of the code for conciseness. It doesn't matter whether DispatchQueue creates another thread because anyway sync will wait until it's finished, and print(1) will be executed only after sync is finished. – Konstantin Oznobihin May 20 '21 at 21:20
  • In that case - you have a mistake. Please check the source code. – Nike Kov May 20 '21 at 23:15