Skip to content

Commit

Permalink
MicroSpinLock: Use atomic_exchange instead of `atomic_compare_excha…
Browse files Browse the repository at this point in the history
…nge` (#1971)

Summary:
The lock only has two-states, so `atomic_exchange` works and is as or more performant in any situation.

Pull Request resolved: #1971

Reviewed By: Gownta

Differential Revision: D47343961

Pulled By: Orvid

fbshipit-source-id: 83d56cccc2617bfbd0c27d2464f498ecf1b1ed5e
  • Loading branch information
goldsteinn authored and facebook-github-bot committed Jul 11, 2023
1 parent 1656027 commit 0d361f7
Showing 1 changed file with 5 additions and 9 deletions.
14 changes: 5 additions & 9 deletions folly/synchronization/MicroSpinLock.h
Original file line number Diff line number Diff line change
Expand Up @@ -73,15 +73,15 @@ struct MicroSpinLock {
void init() noexcept { payload()->store(FREE); }

bool try_lock() noexcept {
bool ret = cas(FREE, LOCKED);
bool ret = xchg(LOCKED) == FREE;
annotate_rwlock_try_acquired(
this, annotate_rwlock_level::wrlock, ret, __FILE__, __LINE__);
return ret;
}

void lock() noexcept {
detail::Sleeper sleeper;
while (!cas(FREE, LOCKED)) {
while (xchg(LOCKED) != FREE) {
do {
sleeper.wait();
} while (payload()->load(std::memory_order_relaxed) == LOCKED);
Expand All @@ -103,13 +103,9 @@ struct MicroSpinLock {
return reinterpret_cast<std::atomic<uint8_t>*>(&this->lock_);
}

bool cas(uint8_t compare, uint8_t newVal) noexcept {
return std::atomic_compare_exchange_strong_explicit(
payload(),
&compare,
newVal,
std::memory_order_acquire,
std::memory_order_relaxed);
uint8_t xchg(uint8_t newVal) noexcept {
return std::atomic_exchange_explicit(
payload(), newVal, std::memory_order_acq_rel);
}
};
static_assert(
Expand Down

0 comments on commit 0d361f7

Please sign in to comment.