Skip to content

Instantly share code, notes, and snippets.

@patka817
Created October 1, 2020 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save patka817/620585c58bedf561e8ebefdf94b77367 to your computer and use it in GitHub Desktop.
Save patka817/620585c58bedf561e8ebefdf94b77367 to your computer and use it in GitHub Desktop.
Wrapper class with a simple API around a recursive pthread_mutex_t
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