1
0
mirror of https://github.com/RPCS3/rpcs3.git synced 2024-11-25 12:12:50 +01:00
rpcs3/Utilities/sema.cpp

80 lines
1.1 KiB
C++
Raw Normal View History

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