Swift变量是原子的吗? [英] Are Swift variables atomic?

查看:115
本文介绍了Swift变量是原子的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Objective-C中,您区分原子和非原子属性:

In Objective-C you have a distinction between atomic and nonatomic properties:

@property (nonatomic, strong) NSObject *nonatomicObject;
@property (atomic, strong) NSObject *atomicObject;

据我了解,您可以安全地从多个线程中读取和写入定义为原子的属性,而同时从多个线程中写入和访问非原子属性或ivars可能导致不确定的行为,包括严重的访问错误.

From my understanding you can read and write properties defined as atomic from multiple threads safely, while writing and accessing nonatomic properties or ivars from multiple threads at the same time can result in undefined behavior, including bad access errors.

因此,如果您在Swift中有这样的变量:

So if you have a variable like this in Swift:

var object: NSObject

我可以安全地并行读写此变量吗? (不考虑这样做的实际含义).

Can I read and write to this variable in parallel safely? (Without considering the actual meaning of doing this).

推荐答案

现在还处于早期阶段,因为没有可用的低级文档,但是您可以从汇编中学习. Hopper Disassembler 是一个很棒的工具.

It's very early to assume as no low-level documentation is available, but you can study from assembly. Hopper Disassembler is a great tool.

@interface ObjectiveCar : NSObject
@property (nonatomic, strong) id engine;
@property (atomic, strong) id driver;
@end

分别对非原子和原子使用objc_storeStrongobjc_setProperty_atomic,其中

Uses objc_storeStrong and objc_setProperty_atomic for nonatomic and atomic respectively, where

class SwiftCar {
    var engine : AnyObject?    
    init() {
    }
}

使用libswift_stdlib_core中的swift_retain,并且显然没有内置线程安全性.

uses swift_retain from libswift_stdlib_core and, apparently, does not have thread safety built in.

我们可以推测,稍后可能会引入其他关键字(类似于@lazy).

We can speculate that additional keywords (similar to @lazy) might be introduced later on.

更新15年7月20日:根据此

Update 07/20/15: according to this blogpost on singletons swift environment can make certain cases thread safe for you, i.e.:

class Car {
    static let sharedCar: Car = Car() // will be called inside of dispatch_once
}

private let sharedCar: Car2 = Car2() // same here
class Car2 {

}

更新16年5月25日:请留意快速发展的提案

Update 05/25/16: Keep an eye out for swift evolution proposal https://github.com/apple/swift-evolution/blob/master/proposals/0030-property-behavior-decls.md - it looks like it is going to be possible to have @atomic behavior implemented by yourself.

这篇关于Swift变量是原子的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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