Skip to content

Instantly share code, notes, and snippets.

@wilburding
Created April 5, 2013 14:06
Show Gist options
  • Save wilburding/5319521 to your computer and use it in GitHub Desktop.
Save wilburding/5319521 to your computer and use it in GitHub Desktop.
tagged pointer for lockfree algorithm(64bit assumed)
template<class T>
class TaggedPointer
{
public:
explicit TaggedPointer(T* ptr = nullptr)
:ptr_(ptr),
counter_(0)
{}
inline T* load_ptr() noexcept
{
return ptr_.load(memory_order_acquire);
}
inline uint64_t load_counter() noexcept
{
return counter_.load(memory_order_acquire);
}
inline bool compare_exchange(T* expected_ptr, uint64_t expected_counter, T* desired_ptr, uint64_t desired_counter) noexcept
{
bool result;
asm volatile (
"lock cmpxchg16b %0;"
"setz %3;"
:"+m"(*this), "+a"(expected_ptr), "+d"(expected_counter), "=q"(result)
:"b"(desired_ptr), "c"(desired_counter)
:"cc", "memory"
);
return result;
}
private:
// atomic in case of compiler keep in registers?
atomic<T*> ptr_;
atomic<uint64_t> counter_;
} __attribute__ (( __aligned__(16) ));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment