gpt4 book ai didi

swift - Swift 中的@guaranteed 属性有什么作用?

转载 作者:搜寻专家 更新时间:2023-10-31 22:30:17 26 4
gpt4 key购买 nike

@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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com