Skip to content

Instantly share code, notes, and snippets.

@yuriks
Last active September 29, 2015 22:28
Show Gist options
  • Save yuriks/cf4f50a604d129f24c98 to your computer and use it in GitHub Desktop.
Save yuriks/cf4f50a604d129f24c98 to your computer and use it in GitHub Desktop.
3DS lightweight mutex
Handle arbiter;
struct Mutex {
// 1 = unlocked
// 0 = locked
// -n = contended
s32 val = 1;
void acquire() {
while (__atomic_fetch_sub(&val, 1, __ATOMIC_ACQUIRE) != 1) {
// Block if val < 0
svcArbitrateAddress(arbiter, &val, WaitIfLessThan, 0, -1);
__atomic_fetch_add(&val, 1, __ATOMIC_RELEASE);
}
}
void release() {
if (__atomic_fetch_add(&val, 1, __ATOMIC_RELEASE) < 0) {
// Wake up 1 thread
svcArbitrateAddress(arbiter, &val, Signal, 1, -1);
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment