[swift-users] Bool type and reading and writing operation atomicity

Joe Groff jgroff at apple.com
Tue Jan 17 12:31:52 CST 2017


> On Jan 16, 2017, at 3:27 AM, Dale Myers via swift-users <swift-users at swift.org> wrote:
> 
> Put simply, are reading and writing to Bools both atomic operations in Swift (3)?
> 
> Obviously, something reading and then assigning assuming the value doesn't change between is not correct, but would something like the following be fine: 
> 
>    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")
>        }
>    }
> 
> 
> I understand that in thread 2, the value of myBool can change between the check and the print statements, but that's fine. What I want to confirm for my team is that `myBool` can never be in some weird "third" state? 
> 
> From what I can tell, behind the scenes, Bool uses a Builtin.Int1 for storage. I can't find the definition for this type anywhere so I can't check what it is really doing. My assumption is that it uses something like a C++ unsigned char behind the scenes, which would be fine with the above code on x86 and ARM as far as I'm aware. 
> 
> Can someone help me figure out if I'm right or wrong in my assumptions?

Nothing in Swift is formally atomic. You'll need to use external APIs that provide atomic operations, such as OSAtomic* on Apple platforms, with raw memory if you need to do that sort of thing in Swift today.

If you naively ported this code to C or C++, it would also formally have a data race, since unless `myBool` is std::atomic (C++) or _Atomic (C11), the compiler will assume that `myBool` is not concurrently accessed and emit nonatomic loads/stores or optimize accordingly. When Swift does gain proper support for atomics, it will almost certainly be something you have to opt in to as well.

-Joe


More information about the swift-users mailing list