14 hours ago, Shaarigan said:I use that behind the scenes as platform and architecture independent std::atomic replacement for something like spin locking in our professional engine
#if defined(__GNUC__) #define SpinLock(__lock) { while (sync_lock_test_and_set(&(__lock), 1)) while (lock) {} } #define SpinUnlock(__lock) { __sync_lock_release(&(__lock)); } #elif defined(WINDOWS) #define SpinLock(__lock) { while (InterlockedExchange(&(__lock), 1)) while (__lock) {} } #define SpinUnlock(__lock) { InterlockedExchange(&(__lock), 0); } #endif
But anybody should stay aware of exotic platforms that implement their own interlocked functions like PSSDK or Switch SDK does
While we're on the topic, Intel recommends that you put a _mm_pause or YieldProcessor (MSVC) call inside the body of any spin loop, which emits a special kind of NOP instruction. The CPU will recognize this pattern, de-pipeline the decoded loop instructions, switch to the HW hyper-thread if the loop keeps spinning, and reduce power consumption until the loop exits
For everyone else: using spin-loops is in general a pretty bad idea for performance. Your compiler's default locks (e.g. a critical section on Win32/MSVC) will use a tried, tested and well tuned spin-lock and then progressively fall back to more heavyweight algorithms if it spins for "too long".