-
Notifications
You must be signed in to change notification settings - Fork 61
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Mutex for Kotlin Common #494
base: master
Are you sure you want to change the base?
Conversation
bbrockbernd
commented
Dec 10, 2024
- Fair mutex for Kotlin/Common
- Thread parking based on futex/ulock/WaitOnAddress
- Thread parking based on pthread_cond and pthread_mutex
… and prevent value capturing in block() by defining contract. Fix expected constructor
pthread_mutex_destroy(&pc->mutex); | ||
pthread_cond_destroy(&pc->cond); | ||
free(pc); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
cinterop, while useful, should be avoided in Kotlin libraries, because libraries containing cinterop declarations get compiled to artifacts containing LLVM bitcode, whose representation can change across versions of the Kotlin compiler in incompatible ways: https://github.com/Kotlin/kotlinx-atomicfu/pull/440/files
Fortunately, it seems like everything here can be rewritten in pure Kotlin/Native, without cinterop.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Alright that is good to know!
The reason why I used cinterop is because the provided posix library in kotlin/native is slightly different over different platforms.
For instance, on windows you use pthread_cond_tVar
and on linux pthread_cond_t
. Also the pthread_cond_init
function is not available in at the nativeMain sourceset.
So instead of having to duplicate this over the platforms, I thought this would be the cleanest solution.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yep, the function API differences are why https://github.com/Kotlin/kotlinx-atomicfu/pull/440/files had to duplicate code and couldn't write it in nativeMain. That's a pity, but what can you do.
actual fun isLocked(): Boolean = locked | ||
actual fun tryLock(): Boolean = true | ||
actual fun lock(): Unit { locked = true } | ||
actual fun unlock(): Unit { locked = false } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Since the mutex is reentrant, you need to maintain a counter instead so the deepest unlock
call does not release the mutex.