From: Daniel Colascione Date: Tue, 1 Mar 2016 22:57:44 +0000 (-0800) Subject: Stern warning about spinlocks X-Git-Tag: deprecate-dynamic-initializer~24 X-Git-Url: http://demsky.eecs.uci.edu/git/?a=commitdiff_plain;h=602d3f04c843726feed56d2e0f31c597bbc596b8;p=folly.git Stern warning about spinlocks Summary: Spinlocks are a bad idea most of the time. Reviewed By: rickbrew Differential Revision: D2996558 fb-gh-sync-id: e86f1f0a084bda0c16759e979201db2e18102555 shipit-source-id: e86f1f0a084bda0c16759e979201db2e18102555 --- diff --git a/folly/RWSpinLock.h b/folly/RWSpinLock.h index 90774e03..a01a2346 100644 --- a/folly/RWSpinLock.h +++ b/folly/RWSpinLock.h @@ -14,6 +14,37 @@ * limitations under the License. */ +/************************************************* + +IF YOU HAVE TO ASK, NO, YOU DO NOT WANT A SPINLOCK. + +Yes, even if a microbench shows that a spinlock is faster, you still probably +don't want one. + +Spinlocks in general are a big problem on systems for which you cannot disable +preemption, like normal user-space code running on POXIX and Windows +platforms. If the thread holding a spinlock is preempted, another thread +trying to acquire the lock and pounding the lock variable +has no idea that it's spinning in vain. Some spinlock implementations use +sched_yield or similar to try to make this problem less severe --- we don't +use the rest of our timeslice to pointlessly read a variable --- +but the overall result is still poor, especially if the thread locking the lock +sleeps (which any thread can do on a demand-paging system), then we'll +sched_yield over and over again, still pointlessly, pounding on the lock. + +You really want a plain old mutex. Regular mutexes will spin for a little while, +then go to sleep. While sleeping, threads use no CPU resources and do +not cause scheduler contention. + +There are exceptions to the above warning. If you have to ask, no, your +code doesn't qualify. + + +STOP USING SPINLOCKS IN ORDINARY CODE. + + +**************************************************/ + /* * Two Read-Write spin lock implementations. *