I want to add given blocks to an array, and then run all the blocks contained in the array, when requested. I have code similar to this:
class MyArrayBlockCl
For synchronization between threads, use dispatch_sync (not _async) and your own dispatch queue (not the global one):
class MyArrayBlockClass {
private var queue = dispatch_queue_create("andrew.myblockarrayclass", nil)
func addBlockToArray(block: () -> Void) {
dispatch_sync(queue) {
self.blocksArray.append(block)
}
}
//....
}
dispatch_sync is nice and easy to use and should be enough for your case (I use it for all my thread synchronization needs at the moment), but you can also use lower-level locks and mutexes. There is a great article by Mike Ash about different choices: Locks, Thread Safety, and Swift