Are setting and reading a Bool atomic operations in Swift?

陌路散爱 提交于 2019-12-23 20:46:27

问题


Simple as the title states. Basically, in this example, could we ever get an invalid state:

var myBool = false

// Thread 1
while true {
    if randomEvent() {
        myBool = true
    }
}

// Thread 2
while true {
    if myBool {
        print("Was set to true")
    } else {
        print("Not set")
    }
}

Could this ever crash because myBool is in some invalid state? Or is this "safe"?


回答1:


I'm not sure what you think this has to do with "thread-safe" or "atomic" or even Swift. The nature of multithreading is as follows. Whenever you say something of this form:

if myBool {
    print("Was set to true")

...you should assume that if myBool can be set on another thread, it can be set between the first line and the second. This could cause "Was set to true" to be printed even though at this moment it is false, or converse could cause it not to be printed even though at this moment it is true.




回答2:


After discussion on the Swift Users mailing list, it was confirmed that read and write of Bool values is not an atomic operation in Swift. Furthermore, the code above may be optimised by the compiler and since myBool is never set in the context of thread 2, it may optimise out the check. The only valid way to do this in Swift is to use GCD to marshall correctly, or use an OS provided locking feature.



来源:https://stackoverflow.com/questions/41639806/are-setting-and-reading-a-bool-atomic-operations-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!