Subj : Re: Optimization to Jeffrey Richter's COptex (Windows)? To : comp.programming.threads From : Alexander Terekhov Date : Thu Jan 27 2005 02:35 pm SenderX wrote: ... You've omitted timedlock(). Why so? ;-) Well, timedlock() aside for a moment, with your waiters counting you increase the overhead of contention. More waiters in a batch results in more counting/read-modify-write. Get rid of waiters counting. With waiters bit maintained by you instead of counting, you'll have needless signaling from time to time (at the end of contention interval) and it may cause "spurious" wake at the beginning of next contention interval but that overhead is "constant" (it doesn't increase with increased contention). Sorta optimizations meant to "compensate" some silly cas impls aside for a moment, atomic m_lock_status; // 0: free, 1/-1: locked/contention auto_reset_event m_retry_event; // prohibitively slow bin.sema/gate // ctor/dtor [w/o lazy event init] bool trylock() throw() { return !m_lock_status.cas(0, 1, msync::acq); } void lock() throw() { if (int lock_status = m_lock_status.cas(0, 1, msync::acq)) { do { while (lock_status < 0 || lock_status = m_lock_status.cas(1, -1, msync::acq)) { m_retry_event.wait(); // acquire msync lock_status = m_lock_status.load(msync::none); if (!lock_status) break; } } while (lock_status = m_lock_status.cas(0, -1, msync::acq)); } } void unlock() throw() { if (m_lock_status.cas(1, 0, msync::rel) < 0) { m_lock_status.store(0, msync::rel); m_retry_event.set(); // release msync } } regards, alexander. .