2017-01-24 20:19:52 +00:00
|
|
|
#include "sema.h"
|
|
|
|
|
2017-02-15 15:07:42 +00:00
|
|
|
void semaphore_base::imp_wait()
|
2017-01-24 20:19:52 +00:00
|
|
|
{
|
2017-02-15 15:07:42 +00:00
|
|
|
for (int i = 0; i < 10; i++)
|
2017-01-24 20:19:52 +00:00
|
|
|
{
|
2017-02-15 15:07:42 +00:00
|
|
|
busy_wait();
|
|
|
|
|
|
|
|
const s32 value = m_value.load();
|
|
|
|
|
|
|
|
if (value > 0 && m_value.compare_and_swap_test(value, value - 1))
|
2017-01-24 20:19:52 +00:00
|
|
|
{
|
2017-02-15 15:07:42 +00:00
|
|
|
return;
|
2017-01-24 20:19:52 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-02-15 15:07:42 +00:00
|
|
|
while (true)
|
2017-01-24 20:19:52 +00:00
|
|
|
{
|
2017-02-15 15:07:42 +00:00
|
|
|
// Try hard way
|
2018-09-05 19:28:37 +00:00
|
|
|
const s32 value = m_value.atomic_op([](s32& value)
|
2017-01-24 20:19:52 +00:00
|
|
|
{
|
2017-02-15 15:07:42 +00:00
|
|
|
// Use sign bit to acknowledge waiter presence
|
|
|
|
if (value && value > INT32_MIN)
|
2017-01-24 20:19:52 +00:00
|
|
|
{
|
2017-02-15 15:07:42 +00:00
|
|
|
value--;
|
|
|
|
|
|
|
|
if (value < 0)
|
|
|
|
{
|
|
|
|
// Remove sign bit
|
|
|
|
value -= INT32_MIN;
|
|
|
|
}
|
2017-01-24 20:19:52 +00:00
|
|
|
}
|
2017-02-15 15:07:42 +00:00
|
|
|
else
|
|
|
|
{
|
|
|
|
// Set sign bit
|
|
|
|
value = INT32_MIN;
|
|
|
|
}
|
2018-09-05 19:28:37 +00:00
|
|
|
|
|
|
|
return value;
|
2017-02-15 15:07:42 +00:00
|
|
|
});
|
2017-01-24 20:19:52 +00:00
|
|
|
|
2017-02-15 15:07:42 +00:00
|
|
|
if (value >= 0)
|
|
|
|
{
|
|
|
|
// Signal other waiter to wake up or to restore sign bit
|
2019-07-27 14:08:45 +00:00
|
|
|
m_value.notify_one();
|
2017-02-15 15:07:42 +00:00
|
|
|
return;
|
|
|
|
}
|
2017-01-24 20:19:52 +00:00
|
|
|
|
2019-07-27 14:08:45 +00:00
|
|
|
m_value.wait(value);
|
2017-01-24 20:19:52 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void semaphore_base::imp_post(s32 _old)
|
|
|
|
{
|
2020-12-09 07:47:45 +00:00
|
|
|
ensure(_old < 0); // "semaphore_base: overflow"
|
2017-01-24 20:19:52 +00:00
|
|
|
|
2019-07-27 14:08:45 +00:00
|
|
|
m_value.notify_one();
|
2017-01-24 20:19:52 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
bool semaphore_base::try_post(s32 _max)
|
|
|
|
{
|
|
|
|
// Conditional increment
|
|
|
|
const s32 value = m_value.fetch_op([&](s32& value)
|
|
|
|
{
|
|
|
|
if (value < _max)
|
|
|
|
{
|
2017-02-15 15:07:42 +00:00
|
|
|
value += 1;
|
2017-01-24 20:19:52 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
if (value < 0)
|
|
|
|
{
|
2017-02-15 15:07:42 +00:00
|
|
|
imp_post(value);
|
2017-01-24 20:19:52 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return value < _max;
|
|
|
|
}
|