Are setting and reading a Bool atomic operations i

2019-07-07 07:33发布

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"?

2条回答
beautiful°
2楼-- · 2019-07-07 08:00

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.

查看更多
Deceive 欺骗
3楼-- · 2019-07-07 08:03

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.

查看更多
登录 后发表回答