Skip to content

Mutex Condition variable

Gautier Lefebvre edited this page Feb 13, 2018 · 2 revisions

Lockable

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.

TLockable

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]
}

Notifiable

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();
}

TNotifiable

Same thing as fwk::TLockable, but with a fwk::Notifiable.

Clone this wiki locally