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

92 lines
1.3 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();
2023-09-11 11:52:10 +02:00
const u32 value = m_value.load();
2017-02-15 16:07:42 +01:00
2023-09-11 11:52:10 +02:00
if (value & c_value_mask && m_value.compare_and_swap_test(value, value - c_value))
{
2017-02-15 16:07:42 +01:00
return;
}
}
2023-09-11 11:52:10 +02:00
bool waits = false;
2017-02-15 16:07:42 +01:00
while (true)
{
2017-02-15 16:07:42 +01:00
// Try hard way
2023-09-11 11:52:10 +02:00
const u32 value = m_value.fetch_op([&](u32& value)
{
2023-09-11 11:52:10 +02:00
ensure(value != c_waiter_mask); // "semaphore_base: overflow"
if (value & c_value_mask)
{
2023-09-11 11:52:10 +02:00
// Obtain signal
value -= c_value;
2017-02-15 16:07:42 +01:00
2023-09-11 11:52:10 +02:00
if (waits)
2017-02-15 16:07:42 +01:00
{
2023-09-11 11:52:10 +02:00
// Remove waiter
value -= c_waiter;
2017-02-15 16:07:42 +01:00
}
}
2023-09-11 11:52:10 +02:00
else if (!waits)
2017-02-15 16:07:42 +01:00
{
2023-09-11 11:52:10 +02:00
// Add waiter
value += c_waiter;
2017-02-15 16:07:42 +01:00
}
});
2023-09-11 11:52:10 +02:00
if (value & c_value_mask)
2017-02-15 16:07:42 +01:00
{
2023-09-11 11:52:10 +02:00
break;
2017-02-15 16:07:42 +01:00
}
2023-09-11 11:52:10 +02:00
m_value.wait(value + (waits ? 0 : c_waiter));
waits = true;
}
}
2023-09-11 11:52:10 +02:00
void semaphore_base::imp_post(u32 _old)
{
2023-09-11 11:52:10 +02:00
ensure(~_old & c_value_mask); // "semaphore_base: overflow"
2023-09-11 11:52:10 +02:00
if ((_old & c_waiter_mask) / c_waiter > (_old & c_value_mask) / c_value)
{
m_value.notify_one();
}
}
2023-09-11 11:52:10 +02:00
bool semaphore_base::try_post(u32 _max)
{
// Conditional increment
2023-09-11 11:52:10 +02:00
const auto [value, ok] = m_value.fetch_op([&](u32& value)
{
2023-09-11 11:52:10 +02:00
if ((value & c_value_mask) <= _max)
{
2023-09-11 11:52:10 +02:00
value += c_value;
return true;
}
2023-09-11 11:52:10 +02:00
return false;
});
2023-09-11 11:52:10 +02:00
if (!ok)
{
return false;
}
if (value & c_waiter_mask)
{
2017-02-15 16:07:42 +01:00
imp_post(value);
}
2023-09-11 11:52:10 +02:00
return true;
}