I have limited experience writing code for macOS, but I’ve recently run into a porting challenge.
In my project, I use futex (fast userspace mutex) on Linux for fast lock-free notifications between threads, like this:
syscall(SYS_futex, &variable, FUTEX_WAIT, 0, ...);
syscall(SYS_futex, &variable, FUTEX_WAKE, 1, ...);
This allows producer threads to notify a consumer thread to wake up without using any locks, and ensures that no notifications are lost if the consumer thread is not currently waiting.
On Windows, the closest equivalents are auto-reset events (pre-Windows 8 ):
_hEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);
WaitForSingleObject(_hEvent, INFINITE);
SetEvent(_hEvent);
and, starting from Windows 8, functions similar to Linux futex that don’t require explicit initialization:
WaitOnAddress(&variable, &variable, sizeof(variable), INFINITE);
WakeByAddressSingle(&variable);
However, while porting this code to macOS, I haven’t been able to find anything that resembles futex. Consequently, on macOS, the only way to send such a notification seems to be acquiring a heavy mutex lock in the producer thread, which can significantly degrade performance. Is it correct?
Does macOS really lack a mechanism for fast lock-free cross-thread notifications inside a process?
How do people usually solve this problem on macOS?