首次提交
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
#include <chrono>
|
||||
#include "SpinLock.h"
|
||||
namespace Toolbox {
|
||||
void SpinLock::lock() {
|
||||
while (flag.test_and_set(std::memory_order_acquire)) {}
|
||||
}
|
||||
bool SpinLock::tryLock() {
|
||||
return !flag.test_and_set(std::memory_order_acquire);
|
||||
}
|
||||
bool SpinLock::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 SpinLock::unlock() {
|
||||
flag.clear(std::memory_order_release);
|
||||
}
|
||||
SpinLockGuard::~SpinLockGuard() {
|
||||
if (mLock) mLock->unlock();
|
||||
}
|
||||
SpinLockGuard::SpinLockGuard(SpinLock *lock) : mLock(lock) {
|
||||
if (mLock) mLock->lock();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user