Subj : Re: reliability of setting thread priority To : comp.programming.threads From : Alexander Terekhov Date : Fri Feb 25 2005 02:35 pm gottlobfrege@gmail.com wrote: [...] > I could wait and call CreateMutex() during the first usage, but then > I'm back to needing a flag/exchange to protect that, No, you don't need anything to "protect that". > and it starts to > seem no better than what I already have. CreateMutex() with subsequent locking is done on first usage by all threads as long as the initialization is not complete. That's why the mutex is named. Since they also call CloseHandle() on exit from DCSI's slow path, named mutex evaporates as soon as the last thread leaves it. #define SWAP_BASED_MUTEX_FOR_WINDOWS_INITIALIZER { 0, 0 } ^^^^ class swap_based_mutex_for_windows { /* ... */ // -1: free, 0: locked, 1: contention ^^^^^^^^^ atomic m_lock_status; atomic m_retry_event; /* ... */ void lock() { if (m_lock_status.swap(0, msync::acq) >= 0) slow_lock(); } void unlock() { if (m_lock_status.swap(-1, msync::rel) > 0) m_retry_event.load(msync::none)->set(); } void slow_lock() { auto_reset_event & retry_event = DCSI(); while (m_lock_status.swap(1, msync::acq) >= 0) retry_event.wait(); } auto_reset_event & DCSI() { auto_reset_event * retry_event; if ((retry_event = m_retry_event.load(msync::none)) == 0) { named_windows_mutex_trick guard(this); if ((retry_event = m_retry_event.load(msync::none)) == 0) { retry_event = new auto_reset_event() m_retry_event.store(retry_event, msync::rel); m_lock_status.store(-1, msync::rel); } } return *retry_event; } } regards, alexander. .