Boost logo

Boost :

From: Alexander Terekhov (terekhov_at_[hidden])
Date: 2004-03-22 08:41:02


Adal Chiriliuc wrote:
>
> Hello.
>
> try_mutex uses a Mutex instead of a CRITICAL_SECTION because on
> Windows 9x and Me it's impossible to try the aquisition of a
> CRITICAL_SECTION.

Yeah.

class swap_based_mutex_for_windows { // noncopyable

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

public:

  // ctor/dtor [w/o lazy event init]

  void lock() {
    if (m_lock_status.swap(1, msync::acq))
      while (m_lock_status.swap(-1, msync::acq))
        m_retry_event.wait();
  }

  bool trylock() {
    return !m_lock_status.swap(1, msync::acq) ?
      true : !m_lock_status.swap(-1, msync::acq);
       
  }

  bool timedlock(absolute_timeout const & timeout) {
    if (m_lock_status.swap(1, msync::acq)) {
      while (m_lock_status.swap(-1, msync::acq))
        if (!m_retry_event.timedwait(timeout))
          return false;
    }
    return true;
  }

  void unlock() {
    if (m_lock_status.swap(0, msync::rel) < 0)
      m_retry_event.set();
  }

};

regards,
alexander.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk