Skip to content

Commit

Permalink
Update spinlock.hpp
Browse files Browse the repository at this point in the history
  • Loading branch information
KRM7 committed Mar 29, 2024
1 parent 1af9df9 commit e792f9f
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 9 deletions.
13 changes: 7 additions & 6 deletions src/utility/shared_spinlock.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,12 @@
#define GA_UTILITY_SHARED_SPINLOCK_HPP

#include "utility.hpp"
#include "spinlock.hpp"
#include <atomic>
#include <thread>
#include <tuple>
#include <limits>
#include <cstdint>

#include "spinlock.hpp"

namespace gapp::detail
{
class shared_spinlock
Expand All @@ -20,9 +19,8 @@ namespace gapp::detail
{
while (true)
{
while (cntr_.load(std::memory_order_relaxed)) GAPP_PAUSE();
if (try_lock()) break;
std::this_thread::yield();
while (cntr_.load(std::memory_order_relaxed)) GAPP_PAUSE();
}
}

Expand All @@ -34,14 +32,16 @@ namespace gapp::detail

void unlock() noexcept
{
//__tsan_release(&cntr_);
cntr_.fetch_sub(WRITER, std::memory_order_release);
}

void lock_shared() noexcept
{
cntr_.fetch_add(1, std::memory_order_release);
while (cntr_.load(std::memory_order_relaxed) >= WRITER) GAPP_PAUSE();
std::ignore = cntr_.load(std::memory_order_acquire);
std::atomic_thread_fence(std::memory_order_acquire);
__tsan_acquire(&cntr_);
}

bool try_lock_shared() noexcept
Expand All @@ -54,6 +54,7 @@ namespace gapp::detail

void unlock_shared() noexcept
{
//__tsan_release(&cntr_);
cntr_.fetch_sub(1, std::memory_order_release);
}

Expand Down
17 changes: 14 additions & 3 deletions src/utility/spinlock.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,13 @@

#include "utility.hpp"
#include <atomic>
#include <thread>

#if __has_feature(thread_sanitizer) && __has_include(<sanitizer/tsan_interface.h>)
#include <sanitizer/tsan_interface.h>
#else
#define __tsan_acquire(...)
#define __tsan_release(...)
#endif

namespace gapp::detail
{
Expand All @@ -16,9 +22,13 @@ namespace gapp::detail
{
while (true)
{
if (!locked_.test_and_set(std::memory_order_relaxed))
{
std::atomic_thread_fence(std::memory_order_acquire);
__tsan_acquire(&locked_);
break;
}
while (locked_.test(std::memory_order_relaxed)) GAPP_PAUSE();
if (!locked_.test_and_set(std::memory_order_acquire)) break;
std::this_thread::yield();
}
}

Expand All @@ -30,6 +40,7 @@ namespace gapp::detail

void unlock() noexcept
{
//__tsan_release(&locked_);
locked_.clear(std::memory_order_release);
}

Expand Down

0 comments on commit e792f9f

Please sign in to comment.