Skip to content
Snippets Groups Projects
Commit 5ed4eb72 authored by Benjamin Cumming's avatar Benjamin Cumming
Browse files

add double_buffer type

parent 2af3e65b
No related branches found
No related tags found
No related merge requests found
#pragma once
#include <array>
#include <atomic>
#include <util/debug.hpp>
namespace nest {
namespace mc {
namespace util {
template <typename T>
class double_buffer {
private:
std::atomic<int> index_;
std::array<T, 2> buffers_;
int other_index() {
return index_ ? 0 : 1;
}
public:
using value_type = T;
double_buffer() :
index_(0)
{}
double_buffer(double_buffer&&) = delete;
double_buffer(const double_buffer&) = delete;
double_buffer& operator=(const double_buffer&) = delete;
double_buffer& operator=(double_buffer&&) = delete;
void exchange() {
index_ ^= 1;
}
value_type& get() {
return buffers_[index_];
}
const value_type& get() const {
return buffers_[index_];
}
value_type& other() {
return buffers_[other_index()];
}
const value_type& other() const {
return buffers_[other_index()];
}
};
} // namespace util
} // namespace mc
} // namespace nest
......@@ -11,6 +11,7 @@ set(HEADERS
set(TEST_SOURCES
# unit tests
test_algorithms.cpp
test_double_buffer.cpp
test_cell.cpp
test_compartments.cpp
test_event_queue.cpp
......
#include "gtest.h"
#include <util/double_buffer.hpp>
// not much to test here: just test that values passed into the constructor
// are correctly stored in members
TEST(double_buffer, exchange_and_get)
{
using namespace nest::mc::util;
double_buffer<int> buf;
buf.get() = 2134;
buf.exchange();
buf.get() = 8990;
buf.exchange();
EXPECT_EQ(buf.get(), 2134);
EXPECT_EQ(buf.other(), 8990);
buf.exchange();
EXPECT_EQ(buf.get(), 8990);
EXPECT_EQ(buf.other(), 2134);
buf.exchange();
EXPECT_EQ(buf.get(), 2134);
EXPECT_EQ(buf.other(), 8990);
}
TEST(double_buffer, assign_get_other)
{
using namespace nest::mc::util;
double_buffer<std::string> buf;
buf.get() = "1";
buf.other() = "2";
EXPECT_EQ(buf.get(), "1");
EXPECT_EQ(buf.other(), "2");
}
TEST(double_buffer, non_pod)
{
using namespace nest::mc::util;
double_buffer<std::string> buf;
buf.get() = "1";
buf.other() = "2";
EXPECT_EQ(buf.get(), "1");
EXPECT_EQ(buf.other(), "2");
buf.exchange();
EXPECT_EQ(buf.get(), "2");
EXPECT_EQ(buf.other(), "1");
buf.exchange();
EXPECT_EQ(buf.get(), "1");
EXPECT_EQ(buf.other(), "2");
}
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment