Skip to content

Instantly share code, notes, and snippets.

@radianttap
Created November 17, 2024 12:49
Show Gist options
  • Save radianttap/7d0206b48765bbbcd6a51c849a2ff3d5 to your computer and use it in GitHub Desktop.
Save radianttap/7d0206b48765bbbcd6a51c849a2ff3d5 to your computer and use it in GitHub Desktop.
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)
}
}
@radianttap
Copy link
Author

radianttap commented Nov 17, 2024

How to use?

Here's property declaration:

private let currencyCode: LegacyMutex<String> = .init("CHF")

Reading the value:

let cc = self.currencyCode.withLock{ $0 }

Update the value:

currencyCode.withLock {
	$0 = "RSD"
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment