Reputation: 6065
I'm relatively new to programming in Swift for iOS. I was wondering if I do:
for n in 1...10 {
DispatchQueue.global(qos: .background).async {
sleep(5)
print("Hello world!")
}
}
Will this spawn 10
more background threads that will immedietly start working on my task?
Or will there ever only be 1
background thread and I will have just enqueued 10
things to do?
Upvotes: 2
Views: 2271
Reputation: 19884
From the DispatchQueue docs:
Work submitted to dispatch queues executes on a pool of threads managed by the system. Except for the dispatch queue representing your app's main thread, the system makes no guarantees about which thread it uses to execute a task.
When a task scheduled by a concurrent dispatch queue blocks a thread, the system creates additional threads to run other queued concurrent tasks.
The system may use one of the existing threads, or it may create a new one. No guarantees that two work items executed on the same dispatch queue will be executed on the same thread (unless it's the main queue).
Upvotes: 4
Reputation: 758
You are creating 10 tasks but the order is not guaranteed. Global returns a concurrent queue so the tasks are executed maybe at the same time maybe out of order or maybe in order. Additionally, you are in no control of the actual threads. The system uses the threads available; so if task 9 finished first, then task 10 may get the thread that task 9 had. Dispatch Apis were meant to take a lot of thread work away from the programmer. In fact even on a serial queue you couldn't guarantee the threads used by the system here. The main queue guarantees the thread, but that's the only way I know of. As for the number of threads working, the system will decide, in this case with a low priority to do as many at once as it can. (.background)
Upvotes: 2