Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于 os_unfair_lock 一文中的问题 #4

Open
notcome opened this issue Mar 30, 2022 · 0 comments
Open

关于 os_unfair_lock 一文中的问题 #4

notcome opened this issue Mar 30, 2022 · 0 comments

Comments

@notcome
Copy link

notcome commented Mar 30, 2022

文章在此

在 Swift 中,对类的成员直接用 &member 是不安全的,Apple 工程师在 Apple Developer 论坛里有提过

简单来说 Swift 可能会把

class AtomicCounter {
    var count: Int32 = 0
    func increment() {
        OSAtomicAdd32(1, &count)
    }
}

展开成

class AtomicCounter {
    var count: Int32 = 0
    func increment() {
        var tmp = count
        OSAtomicAdd32(1, &tmp)
        count = tmp
    }
}

如果改成 os_unfair_lock,就有可能每次传给系统一个临时变量在栈上的地址,而内核是根据内存地址来鉴别锁的。

若要安全使用,必须使用指针(UnsafePointer 家族)手工分配一个地址,初始化,并在 deinit 里记得释放。这样会造成一次额外的内存寻址……之前 Swift 论坛上有标准库的人(@lorentey)在推这个问题的解决方案,但是似乎没有下文了。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant