|
Boost : |
From: Alexander Terekhov (terekhov_at_[hidden])
Date: 2004-05-15 13:33:59
Michael Glassford wrote:
[...]
> Do you have a full-fledged implementation for such a beast?
Trade secret.
> I remember you posting sample code some time back, ...
class swap_based_mutex_for_windows { // noncopyable
atomic<int> m_lock_status; // 0: free, 1/-1: locked/contention
auto_reset_event m_retry_event;
public:
// ctor/dtor [w/o lazy event init]
void lock() throw() {
if (m_lock_status.swap(1, msync::acq))
while (m_lock_status.swap(-1, msync::acq))
m_retry_event.wait();
}
bool trylock() throw() {
return !m_lock_status.swap(1, msync::acq) ?
true : !m_lock_status.swap(-1, msync::acq);
}
bool timedlock(absolute_timeout const & timeout) throw() {
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() throw() {
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