SST  12.0.1
StructuralSimulationToolkit
circularBuffer.h
1 // Copyright 2009-2022 NTESS. Under the terms
2 // of Contract DE-NA0003525 with NTESS, the U.S.
3 // Government retains certain rights in this software.
4 //
5 // Copyright (c) 2009-2022, NTESS
6 // All rights reserved.
7 //
8 // This file is part of the SST software package. For license
9 // information, see the LICENSE file in the top level directory of the
10 // distribution.
11 
12 #ifndef SST_CORE_INTERPROCESS_CIRCULARBUFFER_H
13 #define SST_CORE_INTERPROCESS_CIRCULARBUFFER_H
14 
15 #include "sstmutex.h"
16 
17 namespace SST {
18 namespace Core {
19 namespace Interprocess {
20 
21 template <typename T>
23 {
24 
25 public:
26  CircularBuffer(size_t mSize = 0)
27  {
28  buffSize = mSize;
29  readIndex = 0;
30  writeIndex = 0;
31  }
32 
33  bool setBufferSize(const size_t bufferSize)
34  {
35  if ( buffSize != 0 ) {
36  fprintf(stderr, "Already specified size for buffer\n");
37  return false;
38  }
39 
40  buffSize = bufferSize;
41  __sync_synchronize();
42  return true;
43  }
44 
45  T read()
46  {
47  int loop_counter = 0;
48 
49  while ( true ) {
50  bufferMutex.lock();
51 
52  if ( readIndex != writeIndex ) {
53  const T result = buffer[readIndex];
54  readIndex = (readIndex + 1) % buffSize;
55 
56  bufferMutex.unlock();
57  return result;
58  }
59 
60  bufferMutex.unlock();
61  bufferMutex.processorPause(loop_counter++);
62  }
63  }
64 
65  bool readNB(T* result)
66  {
67  if ( bufferMutex.try_lock() ) {
68  if ( readIndex != writeIndex ) {
69  *result = buffer[readIndex];
70  readIndex = (readIndex + 1) % buffSize;
71 
72  bufferMutex.unlock();
73  return true;
74  }
75 
76  bufferMutex.unlock();
77  }
78 
79  return false;
80  }
81 
82  void write(const T& v)
83  {
84  int loop_counter = 0;
85 
86  while ( true ) {
87  bufferMutex.lock();
88 
89  if ( ((writeIndex + 1) % buffSize) != readIndex ) {
90  buffer[writeIndex] = v;
91  writeIndex = (writeIndex + 1) % buffSize;
92 
93  __sync_synchronize();
94  bufferMutex.unlock();
95  return;
96  }
97 
98  bufferMutex.unlock();
99  bufferMutex.processorPause(loop_counter++);
100  }
101  }
102 
103  ~CircularBuffer() {}
104 
105  void clearBuffer()
106  {
107  bufferMutex.lock();
108  readIndex = writeIndex;
109  __sync_synchronize();
110  bufferMutex.unlock();
111  }
112 
113 private:
114  SSTMutex bufferMutex;
115  size_t buffSize;
116  size_t readIndex;
117  size_t writeIndex;
118  T buffer[0];
119 };
120 
121 } // namespace Interprocess
122 } // namespace Core
123 } // namespace SST
124 
125 #endif // SST_CORE_INTERPROCESS_CIRCULARBUFFER_H
Definition: circularBuffer.h:22
Definition: sstmutex.h:25