2 #include <condition_variable>
11 RingBuffer::getSize(
size_t element_size,
int buffer_num)
13 return (
sizeof(
size_t) +
sizeof(std::mutex) +
sizeof(std::condition_variable) +
sizeof(
int) + (
sizeof(uint64_t)+element_size)*buffer_num);
21 : memory_ptr(first_ptr)
23 , data_expiry_time_us(2000000)
25 unsigned char* temp_ptr = memory_ptr;
26 mutex =
reinterpret_cast<pthread_mutex_t *
>(temp_ptr);
27 temp_ptr +=
sizeof(pthread_mutex_t);
28 condition =
reinterpret_cast<pthread_cond_t *
>(temp_ptr);
29 temp_ptr +=
sizeof(pthread_cond_t);
30 element_size =
reinterpret_cast<size_t *
>(temp_ptr);
35 temp_ptr +=
sizeof(size_t);
36 buf_num =
reinterpret_cast<int *
>(temp_ptr);
39 *buf_num = buffer_num;
41 temp_ptr +=
sizeof(int);
42 timestamp_list =
reinterpret_cast<uint64_t *
>(temp_ptr);
43 temp_ptr +=
sizeof(uint64_t) * *buf_num;
48 initializeExclusiveAccess();
52 RingBuffer::~RingBuffer()
58 RingBuffer::initializeExclusiveAccess()
60 pthread_condattr_t cond_attr;
61 pthread_condattr_init(&cond_attr);
62 pthread_condattr_setpshared(&cond_attr, PTHREAD_PROCESS_SHARED);
63 pthread_cond_init(condition, &cond_attr);
64 pthread_condattr_destroy(&cond_attr);
66 pthread_mutexattr_t m_attr;
67 pthread_mutexattr_init(&m_attr);
68 pthread_mutexattr_setpshared(&m_attr, PTHREAD_PROCESS_SHARED);
69 pthread_mutex_init(mutex, &m_attr);
70 pthread_mutexattr_destroy(&m_attr);
75 RingBuffer::getElementSize()
const
81 RingBuffer::getDataList()
104 timestamp_list[buffer_num] = input_time_us;
109 RingBuffer::getNewestBufferNum()
111 uint64_t timestamp_buf = 0;
112 size_t newest_buffer = -1;
113 for (
int i = 0; i < *buf_num; i++)
115 if (timestamp_list[i] > timestamp_buf)
117 timestamp_buf = timestamp_list[i];
121 timestamp_us = timestamp_buf;
124 clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
125 uint64_t current_time_us = ((uint64_t) ts.tv_sec * 1000000L) + ((uint64_t) ts.tv_nsec / 1000L);
126 if (current_time_us - timestamp_us < data_expiry_time_us)
128 return newest_buffer;
135 RingBuffer::getOldestBufferNum()
137 if (timestamp_us == 0)
139 timestamp_us = UINT64_MAX;
141 uint64_t timestamp_buf = timestamp_list[0];
142 size_t oldest_buffer = 0;
143 for (
int i = 0; i < *buf_num; i++)
145 if (timestamp_list[i] < timestamp_buf)
147 timestamp_buf = timestamp_list[i];
152 timestamp_us = timestamp_buf;
153 return oldest_buffer;
160 pthread_cond_broadcast(condition);
172 long sec =
static_cast<long>(timeout_usec / 1000000);
173 long mod_sec =
static_cast<long>(timeout_usec % 1000000);
174 clock_gettime(CLOCK_REALTIME, &ts);
176 ts.tv_nsec+= mod_sec * 1000;
177 if (1000000000 <= ts.tv_nsec)
179 ts.tv_nsec -= 1000000000;
186 pthread_mutex_lock(mutex);
187 int ret = pthread_cond_timedwait(condition, mutex, &ts);
188 pthread_mutex_unlock(mutex);
189 if (ret == ETIMEDOUT)
207 for (
int i; i < *buf_num; i++)
209 if (timestamp_us < timestamp_list[i])
219 RingBuffer::setDataExpiryTime_us(uint64_t time_us)
221 data_expiry_time_us = time_us;