Hi Swift Community!
I'm trying to understand the best practices for using GCD after watching Modernizing Grand Central Dispatch Usage and reading the discussion here and here.
So it seems like using custom serial queue will give call site an overcommited queue, which can lead to thread explosion. But we also can't directly give work item with DispatchQueue.global().async
as it can block some threads and cause GCD to create new threads for other work items.
Then the only option left is custom concurrent queue? But then it is also not recommended to use custom concurrent queue suggested in multiple resources. (And I guess it would also cause the same thread explosion issue like DispatchQueue.global().async
?)
Then looks like every approach has its limitations. If I understand correctly, here are the recommended practices.
- For light weight tasks, (e.g like just reading / write to some local variables), unfair lock is still preferred compared to GCD queues.
- Custom serial queue is still preferred whenever a queue is needed and should avoid having a long live one when possible, and numbers should be limited to avoid thread explosion.
- When the codebase has too many custom serial queues, we should use target queue hierarchy to control and throttle the work items that are submitted to the default target queue (which is default global queue).
- Only use custom concurrent queues when the benchmark result shows that using it indeed has performance benefits.
DispatchQueue.global().async
is still useful as long as the submitted items are lightweight enough and will finish very quick.
Are those the right practices to follow? Or have I missed something important in the decision making process? Thank you!