Adding items to Swift array across multiple threads causing issues (because arrays aren't thread safe) - how do I get around that?

后端 未结 5 1038
南笙
南笙 2020-11-28 12:12

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         


        
5条回答
  •  南笙
    南笙 (楼主)
    2020-11-28 12:47

    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

提交回复
热议问题