- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
@guaranteed 属性在 swift 中有什么作用?我在这个 blog post 中看到过它的使用但无法理解。
这是帖子的摘录,我指的是。
We can force the compiler to avoid these retains and releases by making the function an extension on PThreadMutex, rather than a free function:
extension PThreadMutex {
private func sync<R>(execute: () throws -> R) rethrows -> R {
pthread_mutex_lock(&m)
defer { pthread_mutex_unlock(&m) }
return try execute()
}
}This forces Swift to treat the
self
parameter as@guaranteed
, eliminating retain/release overhead and we’re finally down to the baseline 0.264 seconds.
最佳答案
@guaranteed
不是 Swift 本身可用的属性,它实际上是一个 SIL (Swift 中间语言)属性——定义函数参数内存管理约定。
The three possible conventions参数传递是:
unowned – 调用者或被调用者均未断言传递值的所有权,但保证在调用时有效(除非被调用者采取措施使其无效) .
owned – 被调用方拥有该值的所有权。调用者将在传递值之前保留它,然后被调用者有责任在完成后释放它。
guaranteed – 调用者断言值的所有权,允许被调用者保证它在调用时有效。
在您提到的帖子中,sync(mutex:execute:)
最初被定义为一个全局函数,默认情况下(AFAIK)将使用 owned 约定它的参数。因此,传递给 mutex
参数的值在传递给函数之前将由调用者保留,然后在完成后释放。
但是,如果传递给函数的值的生命周期超出了函数调用的范围(互斥锁很可能就是这种情况),则拥有约定的这种保留/释放开销是不必要的。正如帖子所观察到的,即使在内联调用之后,编译器也不会消除这种保留/释放开销。
因此,如前所述,解决方案是将 mutex:
参数视为保证,这将允许编译器消除开销,就好像互斥量已经存在一样由调用者保留,那么就不需要任何进一步的保留来保证它在 sync
调用期间存在。
如帖子所述,实现此目的的方法是使 sync
成为 PThreadMutex
的实例方法。这是因为,作为 Joe Groff says in this mailing list discussion ,从 Swift 2 开始,实例方法将保证 self
参数。
关于swift - Swift 中的@guaranteed 属性有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39839746/
今天有小伙伴给我留言问到,try{...}catch(){...}是什么意思?它用来干什么? 简单的说 他们是用来捕获异常的 下面我们通过一个例子来详细讲解下
我正在努力提高网站的可访问性,但我不知道如何在页脚中标记社交媒体链接列表。这些链接指向我在 facecook、twitter 等上的帐户。我不想用 role="navigation" 标记这些链接,因
说现在是 6 点,我有一个 Timer 并在 10 点安排了一个 TimerTask。之后,System DateTime 被其他服务(例如 ntp)调整为 9 点钟。我仍然希望我的 TimerTas
就目前而言,这个问题不适合我们的问答形式。我们希望答案得到事实、引用资料或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visit the
我就废话不多说了,大家还是直接看代码吧~ ? 1
Maven系列1 1.什么是Maven? Maven是一个项目管理工具,它包含了一个对象模型。一组标准集合,一个依赖管理系统。和用来运行定义在生命周期阶段中插件目标和逻辑。 核心功能 Mav
我是一名优秀的程序员,十分优秀!