Skip to content

Commit

Permalink
use relaxed_atomic in BufferedRandomDevice
Browse files Browse the repository at this point in the history
Differential Revision: D31661218

fbshipit-source-id: 48535870ab2b2f86b0d4e9286365fe906110dc3e
  • Loading branch information
yfeldblum authored and facebook-github-bot committed Oct 17, 2021
1 parent e5d8894 commit 0ae0ccc
Showing 1 changed file with 6 additions and 10 deletions.
16 changes: 6 additions & 10 deletions folly/Random.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
#include <folly/Random.h>

#include <array>
#include <atomic>
#include <mutex>
#include <random>

Expand All @@ -30,6 +29,7 @@
#include <folly/portability/Config.h>
#include <folly/portability/SysTime.h>
#include <folly/portability/Unistd.h>
#include <folly/synchronization/RelaxedAtomic.h>

#include <glog/logging.h>

Expand Down Expand Up @@ -92,15 +92,12 @@ class BufferedRandomDevice {
public:
static constexpr size_t kDefaultBufferSize = 128;

static void notifyNewGlobalEpoch() {
globalEpoch_.fetch_add(1, std::memory_order_relaxed);
}
static void notifyNewGlobalEpoch() { ++globalEpoch_; }

explicit BufferedRandomDevice(size_t bufferSize = kDefaultBufferSize);

void get(void* data, size_t size) {
auto const globalEpoch = globalEpoch_.load(std::memory_order_relaxed);
if (LIKELY(globalEpoch == epoch_ && size <= remaining())) {
if (LIKELY(epoch_ == globalEpoch_ && size <= remaining())) {
memcpy(data, ptr_, size);
ptr_ += size;
} else {
Expand All @@ -115,15 +112,15 @@ class BufferedRandomDevice {
return size_t(buffer_.get() + bufferSize_ - ptr_);
}

static std::atomic<size_t> globalEpoch_;
static relaxed_atomic<size_t> globalEpoch_;

size_t epoch_{size_t(-1)}; // refill on first use
const size_t bufferSize_;
std::unique_ptr<unsigned char[]> buffer_;
unsigned char* ptr_;
};

std::atomic<size_t> BufferedRandomDevice::globalEpoch_{0};
relaxed_atomic<size_t> BufferedRandomDevice::globalEpoch_{0};
struct RandomTag {};

BufferedRandomDevice::BufferedRandomDevice(size_t bufferSize)
Expand All @@ -145,8 +142,7 @@ BufferedRandomDevice::BufferedRandomDevice(size_t bufferSize)
}

void BufferedRandomDevice::getSlow(unsigned char* data, size_t size) {
auto const globalEpoch = globalEpoch_.load(std::memory_order_relaxed);
if (globalEpoch != epoch_) {
if (epoch_ != globalEpoch_) {
epoch_ = globalEpoch_;
ptr_ = buffer_.get() + bufferSize_;
}
Expand Down

0 comments on commit 0ae0ccc

Please sign in to comment.