replacing os_unfair_lock with NSLock

learned that os_unfair_lock with & was quite unsafe when used within
swift. Apparently in swift, &foo in Swift means "make a copy of foo and
pass it inout to a function, then overwrite its value with whatever
the function did to it when that function returns."

And if you're using it within a struct, it's apparently even more
dangerous. because the address of self can change from call to call
— self might not even have an address, it might be contained in
registers only.

Using NSlock will be a smidge less performant, but notably more safe.
This commit is contained in:
Joe Heck 2021-05-10 11:14:04 -07:00
parent 2f32a4b928
commit 8df105aad4
1 changed files with 5 additions and 6 deletions

View File

@ -14,13 +14,12 @@ import RSCore
// * Collisions arent going to happen with feed data
private var databaseIDCache = [String: String]()
private var databaseIDCacheLock = os_unfair_lock_s()
private var databaseIDCacheLock = NSLock()
public func databaseIDWithString(_ s: String) -> String {
os_unfair_lock_lock(&databaseIDCacheLock)
defer {
os_unfair_lock_unlock(&databaseIDCacheLock)
}
databaseIdCacheLock.lock()
defer {
databaseIdCacheLock.unlock()
}
if let identifier = databaseIDCache[s] {
return identifier