Created
August 18, 2020 08:05
-
-
Save achernoprudov/21f4e71c9bb765a40233cfe27038504f to your computer and use it in GitHub Desktop.
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
public class ReadWriteLock { | |
// MARK: - Instance variables | |
private var lock = pthread_rwlock_t() | |
private var attr = pthread_rwlockattr_t() | |
// MARK: - Public | |
public init() { | |
pthread_rwlockattr_init(&attr) | |
pthread_rwlock_init(&lock, &attr) | |
} | |
deinit { | |
pthread_rwlock_destroy(&lock) | |
pthread_rwlockattr_destroy(&attr) | |
} | |
public func readLock() { | |
pthread_rwlock_rdlock(&lock) | |
} | |
public func writeLock() { | |
pthread_rwlock_wrlock(&lock) | |
} | |
public func unlock() { | |
pthread_rwlock_unlock(&lock) | |
} | |
} | |
// MARK: - Functional extension | |
public extension ReadWriteLock { | |
func writeLock(closure: () -> Void) { | |
writeLock() | |
closure() | |
unlock() | |
} | |
func writeLockFetch<T>(closure: () -> T) -> T { | |
writeLock() | |
defer { | |
unlock() | |
} | |
return closure() | |
} | |
func readLock(closure: () -> Void) { | |
readLock() | |
closure() | |
unlock() | |
} | |
func readLockFetch<T>(closure: () -> T) -> T { | |
readLock() | |
defer { | |
unlock() | |
} | |
return closure() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment