cosmopolitan/libc/intrin/ulock.h

26 lines
887 B
C
Raw Normal View History

Make futexes 100x better on x86 MacOS Thanks to @autumnjolitz (in #876) the Cosmopolitan codebase is now acquainted with Apple's outstanding ulock system calls which offer something much closer to futexes than Grand Central Dispatch which wasn't quite as good, since its wait function can't be interrupted by signals (therefore necessitating a busy loop) and it also needs semaphore objects to be created and freed. Even though ulock is an internal Apple API, strictly speaking, the benefits of futexes are so great that it's worth the risk for now especially since we have the GCD implementation still as a quick escape hatch if it changes Here's why this change is important for x86 XNU users. Cosmo has a suboptimal polyfill when the operating system doesn't offer an API that let's us implement futexes properly. Sadly we had to use that on X86 XNU until now. The polyfill works using clock_nanosleep, to poll the futex in a busy loop with exponential backoff. On XNU x86 clock_nanosleep suffers from us not being able to use a fast clock gettime implementation, which had a compounding effect that's made the polyfill function even more poorly. On X86 XNU we also need to polyfill sched_yield() using select(), which made things even more troublesome. Now that we have futexes we don't have any busy loops anymore for both condition variables and thread joining so optimal performance is attained. To demonstrate, consider these benchmarks Before: $ ./lockscale_test.com -b consumed 38.8377 seconds real time and 0.087131 seconds cpu time After: $ ./lockscale_test.com -b consumed 0.007955 seconds real time and 0.011515 seconds cpu time Fixes #876
2023-10-03 21:47:20 +00:00
#ifndef COSMOPOLITAN_ULOCK_H_
#define COSMOPOLITAN_ULOCK_H_
COSMOPOLITAN_C_START_
/* both wake and wait take one of these */
#define UL_COMPARE_AND_WAIT 1 /* multi-thread */
#define UL_UNFAIR_LOCK 2
#define UL_COMPARE_AND_WAIT_SHARED 3 /* multi-thread/process */
#define UL_UNFAIR_LOCK64_SHARED 4
#define UL_COMPARE_AND_WAIT64 5
#define UL_COMPARE_AND_WAIT64_SHARED 6
#define ULF_WAKE_ALL 0x00000100
#define ULF_WAKE_THREAD 0x00000200 /* takes wake_value */
#define ULF_WAKE_ALLOW_NON_OWNER 0x00000400
#define ULF_WAIT_WORKQ_DATA_CONTENTION 0x00010000
#define ULF_WAIT_CANCEL_POINT 0x00020000 /* raises eintr */
#define ULF_WAIT_ADAPTIVE_SPIN 0x00040000
int ulock_wake(uint32_t, void *, uint64_t);
int ulock_wait(uint32_t, void *, uint64_t, uint32_t);
COSMOPOLITAN_C_END_
#endif /* COSMOPOLITAN_ULOCK_H_ */