-
Notifications
You must be signed in to change notification settings - Fork 0
Mutex Condition variable
You can make an object thread-safe easily by making it inherit from fwk::Lockable
.
class Foo :public fwk::Lockable {
// ...
};
You can know lock/unlock a Foo
object by using foo.lock()
and foo.unlock()
. This uses a reentrant_lock (the same thread can lock the same object multiple times).
To lock/unlock a fwk::Lockable
object safely by using RAII, you can use:
{
SCOPELOCK(&(foo));
// object is locked here
// [CRITICAL SECTION]
}
// object is unlocked here, even if there is an exception.
There is an easy way to make object inherit from Lockable, even if you can't do it in the class declaration (like on an STL object). To achieve this, you can declare your object like this:
fwk::TLockable<std::list<Foo>> lockableFooList;
{
SCOPELOCK(&(lockableFooList));
// [CRITICAL SECTION]
}
You can use a condition variable using a fwk::Notifiable
object. It inherits from fwk::Lockable
so you can use notifiable.lock()
and notofiable.unlock()
.
You can wait on the fwk::Notifiable
with this:
fwk::Notifiable notifiable;
{
// the Notifiable object must be locked to be waited on.
SCOPELOCK(&(notifiable));
notifiable.wait();
}
Now you can wake threads waiting on the fwk::Notifiable
with this:
{
// The Notifiable object must be locked to be woken.
SCOPELOCK(&(notifiable));
// wake one thread waiting
notifiable.notify();
// or wake all threads waiting
notifiable.notify_all();
}
Same thing as fwk::TLockable
, but with a fwk::Notifiable
.