rpcs3/Utilities/sema.cpp

104 lines
1.6 KiB
C++
Raw Normal View History

#include "sema.h"
#include "sync.h"
2017-02-15 15:07:42 +00:00
void semaphore_base::imp_wait()
{
2017-02-15 15:07:42 +00:00
for (int i = 0; i < 10; i++)
{
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-02-15 15:07:42 +00:00
return;
}
}
2017-02-15 15:07:42 +00:00
#ifdef _WIN32
const s32 value = m_value.fetch_sub(1);
if (value <= 0)
{
2017-02-15 15:07:42 +00:00
NtWaitForKeyedEvent(nullptr, &m_value, false, nullptr);
}
2017-02-15 15:07:42 +00:00
#else
while (true)
{
2017-02-15 15:07:42 +00:00
// Try hard way
const s32 value = m_value.op_fetch([](s32& value)
{
2017-02-15 15:07:42 +00:00
// Use sign bit to acknowledge waiter presence
if (value && value > INT32_MIN)
{
2017-02-15 15:07:42 +00:00
value--;
if (value < 0)
{
// Remove sign bit
value -= INT32_MIN;
}
}
2017-02-15 15:07:42 +00:00
else
{
// Set sign bit
value = INT32_MIN;
}
});
2017-02-15 15:07:42 +00:00
if (value >= 0)
{
// Signal other waiter to wake up or to restore sign bit
futex(&m_value.raw(), FUTEX_WAKE_PRIVATE, 1, nullptr, nullptr, 0);
return;
}
2017-02-15 15:07:42 +00:00
futex(&m_value.raw(), FUTEX_WAIT_PRIVATE, value, nullptr, nullptr, 0);
}
#endif
}
void semaphore_base::imp_post(s32 _old)
{
verify("semaphore_base: overflow" HERE), _old < 0;
#ifdef _WIN32
2017-02-15 15:07:42 +00:00
NtReleaseKeyedEvent(nullptr, &m_value, false, nullptr);
#else
2017-02-15 15:07:42 +00:00
futex(&m_value.raw(), FUTEX_WAKE_PRIVATE, 1, nullptr, nullptr, 0);
#endif
}
bool semaphore_base::try_wait()
{
// Conditional decrement
const s32 value = m_value.fetch_op([](s32& value)
{
2017-02-15 15:07:42 +00:00
if (value > 0)
{
2017-02-15 15:07:42 +00:00
value -= 1;
}
});
2017-02-15 15:07:42 +00:00
return value > 0;
}
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;
}
});
if (value < 0)
{
2017-02-15 15:07:42 +00:00
imp_post(value);
}
return value < _max;
}