Skip to content

Commit

Permalink
Simpler communication with progress printer thread
Browse files Browse the repository at this point in the history
  • Loading branch information
kimci86 committed Mar 2, 2024
1 parent a82d1c6 commit ebf59ef
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 22 deletions.
7 changes: 2 additions & 5 deletions include/ConsoleProgress.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@

#include "Progress.hpp"

#include <condition_variable>
#include <mutex>
#include <future>
#include <thread>

/// Progress indicator which prints itself at regular time intervals
Expand All @@ -21,9 +20,7 @@ class ConsoleProgress : public Progress
private:
const std::chrono::milliseconds m_interval;

std::mutex m_in_destructor_mutex;
std::condition_variable m_in_destructor_cv;
bool m_in_destructor;
std::promise<void> m_inDestructor;

std::thread m_printer;
void printerFunction();
Expand Down
21 changes: 4 additions & 17 deletions src/ConsoleProgress.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,34 +5,24 @@
ConsoleProgress::ConsoleProgress(std::ostream& os, const std::chrono::milliseconds& interval)
: Progress{os}
, m_interval{interval}
, m_in_destructor{false}
, m_printer{&ConsoleProgress::printerFunction, this}
{
}

ConsoleProgress::~ConsoleProgress()
{
{
const auto lock = std::scoped_lock{m_in_destructor_mutex};
m_in_destructor = true;
}

m_in_destructor_cv.notify_all();
m_inDestructor.set_value();
m_printer.join();
}

void ConsoleProgress::printerFunction()
{
auto repeat = true;
const auto inDestructor = m_inDestructor.get_future();

// Give a small delay before the first time progress is printed so that
// the running operation is likely to have initialized the total number of steps.
{
auto lock = std::unique_lock{m_in_destructor_mutex};
repeat = !m_in_destructor_cv.wait_for(lock, std::chrono::milliseconds{1}, [this] { return m_in_destructor; });
}

while (repeat)
for (auto status = inDestructor.wait_for(std::chrono::milliseconds{1}); status != std::future_status::ready;
status = inDestructor.wait_for(m_interval))
{
if (const auto total = this->total.load())
log(
Expand All @@ -47,9 +37,6 @@ void ConsoleProgress::printerFunction()
os.precision(precisionBefore);
os.flags(flagsBefore);
});

auto lock = std::unique_lock{m_in_destructor_mutex};
repeat = !m_in_destructor_cv.wait_for(lock, m_interval, [this] { return m_in_destructor; });
}

if (const auto total = this->total.load())
Expand Down

0 comments on commit ebf59ef

Please sign in to comment.