diff --git a/include/progress/bar.hpp b/include/progress/bar.hpp index b4b22de..16109e5 100644 --- a/include/progress/bar.hpp +++ b/include/progress/bar.hpp @@ -70,7 +70,7 @@ public: std::unique_lock lock{_mutex}; if (_completed) return; _progress = value; - if (static_cast(_progress) == 100) { + if (_progress >= 100.0) { _completed = true; } } @@ -78,8 +78,19 @@ public: } void tick() { - if (_completed) return; - set_progress(_progress + 1); + { + std::unique_lock lock{_mutex}; + if (_completed) return; + _progress += 1; + if (_progress >= 100.0) { + _completed = true; + } + } + _print_progress(); + } + + bool completed() { + return _completed; } }; diff --git a/test/bar.cpp b/test/bar.cpp index 9ed7ec7..7a06afe 100644 --- a/test/bar.cpp +++ b/test/bar.cpp @@ -5,7 +5,7 @@ int main() { ProgressBar bar; // Configure progress bar - bar.bar_width(100); + bar.bar_width(50); bar.start_with("["); bar.fill_progress_with("="); bar.lead_progress_with(">"); @@ -18,24 +18,24 @@ int main() { // // - std::thread first_job( - [&bar]() { - for (size_t i = 0; i <= 50; ++i) { - bar.tick(); - std::this_thread::sleep_for(std::chrono::milliseconds(100)); - } - }); + auto job = [&bar]() { + while(true) { + if (bar.completed()) + break; + bar.tick(); + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } + }; - std::thread second_job( - [&bar]() { - for (size_t i = 0; i <= 50; ++i) { - bar.tick(); - std::this_thread::sleep_for(std::chrono::milliseconds(100)); - } - }); + std::thread first_job(job); + std::thread second_job(job); + std::thread third_job(job); + std::thread last_job(job); first_job.join(); second_job.join(); + third_job.join(); + last_job.join(); return 0; }