You.i Engine
CYIAutoSpinLock Class Reference

Detailed Description

The CYIAutoSpinLock is a helper class that simplifies the locking and unlocking of spin locks based on the RAII principle.

Locking and unlocking a CYISpinLock in a function that has multiple return points can be difficult. Forgetting to unlock a CYISpinLock can result a live-lock.

Consider the following example:

bool OnState(State state)
{
m_spinLock.Lock();
swich (state)
{
case State::INIT:
m_spinLock.Unlock();
return Create();
case State::RUNNING:
m_runCount++;
break;
case State::PAUSED:
m_runCount--;
m_bPaused = true;
break;
case State::STOPPED:
if (!m_bPaused)
{
m_runCount--;
}
case State::DESTROY:
m_spinLock.Unlock();
return Destroy();
default:
break;
}
m_spinLock.Unlock();
return true;
}

With the help of the CYIAutoSpinLock, the code above could be simplified to the following:

void Example(State state)
{
CYIAutoSpinLock lock(m_spinLock);
swich (state)
{
case State::INIT:
return Create();
case State::RUNNING:
m_runCount++;
break;
case State::PAUSED:
m_runCount--;
m_bPaused = true;
break;
case State::STOPPED:
if (!m_bPaused)
{
m_runCount--;
}
case State::DESTROY:
return Destroy();
default:
break;
}
return true;
}

This way, the locked CYISpinLock will always unlock automatically for you, as soon as the lock object gets out of scope.

See also
CYIAutoMutex
CYIAutoReadMutex
CYIAutoWriteMutex
CYISpinLock
CYIMutex
CYIReadWriteMutex

#include <thread/YiAutoSpinLock.h>

Public Member Functions

 CYIAutoSpinLock (CYISpinLock &rSpinLock)
 
 ~CYIAutoSpinLock ()
 
void Relock ()
 
void Unlock ()
 

Constructor & Destructor Documentation

CYIAutoSpinLock::CYIAutoSpinLock ( CYISpinLock rSpinLock)
inline

Constructs a CYIAutoSpinLock and locks m_rSpinLock. The CYISpinLock will automatically unlock when the instance is destroyed.

CYIAutoSpinLock::~CYIAutoSpinLock ( )
inline

Destroys the CYIAutoSpinLock and unlocks m_rSpinLock that was locked by the constructor.

Member Function Documentation

void CYIAutoSpinLock::Relock ( )

Relocks a manually unlocked CYISpinLock.

void CYIAutoSpinLock::Unlock ( )

Unlocks m_rSpinLock. You may relock the CYISpinLock using CYIAutoSpinLock::Relock().


The documentation for this class was generated from the following file: