Skip to content

Instantly share code, notes, and snippets.

@kawaii-ghost
Last active June 11, 2025 00:25
Show Gist options
  • Save kawaii-ghost/978b05dc9c9c58737d96c501733bb82c to your computer and use it in GitHub Desktop.
Save kawaii-ghost/978b05dc9c9c58737d96c501733bb82c to your computer and use it in GitHub Desktop.
#include <stdint.h>
#include <threads.h>
#include <stdatomics.h>
#include <linux/futex.h> /* Definition of FUTEX_* constants */
#include <sys/syscall.h> /* Definition of SYS_* constants */
#include <unistd.h>
#include <errno.h>
static int futex(uint32_t *uaddr, int futex_op, uint32_t val, const struct timespec *timeout, uint32_t *uaddr2, uint32_t val3)
{
return syscall(SYS_futex, uaddr, futex_op, val, timeout, uaddr2, val3);
}
static int address_wait(_Atomic uint32_t *addr, uint32_t *compare)
{
if (atomic_load(addr) == *compare) {
int ret = futex(addr, FUTEX_WAIT_PRIVATE, *compare, nullptr, nullptr, 0);
if (ret == 0) {
return thrd_success;
} else {
return thrd_error;
}
} else {
return thrd_error;
}
}
static int address_timedwait(_Atomic uint32_t* addr, uint32_t *compare, const struct timespec *restrict ts)
{
if (atomic_load(addr) == *compare) {
int ret = futex(addr, FUTEX_WAIT_BITSET_PRIVATE | FUTEX_CLOCK_REALTIME, *compare, ts, nullptr, FUTEX_BITSET_MATCH_ANY);
if (ret == 0) {
return thrd_success;
} else if (ret == -1) {
if (errno == ETIMEDOUT) {
return thrd_timeout;
} else {
return thrd_error;
}
}
} else {
return thrd_success;
}
}
static int address_signal(_Atomic uint32_t *addr)
{
return futex((uint32_t *)addr, FUTEX_WAKE_BITSET_PRIVATE, 1, nullptr, nullptr, FUTEX_BITSET_MATCH_ANY);
}
static int address_broadcast(_Atomic uint32_t *addr)
{
return futex((uint32_t *)addr, FUTEX_WAKE_BITSET_PRIVATE, 128, nullptr, nullptr, FUTEX_BITSET_MATCH_ANY);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment