Added multi-threaded progress bar example

This commit is contained in:
Pranav Srinivas KumaR
2019-12-03 20:14:05 -06:00
parent 6e7926bd96
commit e5bb15e0ba
2 changed files with 28 additions and 13 deletions

View File

@@ -15,7 +15,7 @@ class ProgressBar {
std::string _remainder{"-"}; std::string _remainder{"-"};
std::string _end{" ]"}; std::string _end{" ]"};
std::mutex _mutex; std::mutex _mutex;
bool _completed; std::atomic<bool> _completed;
void _print_progress() { void _print_progress() {
std::unique_lock<std::mutex> lock{_mutex}; std::unique_lock<std::mutex> lock{_mutex};
@@ -29,6 +29,8 @@ class ProgressBar {
std::cout << _end << " " << static_cast<int>(_progress) << "%"; std::cout << _end << " " << static_cast<int>(_progress) << "%";
std::cout << " " << _name << "\r"; std::cout << " " << _name << "\r";
std::cout.flush(); std::cout.flush();
if (_completed)
std::cout << std::endl;
} }
public: public:
@@ -64,19 +66,18 @@ public:
} }
void set_progress(float value) { void set_progress(float value) {
{
std::unique_lock<std::mutex> lock{_mutex}; std::unique_lock<std::mutex> lock{_mutex};
if (_completed) return; if (_completed) return;
_progress = value; _progress = value;
if (static_cast<int>(_progress) == 100) { if (static_cast<int>(_progress) == 100) {
_completed = true; _completed = true;
} }
}
_print_progress(); _print_progress();
if (_completed)
std::cout << std::endl;
} }
void tick() { void tick() {
std::unique_lock<std::mutex> lock{_mutex};
if (_completed) return; if (_completed) return;
set_progress(_progress + 1); set_progress(_progress + 1);
} }

View File

@@ -18,10 +18,24 @@ int main() {
// //
// //
for (size_t i = 0; i < 101; i += 5) { std::thread first_job(
bar.set_progress(i); [&bar]() {
std::this_thread::sleep_for(std::chrono::milliseconds(1000)); for (size_t i = 0; i <= 50; ++i) {
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));
}
});
first_job.join();
second_job.join();
return 0; return 0;
} }