I read spin lock code from here, especially this part
inline void Enter(void)
{
int prev_s;
do
{
prev_s = TestAndSet(&m_s, 0);
if (m_s == 0 && prev_s == 1)
{
break;
}
// reluinquish current timeslice (can only
// be used when OS available and
// we do NOT want to 'spin')
// HWSleep(0);
}
while (true);
}
Why do we need to test two conditions m_s == 0 && prev_s == 1? I think just test prev_s == 1 should be enough. Any ideas?
EDIT: version 2. should we fix in this way if there is a bug?
inline void Enter(void)
{
do
{
if (m_s == 0 && 1 == TestAndSet(&m_s, 0))
{
break;
}
// reluinquish current timeslice (can only
// be used when OS available and
// we do NOT want to 'spin')
// HWSleep(0);
}
while (true);
}
EDIT: version 3. I think version 3 from functional level is correct, but performance is not good enough since each time we need to write, no read test ahead. Is my understanding correct?
inline void Enter(void)
{
do
{
if (1 == TestAndSet(&m_s, 0))
{
break;
}
// reluinquish current timeslice (can only
// be used when OS available and
// we do NOT want to 'spin')
// HWSleep(0);
}
while (true);
}
@dragonfly, here is my bug fix version 4 (fixed a bug in version 2 as you pointed out), could you review whether it is correct please? Thanks!
EDIT: version 4.
inline void Enter(void)
{
do
{
if (m_s == 1 && 1 == TestAndSet(&m_s, 0))
{
break;
}
// reluinquish current timeslice (can only
// be used when OS available and
// we do NOT want to 'spin')
// HWSleep(0);
}
while (true);
}