SST  8.0.0
StructuralSimulationToolkit
circularBuffer.h
1 // Copyright 2009-2018 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-2018, 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 public:
25  CircularBuffer(size_t mSize = 0) {
26  buffSize = mSize;
27  readIndex = 0;
28  writeIndex = 0;
29  }
30 
31  void setBufferSize(const size_t bufferSize)
32  {
33  if ( buffSize != 0 ) {
34  fprintf(stderr, "Already specified size for buffer\n");
35  exit(1);
36  }
37 
38  buffSize = bufferSize;
39  __sync_synchronize();
40  }
41 
42  T read() {
43  int loop_counter = 0;
44 
45  while( true ) {
46  bufferMutex.lock();
47 
48  if( readIndex != writeIndex ) {
49  const T result = buffer[readIndex];
50  readIndex = (readIndex + 1) % buffSize;
51 
52  bufferMutex.unlock();
53  return result;
54  }
55 
56  bufferMutex.unlock();
57  bufferMutex.processorPause(loop_counter++);
58  }
59  }
60 
61  bool readNB(T* result) {
62  if( bufferMutex.try_lock() ) {
63  if( readIndex != writeIndex ) {
64  *result = buffer[readIndex];
65  readIndex = (readIndex + 1) % buffSize;
66 
67  bufferMutex.unlock();
68  return true;
69  }
70 
71  bufferMutex.unlock();
72  }
73 
74  return false;
75  }
76 
77  void write(const T& v) {
78  int loop_counter = 0;
79 
80  while( true ) {
81  bufferMutex.lock();
82 
83  if( ((writeIndex + 1) % buffSize) != readIndex ) {
84  buffer[writeIndex] = v;
85  writeIndex = (writeIndex + 1) % buffSize;
86 
87  __sync_synchronize();
88  bufferMutex.unlock();
89  return;
90  }
91 
92  bufferMutex.unlock();
93  bufferMutex.processorPause(loop_counter++);
94  }
95  }
96 
97  ~CircularBuffer() {
98 
99  }
100 
101  void clearBuffer() {
102  bufferMutex.lock();
103  readIndex = writeIndex;
104  __sync_synchronize();
105  bufferMutex.unlock();
106  }
107 
108 private:
109  SSTMutex bufferMutex;
110  size_t buffSize;
111  size_t readIndex;
112  size_t writeIndex;
113  T buffer[0];
114 
115 };
116 
117 }
118 }
119 }
120 
121 #endif
Definition: circularBuffer.h:22
Definition: sstmutex.h:25