Xref: utzoo comp.sys.next:5473 comp.os.mach:326 Path: utzoo!attcan!uunet!cs.utexas.edu!usc!zaphod.mps.ohio-state.edu!unix.cis.pitt.edu!dsinc!sunybcs!uhura.cc.rochester.edu!rochester!pt.cs.cmu.edu!spice.cs.cmu.edu!mbj From: mbj@spice.cs.cmu.edu (Michael Jones) Newsgroups: comp.sys.next,comp.os.mach Subject: Re: technique used to implement mutex_lock() Summary: mutex_lock() answer Message-ID: <8460@pt.cs.cmu.edu> Date: 17 Mar 90 17:15:17 GMT References: <429@kgw2.bwi.WEC.COM> Distribution: na Organization: Carnegie-Mellon University, CS/RI Lines: 29 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