在Swift中设置和读取Bool原子操作吗? [英] Are setting and reading a Bool atomic operations in Swift?

查看:81
本文介绍了在Swift中设置和读取Bool原子操作吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单如标题所示.基本上,在此示例中,我们能否获得无效状态:

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")
    }
}

这会因为myBool处于某种无效状态而崩溃吗?还是安全"?

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

推荐答案

在Swift用户邮件列表上进行讨论之后,可以确认Bool值的读写不是Swift中的原子操作.此外,上面的代码可以由编译器进行优化,并且由于从不在线程2的上下文中设置myBool,因此可以优化检查.在Swift中执行此操作的唯一有效方法是使用GCD正确编组,或使用OS提供的锁定功能.

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.

这篇关于在Swift中设置和读取Bool原子操作吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆