Skip to content

Commit

Permalink
Merge pull request #57 from Wolkabout/bugfix/infinite-waits
Browse files Browse the repository at this point in the history
Prevent `Buffer` and `CommandBuffer` from waiting forever after last …
  • Loading branch information
nanavuletic authored Feb 25, 2022
2 parents 6f579b5 + eb46ba2 commit 55b8b7c
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 12 deletions.
9 changes: 5 additions & 4 deletions core/utilities/Buffer.h
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,10 @@ template <class T> Buffer<T>::~Buffer()

template <class T> void Buffer<T>::stop()
{
m_exitCondition = true;
{
std::lock_guard<std::mutex> lg{m_pushLock};
m_exitCondition = true;
}
m_condition.notify_one();
}

Expand Down Expand Up @@ -92,7 +95,7 @@ template <class T> T Buffer<T>::pop()

if (m_popQueue.empty())
{
LOG(ERROR) << "Poping from empty buffer";
LOG(ERROR) << "Popping from empty buffer";
return {};
}

Expand All @@ -107,9 +110,7 @@ template <class T> void Buffer<T>::swapBuffers()
std::unique_lock<std::mutex> pushGuard(m_pushLock);

if (m_pushQueue.empty())
{
m_condition.wait(pushGuard, [&] { return !m_pushQueue.empty() || m_exitCondition; });
}

std::lock_guard<std::mutex> popGuard{m_popLock};
std::swap(m_pushQueue, m_popQueue);
Expand Down
13 changes: 6 additions & 7 deletions core/utilities/CommandBuffer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@

#include "CommandBuffer.h"

#include <atomic>
#include <condition_variable>
#include <functional>
#include <memory>
#include <mutex>
Expand All @@ -36,7 +34,7 @@ CommandBuffer::~CommandBuffer()
stop();
}

void CommandBuffer::pushCommand(std::shared_ptr<Command> command)
void CommandBuffer::pushCommand(const std::shared_ptr<Command>& command)
{
std::unique_lock<std::mutex> unique_lock(m_lock);

Expand All @@ -47,7 +45,10 @@ void CommandBuffer::pushCommand(std::shared_ptr<Command> command)

void CommandBuffer::stop()
{
m_isRunning = false;
{
std::lock_guard<std::mutex> lg{m_lock};
m_isRunning = false;
}
notify();

if (m_worker && m_worker->joinable())
Expand Down Expand Up @@ -80,9 +81,7 @@ void CommandBuffer::switchBuffers()
std::unique_lock<std::mutex> unique_lock(m_lock);

if (m_pushCommandQueue.empty())
{
m_condition.wait(unique_lock);
}
m_condition.wait(unique_lock, [&] { return !m_pushCommandQueue.empty() || !m_isRunning; });

std::swap(m_pushCommandQueue, m_popCommandQueue);
}
Expand Down
2 changes: 1 addition & 1 deletion core/utilities/CommandBuffer.h
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ class CommandBuffer
CommandBuffer();
virtual ~CommandBuffer();

void pushCommand(std::shared_ptr<Command> command);
void pushCommand(const std::shared_ptr<Command>& command);

void stop();

Expand Down

0 comments on commit 55b8b7c

Please sign in to comment.