Skip to content

Basic: use std::atomic instead of home-grown synch #3006

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 20, 2016
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 9 additions & 7 deletions include/swift/Basic/ThreadSafeRefCounted.h
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
#ifndef SWIFT_BASIC_THREADSAFEREFCOUNTED_H
#define SWIFT_BASIC_THREADSAFEREFCOUNTED_H

#include "llvm/Support/Atomic.h"
#include <atomic>
#include <cassert>

namespace swift {
Expand All @@ -28,18 +28,19 @@ namespace swift {
/// FIXME: This should eventually move to llvm.
template <class Derived>
class ThreadSafeRefCountedBase {
mutable llvm::sys::cas_flag ref_cnt;
mutable std::atomic<unsigned> ref_cnt;

protected:
ThreadSafeRefCountedBase() : ref_cnt(0) {}

public:
void Retain() const {
llvm::sys::AtomicIncrement(&ref_cnt);
ref_cnt.fetch_add(1, std::memory_order_acq_rel);
}

void Release() const {
int refCount = static_cast<int>(llvm::sys::AtomicDecrement(&ref_cnt));
int refCount =
static_cast<int>(ref_cnt.fetch_sub(1, std::memory_order_acq_rel));
assert(refCount >= 0 && "Reference count was already zero.");
if (refCount == 0) delete static_cast<const Derived*>(this);
}
Expand All @@ -52,7 +53,7 @@ class ThreadSafeRefCountedBase {
/// already have virtual methods to enforce dynamic allocation via 'new'.
/// FIXME: This should eventually move to llvm.
class ThreadSafeRefCountedBaseVPTR {
mutable llvm::sys::cas_flag ref_cnt;
mutable std::atomic<unsigned> ref_cnt;
virtual void anchor();

protected:
Expand All @@ -61,11 +62,12 @@ class ThreadSafeRefCountedBaseVPTR {

public:
void Retain() const {
llvm::sys::AtomicIncrement(&ref_cnt);
ref_cnt.fetch_add(1, std::memory_order_acq_rel);
}

void Release() const {
int refCount = static_cast<int>(llvm::sys::AtomicDecrement(&ref_cnt));
int refCount =
static_cast<int>(ref_cnt.fetch_sub(1, std::memory_order_acq_rel));
assert(refCount >= 0 && "Reference count was already zero.");
if (refCount == 0) delete this;
}
Expand Down