JUCE
Classes | Typedefs
juce_CriticalSection.h File Reference

Classes

class  CriticalSection
 A re-entrant mutex. More...
 
class  DummyCriticalSection
 A class that can be used in place of a real CriticalSection object, but which doesn't perform any locking. More...
 
struct  DummyCriticalSection::ScopedLockType
 A dummy scoped-lock type to use with a dummy critical section. More...
 

Typedefs

typedef CriticalSection::ScopedLockType ScopedLock
 Automatically locks and unlocks a CriticalSection object. More...
 
typedef CriticalSection::ScopedUnlockType ScopedUnlock
 Automatically unlocks and re-locks a CriticalSection object. More...
 
typedef CriticalSection::ScopedTryLockType ScopedTryLock
 Automatically tries to lock and unlock a CriticalSection object. More...
 

Typedef Documentation

§ ScopedLock

Automatically locks and unlocks a CriticalSection object.

You can use a ScopedLock as a local variable to provide RAII-based locking of a CriticalSection.

e.g.

struct MyObject
{
CriticalSection objectLock;
// assuming that this example function will be called by multiple threads
void foo()
{
const ScopedLock myScopedLock (objectLock);
// objectLock is now locked..
...do some thread-safe work here...
// ..and objectLock gets unlocked here, as myScopedLock goes out of
// scope at the end of the block
}
};
See also
CriticalSection, ScopedUnlock

§ ScopedUnlock

Automatically unlocks and re-locks a CriticalSection object.

This is the reverse of a ScopedLock object - instead of locking the critical section for the lifetime of this object, it unlocks it.

Make sure you don't try to unlock critical sections that aren't actually locked!

e.g.

struct MyObject
{
CriticalSection objectLock;
void foo()
{
{
const ScopedLock myScopedLock (objectLock);
// objectLock is now locked..
{
ScopedUnlock myUnlocker (objectLock);
// ..and now unlocked..
}
// ..and now locked again..
}
// ..and finally unlocked.
}
};
See also
CriticalSection, ScopedLock

§ ScopedTryLock

Automatically tries to lock and unlock a CriticalSection object.

Use one of these as a local variable to control access to a CriticalSection.

e.g.

struct MyObject
{
CriticalSection objectLock;
void foo()
{
const ScopedTryLock myScopedTryLock (objectLock);
// Unlike using a ScopedLock, this may fail to actually get the lock, so you
// must call the isLocked() method before making any assumptions..
if (myScopedTryLock.isLocked())
{
...safely do some work...
}
else
{
// If we get here, then our attempt at locking failed because another thread had already locked it..
}
}
};
See also
CriticalSection::tryEnter, ScopedLock, ScopedUnlock, ScopedReadLock