Files
CPP_Core/psc_global_include/Spin_Lock.cpp
T
2026-06-16 10:56:40 +08:00

36 lines
1004 B
C++

#include "Core/Base/global_include.h"
#include <chrono>
namespace Psc {
void Empty_Lock::lock() {}
void Empty_Lock::unlock() {}
bool Empty_Lock::tryLock() {
return true;
}
bool Empty_Lock::tryLock(int durationMillis) {
return true;
}
void Spin_Lock::lock() {
while (flag.test_and_set(std::memory_order_acquire)) {}
}
bool Spin_Lock::tryLock() {
return !flag.test_and_set(std::memory_order_acquire);
}
bool Spin_Lock::tryLock(int durationMillis) {
if (durationMillis == 0) {
return tryLock();
}
auto duration = std::chrono::milliseconds(durationMillis);
auto start = std::chrono::steady_clock::now();
while (std::chrono::steady_clock::now() - start < duration) {
if (tryLock()) {
return true;
}
}
return false;
}
void Spin_Lock::unlock() {
flag.clear(std::memory_order_release);
}
} // namespace Psc