diff --git a/services/common/ring_buffer/ring_buffer.cpp b/services/common/ring_buffer/ring_buffer.cpp index c7348b996b705ff0c003c462e49969299c79cd1b..9ec69a039e5b55908cc6e4e957b679d005ca53e9 100644 --- a/services/common/ring_buffer/ring_buffer.cpp +++ b/services/common/ring_buffer/ring_buffer.cpp @@ -96,13 +96,16 @@ bool RingBuffer::Push(uint8_t *buf, uint32_t len) } } - uint32_t index = writeIndex_ & (num_ - 1); - if (memcpy_s(bufArray_[index], singleSize_, buf, len) != EOK) { - LOG(ERROR) << "memcpy error, len:" << len; - return false; + { + std::unique_lock arrayLock(arrayMtx_); + uint32_t index = writeIndex_ & (num_ - 1); + if (memcpy_s(bufArray_[index], singleSize_, buf, len) != EOK) { + LOG(ERROR) << "memcpy error, len:" << len; + return false; + } + lenArray_[index] = len; + writeIndex_ = (writeIndex_ + 1) & (2 * num_ - 1); // 2: logic buffer size } - lenArray_[index] = len; - writeIndex_ = (writeIndex_ + 1) & (2 * num_ - 1); // 2: logic buffer size std::unique_lock popLock(notifyMtx_); notEmpty_.notify_all(); @@ -127,13 +130,16 @@ bool RingBuffer::Pop(uint8_t *buf, uint32_t maxLen, uint32_t &len) } } - uint32_t index = readIndex_ & (num_ - 1); - if (memcpy_s(buf, maxLen, bufArray_[index], lenArray_[index]) != EOK) { - LOG(ERROR) << "memcpy error, len:" << lenArray_[index]; - return false; + { + std::unique_lock arrayLock(arrayMtx_); + uint32_t index = readIndex_ & (num_ - 1); + if (memcpy_s(buf, maxLen, bufArray_[index], lenArray_[index]) != EOK) { + LOG(ERROR) << "memcpy error, len:" << lenArray_[index]; + return false; + } + len = lenArray_[index]; + readIndex_ = (readIndex_ + 1) & (2 * num_ - 1); // 2: logic buffer size } - len = lenArray_[index]; - readIndex_ = (readIndex_ + 1) & (2 * num_ - 1); // 2: logic buffer size std::unique_lock popLock(notifyMtx_); notFull_.notify_all(); diff --git a/services/common/ring_buffer/ring_buffer.h b/services/common/ring_buffer/ring_buffer.h index 165d8ffe5748da12f0ed2a2564f0898e7ba193ad..7f37fa38132cf05706b7ddd7eb4832cf61975cf9 100644 --- a/services/common/ring_buffer/ring_buffer.h +++ b/services/common/ring_buffer/ring_buffer.h @@ -52,6 +52,7 @@ private: std::condition_variable notFull_; std::condition_variable notEmpty_; std::mutex notifyMtx_; + std::mutex arrayMtx_; }; } // namespace Updater #endif // __RING_BUFFER_H__ \ No newline at end of file