In my code, I use a for-loop to dispatch concurrent tasks to the global dispatch queue like this:
for collectionMember in myCollection {
DispatchQueue.global(qos: .default).async {
// do stuff here with collectionMember and store in variable "result"
DispatchQueue.main.async {
// code using variable "result" that must be executed serially on main thread
// because accesses shared resources
}
}
I'm new to the whole Grand Central Dispatch thing and I'm worried that when the different concurrent threads try to schedule blocks on the main DispatchQueue, there will be some memory problems as they both access the main DispatchQueue.
What I want to happen is for the concurrent threads to add a block to the main DispatchQueue on their completion, without thread safety issues.
Do I have to use a lock around the block where I dispatch code to the main DispatchQueue, or is scheduling a block thread safe?
Lastly, if I have any errors or there's a simpler way to solve this problem let me know. Thanks!
No need for locks. The main queue is a lock! That's the whole point (well, a lot of the point). It is a serial queue; nothing can start executing on the main queue as long as something else is already executing. There is no concurrency within the main thread. What you're doing is exactly right; just be aware that you may be lining up a whole bunch of blocks to be executed on the main thread, one at a time. But that's not an issue unless here are a heck of a lot of them.