12 #ifndef SST_CORE_INTERPROCESS_CIRCULARBUFFER_H
13 #define SST_CORE_INTERPROCESS_CIRCULARBUFFER_H 1
22 namespace Interprocess {
34 pthread_cond_t cond_full, cond_empty;
35 pthread_condattr_t attrcond;
36 pthread_mutexattr_t attrmutex;
50 rPtr(0), wPtr(0), buffSize(bufferSize)
52 pthread_mutexattr_init(&attrmutex);
53 pthread_mutexattr_setpshared(&attrmutex, PTHREAD_PROCESS_SHARED);
54 if ( pthread_mutex_init(&mtx, &attrmutex) ) {
55 fprintf(stderr,
"Failed to initialie mutex: %s\n", strerror(errno));
59 pthread_condattr_init(&attrcond);
60 pthread_condattr_setpshared(&attrcond, PTHREAD_PROCESS_SHARED);
61 if ( pthread_cond_init(&cond_full, &attrcond) ) {
62 fprintf(stderr,
"Failed to initialie condition vars: %s\n", strerror(errno));
65 if ( pthread_cond_init(&cond_empty, &attrcond) ) {
66 fprintf(stderr,
"Failed to initialie condition vars: %s\n", strerror(errno));
72 pthread_mutex_destroy(&mtx);
73 pthread_mutexattr_destroy(&attrmutex);
75 pthread_cond_destroy(&cond_full);
76 pthread_cond_destroy(&cond_empty);
77 pthread_condattr_destroy(&attrcond);
80 void setBufferSize(
size_t bufferSize)
82 if ( buffSize != 0 ) {
83 fprintf(stderr,
"Already specified size for buffer\n");
86 buffSize = bufferSize;
95 if ( pthread_mutex_lock(&mtx) ) {
96 fprintf(stderr,
"LOCKING ERROR: %s\n", strerror(errno));
98 while ( (wPtr+1) % buffSize == rPtr ) {
99 pthread_cond_wait(&cond_full, &mtx);
102 buffer[wPtr] = value;
103 wPtr = (wPtr +1 ) % buffSize;
105 __sync_synchronize();
106 pthread_cond_signal(&cond_empty);
107 pthread_mutex_unlock(&mtx);
116 if ( pthread_mutex_lock(&mtx) ) {
117 fprintf(stderr,
"LOCKING ERROR: %s\n", strerror(errno));
119 while ( rPtr == wPtr ) {
120 pthread_cond_wait(&cond_empty, &mtx);
123 T ans = buffer[rPtr];
124 rPtr = (rPtr +1 ) % buffSize;
126 __sync_synchronize();
127 pthread_cond_signal(&cond_full);
128 pthread_mutex_unlock(&mtx);
139 if ( pthread_mutex_trylock(&mtx) != 0 )
return false;
140 if ( rPtr == wPtr ) {
141 pthread_mutex_unlock(&mtx);
145 *result = buffer[rPtr];
146 rPtr = (rPtr +1 ) % buffSize;
148 __sync_synchronize();
149 pthread_cond_signal(&cond_full);
150 pthread_mutex_unlock(&mtx);
CircularBuffer(size_t bufferSize=0)
Construct a new circular buffer.
Definition: circularBuffer.h:49
Multi-process safe, Circular Buffer class.
Definition: circularBuffer.h:31
T read(void)
Blocking Read a value from the circular buffer.
Definition: circularBuffer.h:114
bool readNB(T *result)
Non-Blocking Read a value from the circular buffer.
Definition: circularBuffer.h:137
void write(const T &value)
Write a value to the circular buffer.
Definition: circularBuffer.h:93