Created
November 17, 2024 12:49
-
-
Save radianttap/7d0206b48765bbbcd6a51c849a2ff3d5 to your computer and use it in GitHub Desktop.
LegacyMutex implementation, per this blog post: https://medium.com/@noahlittle199/thread-safety-with-mutex-in-swift-6-575e79f14386
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
final class LegacyMutex<Wrapped>: @unchecked Sendable { | |
private var mutex = pthread_mutex_t() | |
private var wrapped: Wrapped | |
init(_ initialValue: Wrapped) { | |
pthread_mutex_init(&mutex, nil) | |
self.wrapped = initialValue | |
} | |
deinit { | |
pthread_mutex_destroy(&mutex) | |
} | |
func withLock<R>(_ body: @Sendable (inout Wrapped) throws -> R) rethrows -> R { | |
pthread_mutex_lock(&mutex) | |
defer { pthread_mutex_unlock(&mutex) } | |
return try body (&wrapped) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to use?
Here's property declaration:
Reading the value:
Update the value: