Skip to content

Commit

Permalink
Guard critical variables and standard output procedures with mutex
Browse files Browse the repository at this point in the history
  • Loading branch information
moshiba committed Jan 9, 2020
1 parent b724ddf commit b484f15
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
14 changes: 12 additions & 2 deletions pbar/pbar.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,8 @@ std::string ProgressBar::format_meter() {
void ProgressBar::display() {
/** Refresh display of this bar
*/
const std::lock_guard<std::mutex> guard(this->pbar_mutex);
if (this->position) {
this->moveto(this->position);
}
Expand Down Expand Up @@ -213,8 +215,14 @@ void ProgressBar::update(const int n) {
// TODO: how to evaluate this guess on next round
// Store old values for next call
this->last_update_n = this->n;
this->last_update_time = std::move(now);
{
std::lock_guard<std::mutex> guard(this->pbar_mutex);
// this->last_update_n = this->n;
const long long tmp = this->n.load();
this->last_update_n = tmp;
this->last_update_time = std::move(now);
}
}
}
}
Expand Down Expand Up @@ -242,6 +250,8 @@ void ProgressBar::close() {
// leave this bar as it is
} else {
// close (clean up) the pbar
const std::lock_guard<std::mutex> guard(this->pbar_mutex);
this->moveto(this->position);
std::cout << "\r" << aesc::cursor::EL(aesc::cursor::clear::to_end);
this->moveto(-this->position);
Expand Down
7 changes: 5 additions & 2 deletions pbar/pbar.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@

#include <sys/ioctl.h>

#include <atomic>
#include <chrono>
#include <mutex>
#include <ratio>
#include <sstream>
#include <string>
Expand Down Expand Up @@ -64,11 +66,12 @@ class ProgressBar {
std::chrono::nanoseconds min_interval_time;
long min_interval_iter;
std::string bar_format;
long long n;
std::atomic<long long> n;
const int position;
long long last_update_n;
std::atomic<long long> last_update_n;
std::chrono::system_clock::time_point last_update_time;
bool disable;
std::mutex pbar_mutex;

private:
inline float percentage();
Expand Down

0 comments on commit b484f15

Please sign in to comment.