3 ms·
When spinning on an atomic operation, you should add some kind of yield operation. The "pause" instruction in x86 at least. On newer CPUs a "monitor" and "mwait
by exDM69 11y ago
When spinning on an atomic operation, you should add some kind of yield operation. The "pause" instruction in x86 at least. On newer CPUs a "monitor" and "mwait" can work a little better (but may not be available in user space). Do not use thread_yield or other kernel calls, because at that point you're better off using a mutex.
When spinning on atomics, the interconnect between cores needs to do a lot of work synchronizing the memory. When adding a pause or monitor instruction, the core will give an opportunity for the other hyperthread in the same core to execute, reducing the amount of churn on the interconnect.
Counterintuitively, adding a "pause" in the spin loop will make the program faster by yielding the CPU core for a few nanoseconds.
- vardump 11y agoThat's interesting. Any references about this? What about ARM CPUs?
- exDM69 11y agoSee Intel Programmer's manual (vol 3a iirc) about pause, monitor and mwait. Not sure about ARM, that architecture has different rules of cache coherence and no hyperthreading and you need to add explicit memory barriers.