Xref: utzoo comp.sys.next:5536 comp.os.mach:335 Path: utzoo!attcan!uunet!samsung!uakari.primate.wisc.edu!ames!sgi!shinobu!odin!moose!jwag From: jwag@moose.sgi.com (Chris Wagner) Newsgroups: comp.sys.next,comp.os.mach Subject: Re: technique used to implement mutex_lock() Message-ID: <5612@odin.corp.sgi.com> Date: 22 Mar 90 05:24:56 GMT References: <8460@pt.cs.cmu.edu> <429@kgw2.bwi.WEC.COM> Sender: news@odin.corp.sgi.com Reply-To: jwag@moose.sgi.com (Chris Wagner) Distribution: na Organization: Silicon Graphics, Research & Development Lines: 48 In article <8460@pt.cs.cmu.edu>, mbj@spice.cs.cmu.edu (Michael Jones) writes: > In article <429@kgw2.bwi.WEC.COM>, dennisg@kgw2.bwi.WEC.COM (Dennis Glatting) writes: > > > > how is mutex_lock() implemented in the NeXT computer? > > > > i have several tasks with several threads each. i had a thread lock a > > mutex with mutex_lock() then, unfortunatly, died. the mutex stayed locked. > > i noticed that the NeXT was running a bit slow so i fired up gdb of > > the task in question. i found more than one thread in cthread_yield(). > > my question is: when you call mutex_lock() and the mutex is locked then > > what happens? does the thread do a cthread_yield() until the mutex > > is unlocked? if that is true then why? it seems a waste of cpu. > > mutex_lock(m) spins a few times calling mutex_try_lock(m), and then spins > alternating between mutex_try_lock(m) and cthread_yield(). mutex_try_lock(m) > is a test-and-set on the mutex. > > Now to answer your real question. No, it's not a waste of cpu to spin on a > mutex in a correctly written threads application. A mutex provides mutual > exclusion between two threads. It's intended to be called only when the > mutual exclusion is of a short or bounded duration. It's not the right > primitive for unbounded waiting. Any potentially unbounded waiting should be > done using condition_wait and condition_{signal,broadcast} (which don't spin). > > If a thread dies, none of the memory resources which it logically owns will be > cleaned up. That includes its locks. If a thread dies, you have an incorrect > program anyway, and the fact that some locks are still held is the least of > your problems. > > -- Mike Although in many cases, spinning is a good idea - what happens when a thread holds a lock for what it thnks is a short time - however during the few instructions it has the lock it gets context switched, other threads trying to get the lcok will spin a while then yield. Thats ok as long the the number of threads is not too much greater than the number of processors - but what happens when you have 100 or more threads going after a single lock often, the time till the thread that owns the lock gets to run could be fairly long. Chris Wagner