|
| 1 | +package co.touchlab.stately.concurrency |
| 2 | + |
| 3 | +import kotlinx.cinterop.Arena |
| 4 | +import kotlinx.cinterop.alloc |
| 5 | +import kotlinx.cinterop.ptr |
| 6 | +import platform.posix.PTHREAD_MUTEX_RECURSIVE |
| 7 | +import platform.posix.pthread_mutex_destroy |
| 8 | +import platform.posix.pthread_mutex_init |
| 9 | +import platform.posix.pthread_mutex_lock |
| 10 | +import platform.posix.pthread_mutex_t |
| 11 | +import platform.posix.pthread_mutex_trylock |
| 12 | +import platform.posix.pthread_mutex_unlock |
| 13 | +import platform.posix.pthread_mutexattr_destroy |
| 14 | +import platform.posix.pthread_mutexattr_init |
| 15 | +import platform.posix.pthread_mutexattr_settype |
| 16 | +import platform.posix.pthread_mutexattr_tVar |
| 17 | +import kotlin.native.concurrent.freeze |
| 18 | + |
| 19 | +/** |
| 20 | + * A simple lock. |
| 21 | + * Implementations of this class should be re-entrant. |
| 22 | + */ |
| 23 | +actual class Lock actual constructor() { |
| 24 | + private val arena = Arena() |
| 25 | + private val attr = arena.alloc<pthread_mutexattr_tVar>() |
| 26 | + private val mutex = arena.alloc<pthread_mutex_t>() |
| 27 | + |
| 28 | + init { |
| 29 | + pthread_mutexattr_init(attr.ptr) |
| 30 | + pthread_mutexattr_settype(attr.ptr, PTHREAD_MUTEX_RECURSIVE.toInt()) |
| 31 | + pthread_mutex_init(mutex.ptr, attr.ptr) |
| 32 | + freeze() |
| 33 | + } |
| 34 | + |
| 35 | + actual fun lock() { |
| 36 | + pthread_mutex_lock(mutex.ptr) |
| 37 | + } |
| 38 | + |
| 39 | + actual fun unlock() { |
| 40 | + pthread_mutex_unlock(mutex.ptr) |
| 41 | + } |
| 42 | + |
| 43 | + actual fun tryLock(): Boolean = pthread_mutex_trylock(mutex.ptr) == 0 |
| 44 | + |
| 45 | + fun internalClose() { |
| 46 | + pthread_mutex_destroy(mutex.ptr) |
| 47 | + pthread_mutexattr_destroy(attr.ptr) |
| 48 | + arena.clear() |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +actual inline fun Lock.close() { |
| 53 | + internalClose() |
| 54 | +} |
0 commit comments