3

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

Dale Myers
  • 2,703
  • 3
  • 26
  • 48

2 Answers2

4

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.

Dale Myers
  • 2,703
  • 3
  • 26
  • 48
3

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.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • 2
    Yes that's fine. What I'm trying to prove is that there is no mysterious third state that the bool can be in in Swift. I'm trying to check that it will eventually print "Was set to true" and it will never result in a crash. – Dale Myers Jan 13 '17 at 17:23
  • Granted, I don't know the answer to that one. Swift is open source so I suppose you could comb the code trying to figure it out. I guess my response in general is that if you are deliberately doing to do wanton uncontrolled data sharing across threads, all bets are off. Isn't it simpler to just follow the "Don't Do That" rule than to probe this kind of corner? – matt Jan 13 '17 at 17:31