|
Boost : |
From: Howard Hinnant (hinnant_at_[hidden])
Date: 2004-03-10 10:22:59
On Mar 9, 2004, at 10:56 AM, M Shetty wrote:
> Is it possible to simulate a behaviour like WaitForMultipleObjects
> using boost? If yes, kindly let me know.
I once suggested:
template <class TryLock1, class TryLock2>
class lock_both
{
public:
lock_both(TryLock1& m1, TryLock2& m2);
lock_both(TryLock1& m1, TryLock2& m2, bool lock_it);
~lock_both();
void lock();
bool try_lock();
void unlock();
bool locked() const;
operator int bool_type::* () const;
private:
lock_both(const lock_both&);
lock_both& operator=(const lock_both&);
};
Actually I think I called it lock2. The lock() function could simply
lock one of the locks and then use try_lock on the other. If it
succeeds, then great, else you unlock the first lock and try again in
the reverse order. If the reverse order also fails, yield and start
over with the original order. Might be used like:
try_mutex m1, m2, m3;
void foo2()
{
typedef try_mutex::scoped_try_lock Lock;
typedef lock_both<Lock, Lock> Lock2;
Lock l1(m1, false);
Lock l2(m2, false);
Lock2 lock12(l1, l2);
// m1 and m2 locked here
}
For more than two mutexes you could string lock_both's together since
lock_both is also a try lock.
void foo3()
{
typedef try_mutex::scoped_try_lock Lock;
typedef lock_both<Lock, Lock> Lock2;
typedef lock_both<Lock2, Lock> Lock3;
Lock l1(m1, false);
Lock l2(m2, false);
Lock l3(m3, false);
Lock2 lock12(l1, l2, false);
Lock3 lock123(lock12, l3);
// m1, m2 and m3 locked here
}
-Howard
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk