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