Adds locking versions of delay line and flat demand memory

Enables easier multi-threaded simulation by providing some base classes
with mutex protections.

PiperOrigin-RevId: 1009929353
Change-Id: I1dab3739977b6d4e579251cd299e32ed45f07ed2
diff --git a/mpact/sim/generic/BUILD b/mpact/sim/generic/BUILD
index dc18fdd..3fbb3f4 100644
--- a/mpact/sim/generic/BUILD
+++ b/mpact/sim/generic/BUILD
@@ -41,6 +41,7 @@
         "function_delay_line.h",
         "immediate_operand.h",
         "literal_operand.h",
+        "locking_delay_line.h",
         "operand_interface.h",
         "ref_count.h",
         "resource_bitset.h",
@@ -61,6 +62,7 @@
         "@abseil-cpp//absl/status",
         "@abseil-cpp//absl/status:statusor",
         "@abseil-cpp//absl/strings",
+        "@abseil-cpp//absl/synchronization",
         "@abseil-cpp//absl/types:any",
         "@abseil-cpp//absl/types:span",
     ],
diff --git a/mpact/sim/generic/arch_state.cc b/mpact/sim/generic/arch_state.cc
index 4a82638..8c2dc62 100644
--- a/mpact/sim/generic/arch_state.cc
+++ b/mpact/sim/generic/arch_state.cc
@@ -96,7 +96,6 @@
   fifos_.clear();
   pointer_set.clear();
   delete db_factory_;
-
   delete program_error_controller_;
 }
 
diff --git a/mpact/sim/generic/arch_state.h b/mpact/sim/generic/arch_state.h
index 674795b..ca83feb 100644
--- a/mpact/sim/generic/arch_state.h
+++ b/mpact/sim/generic/arch_state.h
@@ -102,7 +102,7 @@
   }
 
   // Advance all registered delay lines by one cycle.
-  inline void AdvanceDelayLines() {
+  void AdvanceDelayLines() {
     cycle_++;
     for (auto dl : delay_lines_) {
       dl->Advance();
@@ -141,10 +141,16 @@
   DataBufferDelayLine* data_buffer_delay_line() const {
     return data_buffer_delay_line_;
   }
+  void set_data_buffer_delay_line(DataBufferDelayLine* data_buffer_delay_line) {
+    data_buffer_delay_line_ = data_buffer_delay_line;
+  }
   // The void() function delay line
   FunctionDelayLine* function_delay_line() const {
     return function_delay_line_;
   }
+  void set_function_delay_line(FunctionDelayLine* function_delay_line) {
+    function_delay_line_ = function_delay_line;
+  }
   // Returns the PC operand interface (read only)
   SourceOperandInterface* pc_operand() const { return pc_operand_; }
   // Used to report program error (or even internal simulator errors).
diff --git a/mpact/sim/generic/data_buffer.cc b/mpact/sim/generic/data_buffer.cc
index 5482a56..36d644e 100644
--- a/mpact/sim/generic/data_buffer.cc
+++ b/mpact/sim/generic/data_buffer.cc
@@ -15,12 +15,16 @@
 #include "mpact/sim/generic/data_buffer.h"
 
 #include <cstdint>
+#include <vector>
+
+#include "absl/synchronization/mutex.h"
 
 namespace mpact {
 namespace sim {
 namespace generic {
 
 DataBufferFactory::~DataBufferFactory() { Clear(); }
+LockingDataBufferFactory::~LockingDataBufferFactory() { Clear(); }
 
 // Free up all allocated DataBuffers held in the db_store.
 void DataBufferFactory::Clear() {
@@ -38,6 +42,22 @@
   }
 }
 
+void LockingDataBufferFactory::Clear() {
+  absl::MutexLock lock(&mutex_);
+  for (int i = 0; i <= kShortSize; i++) {
+    for (auto db : short_free_list_[i]) {
+      delete db;
+    }
+    short_free_list_[i].clear();
+  }
+  for (auto bucket : free_list_) {
+    for (auto db : bucket.second) {
+      delete db;
+    }
+    bucket.second.clear();
+  }
+}
+
 // Allocate a DataBuffer and then copy the value of the source DB into
 // the newly allocated buffer.
 DataBuffer* DataBufferFactory::MakeCopyOf(const DataBuffer* src_db) {
@@ -46,6 +66,12 @@
   return db;
 }
 
+DataBuffer* LockingDataBufferFactory::MakeCopyOf(const DataBuffer* src_db) {
+  DataBuffer* db = Allocate(src_db->size<uint8_t>());
+  db->CopyFrom(src_db);
+  return db;
+}
+
 DataBuffer::DataBuffer(unsigned size) : size_(size) {
   // Allocate using unsigned char to guarantee appropriate alignment according
   // to C++ standard 5.3.4 (11).
@@ -66,6 +92,7 @@
     delay_line_->Add(latency, this, destination_);
   }
 }
+
 }  // namespace generic
 }  // namespace sim
 }  // namespace mpact
diff --git a/mpact/sim/generic/data_buffer.h b/mpact/sim/generic/data_buffer.h
index 2d8a480..46e34df 100644
--- a/mpact/sim/generic/data_buffer.h
+++ b/mpact/sim/generic/data_buffer.h
@@ -20,7 +20,9 @@
 #include <vector>
 
 #include "absl/base/macros.h"
+#include "absl/base/thread_annotations.h"
 #include "absl/container/btree_map.h"
+#include "absl/synchronization/mutex.h"
 #include "absl/types/span.h"
 #include "mpact/sim/generic/delay_line.h"
 #include "mpact/sim/generic/ref_count.h"
@@ -46,11 +48,24 @@
 
 class DataBuffer;
 
+namespace internal {
+
+// Data factory base class.
+class DataBufferFactoryBase {
+ public:
+  virtual ~DataBufferFactoryBase() = default;
+  // Method called by DataBuffer to recycle itself.
+  virtual void Recycle(DataBuffer* db) = 0;
+  DataBuffer* MakeCopyOf(const DataBuffer* src_db);
+};
+
+}  // namespace internal
+
 // Factory class for DataBuffer. Note that a new data buffer can be
 // either obtained through Allocate or MakeCopyOf. The latter call is useful
 // when only some of the bit/bytes/words of the original value of an item of
 // processor state will be modified by a semantic function.
-class DataBufferFactory {
+class DataBufferFactory : public internal::DataBufferFactoryBase {
   static constexpr int kShortSize = 4096;
   friend class DataBuffer;
 
@@ -82,8 +97,8 @@
 
  private:
   // Moves the DataBuffer instance on to a free list based on the size of the
-  // internal buffer. This method is only called by DataBuffere instances.
-  inline void Recycle(DataBuffer* db);
+  // internal buffer. This method is only called by DataBuffer instances.
+  void Recycle(DataBuffer* db) final;
   // The DBStore keeps free DataBuffer instances in free lists by size of
   // the data_ store. That way runtime overhead is reduced, since DataBuffer
   // objects are allocated very frequently.
@@ -95,6 +110,57 @@
   DataBufferFreeList free_list_;
 };
 
+// Factory class for DataBuffer. Note that a new data buffer can be
+// either obtained through Allocate or MakeCopyOf. The latter call is useful
+// when only some of the bit/bytes/words of the original value of an item of
+// processor state will be modified by a semantic function.
+class LockingDataBufferFactory : public internal::DataBufferFactoryBase {
+  static constexpr int kShortSize = 4096;
+  friend class DataBuffer;
+
+ public:
+  // Constructor and Destructor.
+  LockingDataBufferFactory() = default;
+  virtual ~LockingDataBufferFactory();
+
+  // Allocates a DataBuffer instance with a buffer size of num instances of T.
+  // The free list is searched before falling back on using new.
+  template <typename T>
+  DataBuffer* Allocate(int num) {
+    return Allocate(sizeof(T) * num);
+  }
+
+  // Allocates a DataBuffer instance with a buffer of size bytes. The free
+  // list is searched before falling back on using new.
+  inline DataBuffer* Allocate(int size) ABSL_LOCKS_EXCLUDED(mutex_);
+
+  // Allocates a new DataBuffer instance with the same size as db and
+  // initializes the contents of the internal buffer to the value of that of
+  // db - without changing db. Except for the memcpy this method acts just like
+  // Allocate()
+  DataBuffer* MakeCopyOf(const DataBuffer* src_db);
+
+  // Clears and frees up all the objects contained in the DBStore that holds
+  // the recycled DataBuffers.
+  void Clear() ABSL_LOCKS_EXCLUDED(mutex_);
+
+ private:
+  // Moves the DataBuffer instance on to a free list based on the size of the
+  // internal buffer. This method is only called by DataBuffere instances.
+  void Recycle(DataBuffer* db) final ABSL_LOCKS_EXCLUDED(mutex_);
+  // The DBStore keeps free DataBuffer instances in free lists by size of
+  // the data_ store. That way runtime overhead is reduced, since DataBuffer
+  // objects are allocated very frequently.
+  //
+  // map <size of data buffer data_, list of free data buffers >
+  using DataBufferFreeList = absl::btree_map<int, std::vector<DataBuffer*>>;
+
+  absl::Mutex mutex_;
+  std::vector<DataBuffer*> short_free_list_[kShortSize + 1] ABSL_GUARDED_BY(
+      mutex_);
+  DataBufferFreeList free_list_ ABSL_GUARDED_BY(mutex_);
+};
+
 // DataBufferDestination is an interface that is inherited by the simulated
 // state objects that use data buffers. This interface is used by the
 // simulator to set a new DataBuffer object as the value of the state object,
@@ -144,6 +210,7 @@
 
 class DataBuffer : public ReferenceCount {
   friend class DataBufferFactory;
+  friend class LockingDataBufferFactory;
 
  public:
   ~DataBuffer() override;
@@ -262,7 +329,7 @@
 
  private:
   explicit DataBuffer(unsigned size);
-  DataBufferFactory* db_factory_;
+  internal::DataBufferFactoryBase* db_factory_;
   DataBufferDelayLine* delay_line_;
   DataBufferDestination* destination_;
   int latency_;
@@ -313,6 +380,21 @@
   }
 }
 
+inline void LockingDataBufferFactory::Recycle(DataBuffer* db) {
+  absl::MutexLock lock(&mutex_);
+  int size = db->size<uint8_t>();
+  if (size <= kShortSize) {
+    short_free_list_[size].push_back(db);
+  } else {
+    auto ptr = free_list_.find(size);
+    if (ptr != free_list_.end()) {
+      ptr->second.push_back(db);
+      return;
+    }
+    free_list_.emplace(size, std::vector<DataBuffer*>{db});
+  }
+}
+
 // Search through the DataBuffer recycled store to see if there is a buffer
 // of the appropriate size. If not, allocate a new one.
 inline DataBuffer* DataBufferFactory::Allocate(int size) {
@@ -347,6 +429,39 @@
   return db;
 }
 
+inline DataBuffer* LockingDataBufferFactory::Allocate(int size) {
+  DataBuffer* db = nullptr;
+  {
+    absl::MutexLock lock(&mutex_);
+    if (size <= kShortSize) {
+      auto& free_list = short_free_list_[size];
+      if (!free_list.empty()) {
+        db = free_list.back();
+        free_list.pop_back();
+        db->IncRef();
+        db->ResetCounts();
+        return db;
+      }
+    } else {
+      auto ptr = free_list_.find(size);
+      if (ptr != free_list_.end()) {
+        if (!ptr->second.empty()) {
+          db = ptr->second.back();
+          ptr->second.pop_back();
+          db->IncRef();
+          db->ResetCounts();
+          return db;
+        }
+      }
+    }
+  }
+
+  db = new DataBuffer(size);
+  db->db_factory_ = this;
+
+  return db;
+}
+
 }  // namespace generic
 }  // namespace sim
 }  // namespace mpact
diff --git a/mpact/sim/generic/delay_line.h b/mpact/sim/generic/delay_line.h
index 7947358..0472942 100644
--- a/mpact/sim/generic/delay_line.h
+++ b/mpact/sim/generic/delay_line.h
@@ -87,9 +87,10 @@
     if (latency >= static_cast<int>(delay_line_.size())) {
       Resize(latency);
     }
+    ++num_entries_;
     int pos = (latency + current_) & mask_;
     delay_line_[pos].emplace_back(args...);
-    return ++num_entries_;
+    return num_entries_;
   }
 
   // Advances the delay line by a cycle and performs any actions required.
diff --git a/mpact/sim/generic/function_delay_line.h b/mpact/sim/generic/function_delay_line.h
index ebdd2e6..fa92aed 100644
--- a/mpact/sim/generic/function_delay_line.h
+++ b/mpact/sim/generic/function_delay_line.h
@@ -22,6 +22,7 @@
 #include <functional>
 
 #include "mpact/sim/generic/delay_line.h"
+#include "mpact/sim/generic/locking_delay_line.h"
 
 namespace mpact {
 namespace sim {
@@ -45,6 +46,7 @@
 };
 
 using FunctionDelayLine = DelayLine<FunctionDelayRecord>;
+using LockingFunctionDelayLine = LockingDelayLine<FunctionDelayRecord>;
 
 }  // namespace generic
 }  // namespace sim
diff --git a/mpact/sim/generic/locking_delay_line.h b/mpact/sim/generic/locking_delay_line.h
new file mode 100644
index 0000000..0dc59b5
--- /dev/null
+++ b/mpact/sim/generic/locking_delay_line.h
@@ -0,0 +1,170 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef MPACT_SIM_GENERIC_LOCKING_FUNCTION_DELAY_LINE__H_
+#define MPACT_SIM_GENERIC_LOCKING_FUNCTION_DELAY_LINE__H_
+
+#include <cstdint>
+#include <vector>
+
+#include "absl/base/thread_annotations.h"
+#include "absl/numeric/bits.h"
+#include "absl/synchronization/mutex.h"
+#include "mpact/sim/generic/delay_line_interface.h"
+
+namespace mpact {
+namespace sim {
+namespace generic {
+
+// The DelayLine is the generic class for implementing delay lines for
+// values and deferred function calls. It allows one or more "actions" to
+// be scheduled to be performed a number of cycles (calls to Advance()) in
+// the future. The exact action to be performed is determined by the template
+// parameter type DelayRecord. Abstractly, the DelayLine class is a circular
+// buffer of lists of DelayRecords. It is implemented as a vector
+// of vectors of DelayRecord instances. A given index into the first dimension
+// contains a vector of the set of DelayRecord instances that specifies the
+// "actions" that are performed for a given cycle in the future (based on its
+// distance from the current_ index (mod vector size).
+//
+// The DelayLine circular buffer is always a power of two to make the
+// mod operator cheap.
+//
+// The DelayLine class can be instantiated by passing in the DelayRecord
+// type as a template argument. The DelayRecord must have a void Apply()
+// method that performs the actions intended once the delay line has advanced
+// to that record. Additionally, the DelayRecord type must have a constructor
+// that can be called by std::vector::emplace_back().
+//
+// For instance, if the DelayRecord consists of a pointer and a value (with the
+// intent that after a delay, the value gets written to the object pointed to
+// by that pointer) a reasonable DelayRecord would be.
+//
+// struct MyDelayRecord {
+//   int *destination;
+//   int value;
+//   void Apply() {
+//     *destination = value;
+//   }
+//   MyDelayRecord(int *dest, int val) : destination(dest), value(val) {}
+// };
+//
+// This class is thread safe.
+template <typename DelayRecord>
+class LockingDelayLine : public DelayLineInterface {
+ public:
+  constexpr static int kDefaultDelayLineDepth = 16;
+  // Constructor that takes an initial minimum size
+  explicit LockingDelayLine(uint32_t min_size)
+      : delay_line_(absl::bit_ceil(min_size)), current_(0), num_entries_(0) {
+    mask_ = delay_line_.size() - 1;
+  }
+
+  // Default constructor and destructors
+  LockingDelayLine() : LockingDelayLine(kDefaultDelayLineDepth) {}
+  ~LockingDelayLine() override = default;
+
+  // Add an item to the delay line with the given latency. The Ts... argument
+  // pack is the set of arguments to the constructor of the DelayRecord which
+  // is the value record type for the LockingDelayLine. Returns the total number
+  // of valid elements.
+  template <typename... Ts>
+  int Add(int latency, Ts... args) ABSL_LOCKS_EXCLUDED(delay_line_lock_) {
+    absl::MutexLock dl(&delay_line_lock_);
+    // If the latency is longer than the delay line, resize the delay line.
+    if (latency >= static_cast<int>(delay_line_.size())) {
+      Resize(latency);
+    }
+    ++num_entries_;
+    int pos = (latency + current_) & mask_;
+    delay_line_[pos].emplace_back(args...);
+    return num_entries_;
+  }
+
+  // Advances the delay line by a cycle and performs any actions required.
+  // Depending on the record type R, the actual action may vary. The initial
+  // actions supported generically are writing back a data buffer to a state
+  // instance and calling a function. Additional actions can be created by
+  // deriving new delay lines as needed. Returns the number of valid entries
+  // left in the delay line.
+  int Advance() override ABSL_LOCKS_EXCLUDED(delay_line_lock_) {
+    std::vector<DelayRecord> records;
+    {
+      absl::MutexLock dl(&delay_line_lock_);
+      current_ = (current_ + 1) & mask_;
+      records.swap(delay_line_[current_]);
+      num_entries_ -= records.size();
+    }
+    for (auto& rec : records) {
+      rec.Apply();
+    }
+    absl::ReaderMutexLock dl(&delay_line_lock_);
+    return num_entries_;
+  }
+
+  // Returns true if the delay line is empty.
+  bool IsEmpty() const override ABSL_LOCKS_EXCLUDED(delay_line_lock_) {
+    absl::ReaderMutexLock dl(&delay_line_lock_);
+    return num_entries_ == 0;
+  }
+
+  bool IsEmptyLocked() const ABSL_SHARED_LOCKS_REQUIRED(delay_line_lock_) {
+    return num_entries_ == 0;
+  }
+
+  absl::Mutex& delay_line_lock() ABSL_LOCK_RETURNED(delay_line_lock_) {
+    return delay_line_lock_;
+  }
+
+ private:
+  // If the latency is >= the delay line length, the delay line has to be
+  // resized so the latency is covered.
+  void Resize(uint32_t min_size) {
+    // Compute a new size that's >= min_size and is a power of 2
+    // Given that the initial size is a power of two, multiplying the
+    // current size by two until it's greater or equal to min_size is
+    // sufficient.
+    uint32_t prev_size = delay_line_.size();
+
+    if (min_size < prev_size) {
+      return;
+    }
+
+    uint32_t new_size = absl::bit_ceil(min_size);
+
+    mask_ = new_size - 1;
+    delay_line_.resize(new_size);
+
+    // now need to move elements from 0 to current-1 to new locations.
+    for (int index = 0; index < current_; ++index) {
+      if (!delay_line_[index].empty()) {
+        delay_line_[prev_size + index] = delay_line_[index];
+        delay_line_[index].clear();
+      }
+    }
+  }
+
+  std::vector<std::vector<DelayRecord>> delay_line_
+      ABSL_GUARDED_BY(delay_line_lock_);
+  int current_ ABSL_GUARDED_BY(delay_line_lock_);
+  int mask_ ABSL_GUARDED_BY(delay_line_lock_);
+  uint32_t num_entries_ ABSL_GUARDED_BY(delay_line_lock_);
+  mutable absl::Mutex delay_line_lock_;
+};
+
+}  // namespace generic
+}  // namespace sim
+}  // namespace mpact
+
+#endif  // MPACT_SIM_GENERIC_LOCKING_FUNCTION_DELAY_LINE__H_
diff --git a/mpact/sim/generic/test/BUILD b/mpact/sim/generic/test/BUILD
index 80c6ef7..46159e7 100644
--- a/mpact/sim/generic/test/BUILD
+++ b/mpact/sim/generic/test/BUILD
@@ -32,6 +32,17 @@
 )
 
 cc_test(
+    name = "locking_data_buffer_test",
+    size = "small",
+    srcs = ["locking_data_buffer_test.cc"],
+    deps = [
+        "//mpact/sim/generic:core",
+        "@com_google_googletest//:gtest",
+        "@com_google_googletest//:gtest_main",
+    ],
+)
+
+cc_test(
     name = "delay_line_test",
     size = "small",
     srcs = ["delay_line_test.cc"],
diff --git a/mpact/sim/generic/test/locking_data_buffer_test.cc b/mpact/sim/generic/test/locking_data_buffer_test.cc
new file mode 100644
index 0000000..3b77f85
--- /dev/null
+++ b/mpact/sim/generic/test/locking_data_buffer_test.cc
@@ -0,0 +1,149 @@
+// Copyright 2023 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include <cstddef>
+#include <cstdint>
+#include <vector>
+
+#include "googlemock/include/gmock/gmock.h"
+#include "googletest/include/gtest/gtest.h"
+#include "mpact/sim/generic/data_buffer.h"
+
+namespace mpact {
+namespace sim {
+namespace generic {
+namespace {
+
+// Test fixture that instantiates the factory class for DataBuffers.
+class DataBufferTest : public testing::Test {
+ protected:
+  DataBufferTest() { db_factory_ = new LockingDataBufferFactory(); }
+
+  ~DataBufferTest() override { delete db_factory_; }
+
+  LockingDataBufferFactory* db_factory_;
+};
+
+// Test that DataBufferFactory allocates the right sizes.
+TEST_F(DataBufferTest, DataBufferFactoryAllocate) {
+  DataBuffer* db8_1 = db_factory_->Allocate<uint32_t>(8);
+  EXPECT_EQ(db8_1->size<uint32_t>(), 8);
+  EXPECT_EQ(db8_1->size<uint8_t>(), 32);
+  EXPECT_EQ(db8_1->ref_count(), 1);
+
+  DataBuffer* db4_1 = db_factory_->Allocate<uint32_t>(4);
+  EXPECT_EQ(db4_1->size<uint32_t>(), 4);
+  EXPECT_EQ(db4_1->size<uint8_t>(), 16);
+  EXPECT_EQ(db4_1->ref_count(), 1);
+
+  db8_1->DecRef();
+  db4_1->DecRef();
+}
+
+// Test that DataBuffers are allocated and recycled.
+TEST_F(DataBufferTest, DataBufferFactoryAllocateRecycleAllocate) {
+  DataBuffer* db8_1 = db_factory_->Allocate<uint32_t>(8);
+
+  db8_1->DecRef();
+
+  DataBuffer* db4_1 = db_factory_->Allocate<uint32_t>(4);
+  EXPECT_NE(db8_1, db4_1);
+
+  db4_1->DecRef();
+
+  DataBuffer* db8_2 = db_factory_->Allocate<uint32_t>(8);
+  DataBuffer* db4_2 = db_factory_->Allocate<uint32_t>(4);
+
+  EXPECT_EQ(db8_1, db8_2);
+  EXPECT_EQ(db4_1, db4_2);
+  EXPECT_NE(db8_2, db4_2);
+
+  db8_2->DecRef();
+  db4_2->DecRef();
+}
+
+// Test that MakeCopyOf allocates a DataBuffer with the content copied from
+// the source DataBuffer.
+TEST_F(DataBufferTest, DataBufferFactoryMakeCopyOf) {
+  const uint32_t kValues[] = {0x01020304, 0xDEADBEEF, 0xA5A55A5A, 0xF0F00F0F};
+  const int kSize = 4;
+
+  DataBuffer* db_source = db_factory_->Allocate<uint32_t>(kSize);
+
+  for (int index = 0; index < kSize; index++) {
+    db_source->Set<uint32_t>(index, kValues[index]);
+  }
+
+  DataBuffer* db_dest = db_factory_->MakeCopyOf(db_source);
+
+  EXPECT_NE(db_source, db_dest);
+  EXPECT_EQ(db_source->size<uint32_t>(), db_dest->size<uint32_t>());
+
+  for (int index = 0; index < kSize; index++) {
+    EXPECT_EQ(db_dest->Get<uint32_t>(index), kValues[index]);
+  }
+
+  db_source->DecRef();
+  db_dest->DecRef();
+}
+
+// Test vector/array based Set and Get of Databuffer.
+TEST_F(DataBufferTest, DataBufferVectorSet) {
+  // First use a const vector.
+  const std::vector<uint32_t> kValueVec{0x01020304, 0xDEADBEEF, 0xA5A55A5A,
+                                        0xF0F00F0F};
+
+  DataBuffer* db = db_factory_->Allocate<uint32_t>(kValueVec.size());
+  db->Set<uint32_t>(kValueVec);
+
+  for (size_t index = 0; index < kValueVec.size(); index++) {
+    EXPECT_EQ(db->Get<uint32_t>(index), kValueVec[index]);
+  }
+  EXPECT_THAT(db->Get<uint32_t>(), testing::ElementsAreArray(kValueVec));
+
+  // Next try a const array.
+  const uint32_t kValueArray[] = {0x01010101, 0x02020202, 0x03030303,
+                                  0x04040404};
+  db->Set<uint32_t>(kValueArray);
+
+  for (size_t index = 0; index < kValueVec.size(); index++) {
+    EXPECT_EQ(db->Get<uint32_t>(index), kValueArray[index]);
+  }
+  EXPECT_THAT(db->Get<uint32_t>(), testing::ElementsAreArray(kValueArray));
+
+  db->DecRef();
+}
+
+// Test raw pointer use with a struct.
+TEST_F(DataBufferTest, DataBufferRawPointer) {
+  struct MyTest {
+    bool a;
+    uint16_t b;
+    uint32_t c;
+    uint64_t d;
+    float x;
+    double y;
+  };
+
+  DataBuffer* db = db_factory_->Allocate(sizeof(MyTest));
+  EXPECT_EQ(sizeof(MyTest), db->size<unsigned char>());
+  MyTest* my_test = reinterpret_cast<MyTest*>(db->raw_ptr());
+  my_test->y = 3.14;
+  db->DecRef();
+}
+
+}  // namespace
+}  // namespace generic
+}  // namespace sim
+}  // namespace mpact
diff --git a/mpact/sim/util/memory/BUILD b/mpact/sim/util/memory/BUILD
index 492aa32..14e4b0b 100644
--- a/mpact/sim/util/memory/BUILD
+++ b/mpact/sim/util/memory/BUILD
@@ -28,6 +28,7 @@
         "atomic_tagged_memory.cc",
         "flat_demand_memory.cc",
         "flat_memory.cc",
+        "locking_flat_demand_memory.cc",
         "memory_router.cc",
         "memory_use_profiler.cc",
         "memory_watcher.cc",
@@ -41,6 +42,7 @@
         "atomic_tagged_memory.h",
         "flat_demand_memory.h",
         "flat_memory.h",
+        "locking_flat_demand_memory.h",
         "memory_interface.h",
         "memory_router.h",
         "memory_use_profiler.h",
@@ -65,6 +67,7 @@
         "@abseil-cpp//absl/status",
         "@abseil-cpp//absl/strings",
         "@abseil-cpp//absl/strings:str_format",
+        "@abseil-cpp//absl/synchronization",
     ],
 )
 
diff --git a/mpact/sim/util/memory/flat_demand_memory.cc b/mpact/sim/util/memory/flat_demand_memory.cc
index 841d85f..1453325 100644
--- a/mpact/sim/util/memory/flat_demand_memory.cc
+++ b/mpact/sim/util/memory/flat_demand_memory.cc
@@ -184,9 +184,10 @@
 
     uint8_t* block;
     if (iter == block_map_.end()) {
+      // In this case we need to allocate a new block.
       block = new uint8_t[allocation_byte_size_];
-      block_map_.insert(std::make_pair(block_address, block));
       std::memset(block, fill_value_, allocation_byte_size_);
+      block_map_.insert(std::make_pair(block_address, block));
     } else {
       block = iter->second;
     }
diff --git a/mpact/sim/util/memory/locking_flat_demand_memory.cc b/mpact/sim/util/memory/locking_flat_demand_memory.cc
new file mode 100644
index 0000000..25d3ab8
--- /dev/null
+++ b/mpact/sim/util/memory/locking_flat_demand_memory.cc
@@ -0,0 +1,242 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "mpact/sim/util/memory/locking_flat_demand_memory.h"
+
+#include <algorithm>
+#include <cstdint>
+#include <cstring>
+#include <utility>
+
+#include "absl/base/macros.h"
+#include "absl/container/flat_hash_map.h"
+#include "absl/log/log.h"
+#include "absl/numeric/bits.h"
+#include "absl/strings/str_format.h"
+#include "absl/synchronization/mutex.h"
+
+namespace mpact::sim::util {
+
+LockingFlatDemandMemory::LockingFlatDemandMemory(uint64_t memory_size_in_units,
+                                                 uint64_t base_address,
+                                                 unsigned addressable_unit_size,
+                                                 uint8_t fill)
+    : base_address_(base_address),
+      max_address_(base_address + memory_size_in_units),
+      fill_value_(fill),
+      allocation_byte_size_(kAllocationSize * addressable_unit_size) {
+  // Compute the addressable unit shift.
+  ABSL_HARDENING_ASSERT(
+      (addressable_unit_size != 0) &&
+      ((addressable_unit_size & (addressable_unit_size - 1)) == 0));
+  addressable_unit_shift_ = absl::bit_width(addressable_unit_size) - 1;
+}
+
+// Delete all the allocated blocks.
+LockingFlatDemandMemory::~LockingFlatDemandMemory() { Clear(); }
+
+void LockingFlatDemandMemory::Load(uint64_t address, DataBuffer* db,
+                                   Instruction* inst, ReferenceCount* context) {
+  int size_in_units = db->size<uint8_t>() >> addressable_unit_shift_;
+  uint64_t high = address + size_in_units;
+  if (address < base_address_ || high > max_address_) [[unlikely]] {
+    LOG(WARNING) << absl::StrFormat(
+        "Load access [%x, %x] out of bounds [%x, %x]\n", address, high,
+        base_address_, max_address_);
+  }
+  if (size_in_units <= 0) [[unlikely]] {
+    LOG(ERROR) << absl::StrFormat("Size in units %d is not positive\n",
+                                  size_in_units);
+    ABSL_HARDENING_ASSERT(false);
+  }
+  uint8_t* byte_ptr = static_cast<uint8_t*>(db->raw_ptr());
+  // Load the data into the data buffer.
+  LoadStoreHelper(address, byte_ptr, size_in_units, true);
+  // Execute the instruction to process and write back the load data.
+  if (nullptr != inst) {
+    if (db->latency() > 0) {
+      inst->IncRef();
+      if (context != nullptr) context->IncRef();
+      inst->state()->function_delay_line()->Add(db->latency(),
+                                                [inst, context]() {
+                                                  inst->Execute(context);
+                                                  if (context != nullptr)
+                                                    context->DecRef();
+                                                  inst->DecRef();
+                                                });
+    } else {
+      inst->Execute(context);
+    }
+  }
+}
+
+void LockingFlatDemandMemory::Load(DataBuffer* address_db, DataBuffer* mask_db,
+                                   int el_size, DataBuffer* db,
+                                   Instruction* inst, ReferenceCount* context) {
+  auto mask_span = mask_db->Get<bool>();
+  auto address_span = address_db->Get<uint64_t>();
+  uint8_t* byte_ptr = static_cast<uint8_t*>(db->raw_ptr());
+  int size_in_units = el_size >> addressable_unit_shift_;
+  if (size_in_units <= 0) {
+    LOG(ERROR) << absl::StrFormat("Size in units %d is not positive\n",
+                                  size_in_units);
+    ABSL_HARDENING_ASSERT(false);
+  }
+  // This is either a gather load, or a unit stride load depending on size of
+  // the address span.
+  bool gather = address_span.size() > 1;
+  for (unsigned i = 0; i < mask_span.size(); i++) {
+    if (!mask_span[i]) continue;
+    uint64_t address = gather ? address_span[i] : address_span[0] + i * el_size;
+    uint64_t high = address + size_in_units;
+    if (address < base_address_ || high > max_address_) [[unlikely]] {
+      LOG(ERROR) << absl::StrFormat(
+          "Load access [%x, %x] out of bounds [%x, %x]\n", address, high,
+          base_address_, max_address_);
+      ABSL_HARDENING_ASSERT(false);
+    }
+    LoadStoreHelper(address, &byte_ptr[el_size * i], size_in_units, true);
+  }
+  // Execute the instruction to process and write back the load data.
+  if (nullptr != inst) {
+    if (db->latency() > 0) {
+      inst->IncRef();
+      if (context != nullptr) context->IncRef();
+      inst->state()->function_delay_line()->Add(db->latency(),
+                                                [inst, context]() {
+                                                  inst->Execute(context);
+                                                  if (context != nullptr)
+                                                    context->DecRef();
+                                                  inst->DecRef();
+                                                });
+    } else {
+      inst->Execute(context);
+    }
+  }
+}
+
+void LockingFlatDemandMemory::Store(uint64_t address, DataBuffer* db) {
+  int size_in_units = db->size<uint8_t>() >> addressable_unit_shift_;
+  uint64_t high = address + size_in_units;
+  if (address < base_address_ || high > max_address_) [[unlikely]] {
+    LOG(ERROR) << absl::StrFormat(
+        "Store access [%x, %x] out of bounds [%x, %x]\n", address, high,
+        base_address_, max_address_);
+    ABSL_HARDENING_ASSERT(false);
+  }
+  if (size_in_units <= 0) [[unlikely]] {
+    LOG(ERROR) << absl::StrFormat("Size in units %d is not positive\n",
+                                  size_in_units);
+    ABSL_HARDENING_ASSERT(false);
+  }
+  uint8_t* byte_ptr = static_cast<uint8_t*>(db->raw_ptr());
+  LoadStoreHelper(address, byte_ptr, size_in_units, /*is_load*/ false);
+}
+
+void LockingFlatDemandMemory::Store(DataBuffer* address_db, DataBuffer* mask_db,
+                                    int el_size, DataBuffer* db) {
+  auto mask_span = mask_db->Get<bool>();
+  auto address_span = address_db->Get<uint64_t>();
+  uint8_t* byte_ptr = static_cast<uint8_t*>(db->raw_ptr());
+  int size_in_units = el_size >> addressable_unit_shift_;
+  if (size_in_units <= 0) [[unlikely]] {
+    LOG(ERROR) << absl::StrFormat("Size in units %d is not positive\n",
+                                  size_in_units);
+    ABSL_HARDENING_ASSERT(false);
+  }
+  // If the address_span.size() > 1, then this is a scatter store, otherwise
+  // it's a unit stride store.
+  bool scatter = address_span.size() > 1;
+  for (unsigned i = 0; i < mask_span.size(); i++) {
+    if (!mask_span[i]) continue;
+    uint64_t address =
+        scatter ? address_span[i] : address_span[0] + i * el_size;
+    uint64_t high = address + size_in_units;
+    if (address < base_address_ || high > max_address_) [[unlikely]] {
+      LOG(ERROR) << absl::StrFormat(
+          "Store access [%x, %x] out of bounds [%x, %x]\n", address, high,
+          base_address_, max_address_);
+      ABSL_HARDENING_ASSERT(false);
+    }
+    LoadStoreHelper(address, &byte_ptr[el_size * i], size_in_units,
+                    /*is_load*/ false);
+  }
+}
+
+void LockingFlatDemandMemory::LoadStoreHelper(uint64_t address,
+                                              uint8_t* data_ptr,
+                                              int size_in_units, bool is_load) {
+  // Repeat the following while there is data to copy. If it's a big chunk of
+  // data it may span across more than one block.
+  do {
+    // Find the block, allocate a new one if needed.
+    uint64_t block_address = address >> kAllocationShift;
+    uint8_t* block = nullptr;
+    absl::flat_hash_map<uint64_t, uint8_t*>::iterator iter;
+
+    {
+      absl::ReaderMutexLock lock(&mutex_);
+      iter = block_map_.find(block_address);
+
+      if (iter != block_map_.end()) {
+        block = iter->second;
+      }
+    }
+
+    if (iter == block_map_.end()) {
+      absl::MutexLock lock(&mutex_);
+      iter = block_map_.find(block_address);
+      if (iter == block_map_.end()) {
+        // In this case we need to allocate a new block.
+        block = new uint8_t[allocation_byte_size_];
+        std::memset(block, fill_value_, allocation_byte_size_);
+        block_map_.insert(std::make_pair(block_address, block));
+      } else {
+        block = iter->second;
+      }
+    }
+
+    int block_unit_offset = (address & kAllocationMask);
+
+    // Compute how many addressable units to load/store from/to the current
+    // block.
+    int store_size_in_units =
+        std::min(size_in_units, kAllocationSize - block_unit_offset);
+
+    // Translate from unit size to byte size.
+    int store_size_in_bytes = store_size_in_units << addressable_unit_shift_;
+    int block_byte_offset = block_unit_offset << addressable_unit_shift_;
+
+    if (is_load) {
+      std::memcpy(data_ptr, &block[block_byte_offset], store_size_in_bytes);
+    } else {
+      std::memcpy(&block[block_byte_offset], data_ptr, store_size_in_bytes);
+    }
+
+    // Adjust address, data pointer and the remaining data left to be
+    // loaded/stored.
+    size_in_units -= store_size_in_units;
+    data_ptr += store_size_in_bytes;
+    address += store_size_in_units;
+  } while (size_in_units > 0);
+}
+
+void LockingFlatDemandMemory::Clear() {
+  for (auto& [unused, block_ptr] : block_map_) {
+    delete[] block_ptr;
+  }
+  block_map_.clear();
+}
+
+}  // namespace mpact::sim::util
diff --git a/mpact/sim/util/memory/locking_flat_demand_memory.h b/mpact/sim/util/memory/locking_flat_demand_memory.h
new file mode 100644
index 0000000..8207060
--- /dev/null
+++ b/mpact/sim/util/memory/locking_flat_demand_memory.h
@@ -0,0 +1,110 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef MPACT_SIM_UTIL_MEMORY_LOCKING_FLAT_DEMAND_MEMORY_H_
+#define MPACT_SIM_UTIL_MEMORY_LOCKING_FLAT_DEMAND_MEMORY_H_
+
+#include <cstdint>
+
+#include "absl/container/flat_hash_map.h"
+#include "absl/synchronization/mutex.h"
+#include "mpact/sim/generic/data_buffer.h"
+#include "mpact/sim/generic/instruction.h"
+#include "mpact/sim/generic/ref_count.h"
+#include "mpact/sim/util/memory/memory_interface.h"
+
+namespace mpact::sim::util {
+
+using ::mpact::sim::generic::DataBuffer;
+using ::mpact::sim::generic::Instruction;
+using ::mpact::sim::generic::ReferenceCount;
+
+// This class models a flat memory that is demand allocated in blocks 16K
+// addressable units. This is useful for modeling memory spaces that are large
+// and sparsely populated/utilitized. There is an assumption that the minimum
+// addressable unit is a power of two and that any memory access smaller than
+// the addressable_unit will treat the addressable unit as byte addressable and
+// only access the low order bytes. All addresses are in terms of the
+// addressable units.
+class LockingFlatDemandMemory : public MemoryInterface {
+ public:
+  LockingFlatDemandMemory(uint64_t memory_size_in_units, uint64_t base_address,
+                          unsigned addressable_unit_size, uint8_t fill);
+  LockingFlatDemandMemory(uint64_t memory_size_in_units, uint64_t base_address)
+      : LockingFlatDemandMemory(memory_size_in_units, base_address, 1, 0) {}
+  explicit LockingFlatDemandMemory(uint64_t base_address)
+      : LockingFlatDemandMemory(0xffff'ffff'ffff'ffffULL, base_address, 1, 0) {}
+  LockingFlatDemandMemory()
+      : LockingFlatDemandMemory(0xffff'ffff'ffff'ffffULL, 0, 1, 0) {}
+  ~LockingFlatDemandMemory() override;
+  // Load data from address into the DataBuffer, then schedule the Instruction
+  // inst (if not nullptr) to be executed (using the function delay line) with
+  // context. The size of the data access is based on size of the data buffer.
+  void Load(uint64_t address, DataBuffer* db, Instruction* inst,
+            ReferenceCount* context) override;
+  // Load data from N addresses stored in address_db (uint64), using mask_db
+  // (bool) to mask out the corresponding loads from taking place (if false).
+  // Each access is el_size bytes long, and is stored into the DataBuffer.
+  // Once done, the Instruction inst (if not nullptr) is scheduled to be
+  // executed (using the function delay line) with context. It's the
+  // responsibility of the caller to ensure that all DataBuffer instances passed
+  // in are appropriately sized.
+  void Load(DataBuffer* address_db, DataBuffer* mask_db, int el_size,
+            DataBuffer* db, Instruction* inst,
+            ReferenceCount* context) override;
+  // Convenience template function that calls the above function with the
+  // element size as the sizeof() the template parameter type.
+  template <typename T>
+  void Load(DataBuffer* address_db, DataBuffer* mask_db, DataBuffer* db,
+            Instruction* inst, ReferenceCount* context) {
+    Load(address_db, mask_db, sizeof(T), db, inst, context);
+  }
+  // Stores data from the DataBuffer instance to memory starting at address.
+  void Store(uint64_t address, DataBuffer* db) override;
+  // Stores data starting at each of the N addresses stored in address_db,
+  // (uint64) using mask_db (bool) to mask out stores from taking place (if
+  // false). Each store is el_size bytes long. It's the responsibility of the
+  // caller to ensure that all DataBuffer instances that are passed in are
+  // appropriately sized.
+  void Store(DataBuffer* address_db, DataBuffer* mask_db, int el_size,
+             DataBuffer* db) override;
+  // Convenience template function that calls the above function with the
+  // element size as the sizeof() the template parameter type.
+  template <typename T>
+  void Store(DataBuffer* address_db, DataBuffer* mask_db, DataBuffer* db) {
+    Store(address_db, mask_db, sizeof(T), db);
+  }
+  static constexpr int kAllocationSize = 16 * 1024;  // Power of two.
+
+  // Clears the memory and frees all allocated blocks.
+  void Clear();
+
+ private:
+  void LoadStoreHelper(uint64_t address, uint8_t* data_ptr, int size_in_units,
+                       bool is_load);
+
+  absl::Mutex mutex_;
+  static constexpr int kAllocationShift = 14;
+  static constexpr uint64_t kAllocationMask = kAllocationSize - 1;
+  uint64_t base_address_;
+  uint64_t max_address_;
+  uint8_t fill_value_;
+  int addressable_unit_shift_;
+  int allocation_byte_size_;
+  absl::flat_hash_map<uint64_t, uint8_t*> block_map_;
+};
+
+}  // namespace mpact::sim::util
+
+#endif  // MPACT_SIM_UTIL_MEMORY_LOCKING_FLAT_DEMAND_MEMORY_H_