简体   繁体   中英

Swift - Is dispatching to the main queue enough to make a var thread safe?

When it comes to synchronization solutions, I know there are a lot of stuff I can use in order to make a var thread safe. But my question is this:

Since the main queue is serial, is dispatching to it enough to make a var safe for async reading/writing operations?

Let's say I have an Int array:

var myArr: [Int] = []

Whenever I need to update it i use the main queue:

let newVal = 123

dispatch_async(dispatch_get_main_queue(), { () -> Void in
    myArr.append(newVal)
})

And whenever I need to read from it:

dispatch_async(dispatch_get_main_queue(), { () -> Void in
    println(myArr.count)
})

Will that be enough to make myArr thread safe?

Yes, that is enough. As long as you read and write from the same serial queue you are safe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM