Created
October 1, 2020 20:14
-
-
Save patka817/620585c58bedf561e8ebefdf94b77367 to your computer and use it in GitHub Desktop.
Wrapper class with a simple API around a recursive pthread_mutex_t
This file contains 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
final class ReentrantLock { | |
private var _lock: pthread_mutex_t | |
init() { | |
var attr = pthread_mutexattr_t() | |
pthread_mutexattr_init(&attr) | |
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) | |
self._lock = pthread_mutex_t() | |
pthread_mutex_init(&self._lock, &attr) | |
pthread_mutexattr_destroy(&attr) | |
} | |
deinit { | |
pthread_mutex_destroy(&self._lock) | |
} | |
func inLock(_ work: () throws -> Void) rethrows { | |
defer { unlock() } | |
lock() | |
try work() | |
} | |
func inLock<ReturnType>(_ work: () throws -> ReturnType) rethrows -> ReturnType { | |
defer { unlock() } | |
lock() | |
return try work() | |
} | |
func lock() { | |
pthread_mutex_lock(&_lock) | |
} | |
func unlock() { | |
pthread_mutex_unlock(&_lock) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment