MISC 3: Make the whole BufferType life-cycle and recycling properly guarded against concurrent access

This commit is contained in:
vsonnier 2016-06-01 19:51:01 +02:00
parent fc4fa3e74f
commit c3d949ddba

View File

@ -20,6 +20,7 @@ struct map_string_less : public std::binary_function<std::string,std::string,boo
class ReferenceCounter { class ReferenceCounter {
public: public:
void setRefCount(int rc) { void setRefCount(int rc) {
@ -56,17 +57,19 @@ public:
} }
BufferType *getBuffer() { BufferType *getBuffer() {
BufferType* buf = NULL; std::lock_guard < std::mutex > lock(m_mutex);
BufferType* buf = nullptr;
for (outputBuffersI = outputBuffers.begin(); outputBuffersI != outputBuffers.end(); outputBuffersI++) { for (outputBuffersI = outputBuffers.begin(); outputBuffersI != outputBuffers.end(); outputBuffersI++) {
if (!buf && (*outputBuffersI)->getRefCount() <= 0) { if (buf == nullptr && (*outputBuffersI)->getRefCount() <= 0) {
buf = (*outputBuffersI); buf = (*outputBuffersI);
(*outputBuffersI)->setRefCount(0); buf->setRefCount(0);
} else if ((*outputBuffersI)->getRefCount() <= 0) { } else if ((*outputBuffersI)->getRefCount() <= 0) {
(*outputBuffersI)->decRefCount(); (*outputBuffersI)->decRefCount();
} }
} }
if (buf) { if (buf != nullptr) {
if (outputBuffers.back()->getRefCount() < -REBUFFER_GC_LIMIT) { if (outputBuffers.back()->getRefCount() < -REBUFFER_GC_LIMIT) {
BufferType *ref = outputBuffers.back(); BufferType *ref = outputBuffers.back();
outputBuffers.pop_back(); outputBuffers.pop_back();
@ -87,6 +90,7 @@ public:
} }
void purge() { void purge() {
std::lock_guard < std::mutex > lock(m_mutex);
while (!outputBuffers.empty()) { while (!outputBuffers.empty()) {
BufferType *ref = outputBuffers.front(); BufferType *ref = outputBuffers.front();
outputBuffers.pop_front(); outputBuffers.pop_front();
@ -97,6 +101,7 @@ private:
std::string bufferId; std::string bufferId;
std::deque<BufferType*> outputBuffers; std::deque<BufferType*> outputBuffers;
typename std::deque<BufferType*>::iterator outputBuffersI; typename std::deque<BufferType*>::iterator outputBuffersI;
mutable std::mutex m_mutex;
}; };