Remix.run Logo
jcranmer 2 hours ago

The basic rule of writing your own cross-thread datastructures like mutexes or condition variables is... don't, unless you have very good reason not to. If you're in that rare circumstance where you know the library you're using isn't viable for some reason, then the next best rule is to use your OS's version of a futex as the atomic primitive, since it's going to solve most of the pitfalls for you automatically.

The only time I've manually written my own spin lock was when I had to coordinate between two different threads, one of which was running 16-bit code, so using any library was out of the question, and even relying on syscalls was sketchy because making sure the 16-bit code is in the right state to call a syscall itself is tricky. Although in this case, since I didn't need to care about things like fairness (only two threads are involved), the spinlock core ended up being simple:

    "thunk_spin:",
        "xchg cx, es:[{in_rv}]",
        "test cx, cx",
        "jnz thunk_has_data",
        "pause",
        "jmp thunk_spin",
    "thunk_has_data:",
fasterik an hour ago | parent | next [-]

As always: use standard libraries first, profile, then write your own if the data indicate that it's necessary. To your point, the standard library probably already uses the OS primitives under the hood, which themselves do a short userspace spin-wait and then fall back to a kernel wait queue on contention. If low latency is a priority, the latter might be unacceptable.

The following is an interesting talk where the author used a custom spinlock to significantly speed up a real-time physics solver.

Dennis Gustafsson – Parallelizing the physics solver – BSC 2025 https://www.youtube.com/watch?v=Kvsvd67XUKw

kccqzy 2 hours ago | parent | prev | next [-]

Another time when writing a quick and dirty spinlock is reasonable is inside a logging library. A logging library would normally use a full-featured mutex, but what if we want the mutex implementation to be able to log? Say the mutex can log that it is non recursive yet the same thread is acquiring it twice; or that it has detected a deadlock. The solution is to introduce a special subset of the logging library to use a spinlock.

wizzwizz4 an hour ago | parent [-]

I'm not sure how a spinlock solves this problem. Wouldn't that just cause the process to hang busy?

direwolf20 7 minutes ago | parent [-]

Only until the other thread leaves the logger

an hour ago | parent | prev [-]
[deleted]