public inbox for pthreads-win32@sourceware.org
 help / color / mirror / Atom feed
* mutexes: "food for thought"
@ 2003-10-18 17:47 Alexander Terekhov
  2004-10-08 12:49 ` Ross Johnson
  0 siblings, 1 reply; 3+ messages in thread
From: Alexander Terekhov @ 2003-10-18 17:47 UTC (permalink / raw)
  To: pthreads-win32

G'Day,

here's "ala futex based" mutex stuff using XCHG. 

No need for CAS. I hope that it will work just fine. 

Can you see any harmful race condition(s) here? 

TIA.

#define SWAP_BASED_MUTEX_FOR_WINDOWS_INITIALIZER { 0, 0 }

struct swap_based_mutex_for_windows {

  atomic<int>                m_lock_status;  // -1: free, 0: locked, 1 
lock-contention
  atomic<auto_reset_event *> m_retry_event;  // DCSI'd 

  void DCSI(); // double-checked serialized initialization
  void slow_lock();
  bool slow_trylock();
  bool slow_timedlock(absolute_timeout const & timeout);
  void release_one_waiter_if_any();

  void lock() {
    if (m_lock_status.swap(0, msync::acq) >= 0) slow_lock();
  } 

  bool trylock() {
    return (m_lock_status.swap(0, msync::acq) < 0) ? true : 
slow_trylock(); 
  }

  bool timedlock(absolute_timeout const & timeout) {
    return (m_lock_status.swap(0, msync::acq) < 0) ? true : 
slow_timedlock(timeout);
  }

  void unlock() {
    if (m_lock_status.swap(-1, msync::rel) > 0) 
release_one_waiter_if_any();
  }

};

void swap_based_mutex_for_windows::slow_lock() {
  DCSI();
  while (m_lock_status.swap(1, msync::acq) >= 0)
    m_retry_event.load(msync::none)->wait();
}

bool swap_based_mutex_for_windows::slow_trylock() {
  DCSI();
  return m_lock_status.swap(1, msync::acq) < 0;
}

bool swap_based_mutex_for_windows::slow_timedlock(absolute_timeout const & 
timeout) {
  DCSI();
  while (m_lock_status.swap(1, msync::acq) >= 0)
    if (!m_retry_event.load(msync::none)->timedwait(timeout)) return 
false;
  return true;
}

void swap_based_mutex_for_windows::release_one_waiter_if_any() {
  m_retry_event.load(msync::none)->set();
}

void swap_based_mutex_for_windows::DCSI() {
  if (!m_retry_event.load(msync::none)) {
    named_windows_mutex_trick guard(this);
    if (!m_retry_event.load(msync::none)) {
      m_retry_event.store(new auto_reset_event(), msync::rel);
      m_lock_status.store(-1, msync::rel);
    }
  }
}

regards,
alexander.

P.S. I've never run it. Just a sketch.

^ permalink raw reply	[flat|nested] 3+ messages in thread

end of thread, other threads:[~2004-10-26 17:29 UTC | newest]

Thread overview: 3+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2003-10-18 17:47 mutexes: "food for thought" Alexander Terekhov
2004-10-08 12:49 ` Ross Johnson
2004-10-26 17:29   ` mutexes: "food for thought" [upcoming XBOX] Alexander Terekhov

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).