From mboxrd@z Thu Jan 1 00:00:00 1970 X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: fee84,a3ae14aeae49226 X-Google-Attributes: gidfee84,public From: Monty Brandenberg Subject: Re: mutex between processes? Date: 1998/08/10 Message-ID: <35CFAAE2.42E645BA@ne.mediaone.net> X-Deja-AN: 379912278 Content-Transfer-Encoding: 7bit References: <35C85511.E31EBB9E@brighttiger.com> <35CAC907.497400F4@orga.com> <35CB2911.61856927@brighttiger.com> <35CF6191.3BB020B5@ne.mediaone.net> To: Dirk Grunwald Content-Type: text/plain; charset=us-ascii Organization: MCB, Inc. Mime-Version: 1.0 Reply-To: mcbinc@ne.mediaone.net.MAPS.SPAM Newsgroups: comp.unix.osf.osf1 Dirk Grunwald wrote: > > Look, if I'm just incrementing a variable (the problem being described > by the person in question) there's no reason to even *hint* at the > possibility of a context switch forced by the thread library during > that incremenet. > > E.g., if I'm going > > pthread_mutex_lock(foo); > counter++; > pthread_mutex_unlock(foo); > > it will take more time to get into/out of the O/S than to simply way. > > Many performance oriented programmers would know this and exercise > proper judgement about when to use a spinlock. Let's break things down into two cases: Shared-read/exclusive-write data who correctness is (case 1) not critical or (case 2) critical. Case 1: An application can elect not to put the data under a mutex. All algorithms that use that data as input must be prepared to deal with incorrect or inconsistent values in the structure. Candidates for this class are: performance counters, profiling code, debug flags. Other application data can fall into this class keeping the incorrectness/ inconsistency aspect in mind and communicating it to those poor bastards who have to do maintenance on the thing once you've gone on to greener pastures. Case 2: Since I write device drivers and similar kernel code, almost everything I do falls into this area. I'll discuss this in an application space, which is slightly different from kernel, where there are roughly four approaches: Case 2.a: Do nothing. This will get you into trouble. It's hard to debug and your co-workers will hate you. You will be forced to write Visual Basic faux-programs for the rest of your life. Case 2.b: System mutex. In the case of Digital Unix, use pthreads, mach thread control, or TIS services to implement a classic mutex around the data. In the case of pthreads, the system services even guarantee data ordering in an SMP system between system calls. That is, all the requirements of section 5.6 of the Alpha SRM are satisified with respect to cpu/cpu operations. Device/cpu ordering is a separate issue. Case 2.c: System mutex with syscall avoidance. The idea is that syscalls are expensive (a relative measure as I'll detail in a moment) so avoiding them is A Good Thing. It is achieved by using an interlocked counter or similar mechanism to detect contention for a mutex and to only make mutex calls when contention arises. I've offered the BeOS' Benaphores up as an example of this and they are generally a win for infrequent locking. However, there can be major performance hits due to scheduler activity. See the Be Newsletters for details. Case 2.d: User-mode spinlocks. In a way, this is a return to DOS programming. The idea is that the cost of a thread simply spinning on an smp-safe flag will be less than the cost of entering and exiting a pair of system services. There a number of reasons why this may not be so which I'll go into in a moment. First, I'll discuss implementation. An smp-safe spinlock cannot be constructed from STx, LDx, and MB. It must be built from LDx_L and STx_C instructions. These are the load locked/store conditionals that use the architecture- and implementation-defined interlocked access protocols to guarantee that multiple cpus see identical versions of longwords or quadwords. From an old version of the SRM, here's a spin-lock algorithm (may contain errors): stq_c_loop: spin_loop: LDQ_L r1, lock_variable BLBS r1, already_set OR r1, #1, r2 STQ_C r2, lock_variable BEQ r2, stq_c_fail MB ; Begin critical section ; End critical section MB STQ r31, lock_variable ; clear lock ; Return to application code ; Forward branching failure targets already_set: ; Sleep, check for too many iterations, or do nothing BR spin_loop stq_c_fail: ; Check for too many interations. BR stq_c_loop Now let's consider the merits: . Cost of syscall versus cost of spinlock contention. The time to execute a trivial syscall (trap, prepare return value, dismiss trap) on an EV5-class alpha can be as low as 500 nS (nano). Obviously, a real syscall is going to take more time. It's been some time since I've benchmarked it but a heavy- weight syscall using the ioctl interface, a sleep, an interrupt in an ISR routine to do a wakeup was under 10 uS and 6 uS comes to mind. A mutex acquire/release pair could be as fast as 1 uS for no contention, and on the order of 10 uS (plus sleep time) with contention. The user-mode spinlock widens the spread. First, with no contention, you still need a correct implementation of the spinlock and that will eat a few cycles (see algorithm) but is still faster than a syscall. On a single processor, with, say, a 10,000 uS scheduling quantum, encountering contention, the losing thread is in a cpu-spin and will have to exhaust its quantum before the lock-owning thread can proceed and release the lock. In the best case, the lock-owning thread is scheduled, clears the lock, and *immediately* sleeps allowing the first thread to execute and do useful work. In this case, the statistical expected value for lock acquisition is 5,000 uS. I.e. lower bound is half the scheduling quantum. There are worse cases: The lock-owning thread is cpu-bound and continues to consume a full quantum every time it is scheduled. Expected value for lock acquisition: 15,000 uS or 1.5 times the scheduling quantum. Worse still: lock-owning thread consumes a quantum and re-acquires lock just before losing quantum. Expected value for lock acquisition: >1.5 times the scheduling quantum. Now we have: T.exp.mut Expected time to execute real mutex code T.exp.spin Expected time to execute user-mode spinlock code T.exp.unlock Expected time to unlock mutex under contention T.spin.nocont Expected time to acquire spinlock with no contention P.mut.cont Probability of encountering contention with real mutex code P.spin.cont Probability of encountering contention with user-mode spinlock P.best Probability of best-case spinlock contention resolution P.worse Probability of worse-case spinlock contention resolution P.worst Probability of worst-case spinlock contention resolution T.exp.mut = (P.mut.cont * (10uS + T.exp.unlock)) + ((1 - P.mut.cont) * 1uS) T.exp.spin = (P.spin.cont * ((P.best * 5,000 uS) +(P.worse * 15,000 uS) +(P.worst * 20,000 uS))) + ((1 - P.spin.cont) * T.spin.nocont) 1 ~ P.best + P.worse + P.worst We can make some assumptions: P.best should be near 1. T.spin.nocont is on the order of 10's of nS unless some of the situations below arise. T.exp.unlock is dependent upon the application's algorithms but it also represents useful work as opposed to the time consumed under the P.spin.cont term which is dead CPU. How you weight it is a designer's decision. The goal is to keep T.exp.spin well under (i.e. the benefit outweighs the effort of supporting and debugging home-grown spinlock code on every supported system) T.exp.mut. Obviously, there are several independent variables but a few will likely dominate. If P.spin.cont is much greater than 1/5000, its term dominates T.exp.spin and bounds that latter to a minimum of 1uS which is the lower bound for T.exp.mut regardless of P.mut.cont. What do you need to do? Profile your application so that you can estimate P.spin.cont. Certain application decisions will affect this value. If the spinlock is coarse-grained, i.e. a few locks cover all data structures, the probability goes up. As the time required to execute the code in the critical section goes up, this probability goes up. If the spinlocks are fine-grained, the probability goes down *but* T.spin.nocont starts to increase exponentially. That is because the system bus protocol for interlocked operations typically has very large granularity. . On an SMP system, the times under the P.spin.cont term should be smaller. A thread has the potential to get running on one processor and clear the lock allowing a blocked thread on the other system to run (which is why spinlocks work well for kernel mode code which first assumes priority ordering under spl level). However, with more than two threads, or more specifically, with too many more threads than cpus, P.spin.cont goes back up. And with too many cpus, T.spin.nocont goes up (this represents the asymptotic limit of smp systems). . The user-mode spinlocks are subject to some of the problems of 2.c. See lit. for details. . The particular times in the above are not definitive. I haven't benchmarked the pthread, mach thread, or tis services. Only the kernel-mode sleep mechanisms, interrupt dispatching, and trap handling. The numbers I present are certainly possible but what is actually achieved in the libraries needs competent benchmarking. Finally, if you go down the SMP route, make *certain* you develop and test on an SMP system. You can violate all the data ordering requirements on a single processor system and everything will work correctly as a single cpu sees only one consistent view of the system. Put that code on an smp machine and it will very quickly fall apart in obvious and not-so-obvious ways. > However, without representative & provided "spinlock" code, even > expert programmers will screw up the WB's, MB's and the like needed > for correctness. Representative and provided spinlock code is in the Alpha SRM. If you are attempting to implement SMP algorithms on Alpha without this book, or the corresponding book on other architectures, you're not doing your employers good service. > We shouldn't assume all programmers don't know how to write concurrent code. That's a nice sentiment but it doesn't stand up to scutiny. It's a better than one sigma programmer who can use explicit concurrent programming services correctly. (I present the Modula-3 project's motivation as proof.) Those who can actually implement the services correctly are out at three sigma, I'd say. m -- Monty Brandenberg, Software Consultant MCB, Inc. mcbinc@ne.mediaone.net.MAPS.SPAM P.O. Box 426188 mcbinc@world.std.com.MAPS.SPAM Cambridge, MA 02142 617.864.6907