mirror of
https://github.com/p-ranav/indicators.git
synced 2025-12-13 18:48:53 +08:00
Added multi-threaded progress bar example
This commit is contained in:
@@ -15,7 +15,7 @@ class ProgressBar {
|
||||
std::string _remainder{"-"};
|
||||
std::string _end{" ]"};
|
||||
std::mutex _mutex;
|
||||
bool _completed;
|
||||
std::atomic<bool> _completed;
|
||||
|
||||
void _print_progress() {
|
||||
std::unique_lock<std::mutex> lock{_mutex};
|
||||
@@ -29,6 +29,8 @@ class ProgressBar {
|
||||
std::cout << _end << " " << static_cast<int>(_progress) << "%";
|
||||
std::cout << " " << _name << "\r";
|
||||
std::cout.flush();
|
||||
if (_completed)
|
||||
std::cout << std::endl;
|
||||
}
|
||||
|
||||
public:
|
||||
@@ -64,19 +66,18 @@ public:
|
||||
}
|
||||
|
||||
void set_progress(float value) {
|
||||
{
|
||||
std::unique_lock<std::mutex> lock{_mutex};
|
||||
if (_completed) return;
|
||||
_progress = value;
|
||||
if (static_cast<int>(_progress) == 100) {
|
||||
_completed = true;
|
||||
}
|
||||
}
|
||||
_print_progress();
|
||||
if (_completed)
|
||||
std::cout << std::endl;
|
||||
}
|
||||
|
||||
void tick() {
|
||||
std::unique_lock<std::mutex> lock{_mutex};
|
||||
if (_completed) return;
|
||||
set_progress(_progress + 1);
|
||||
}
|
||||
|
||||
20
test/bar.cpp
20
test/bar.cpp
@@ -18,10 +18,24 @@ int main() {
|
||||
//
|
||||
//
|
||||
|
||||
for (size_t i = 0; i < 101; i += 5) {
|
||||
bar.set_progress(i);
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
|
||||
std::thread first_job(
|
||||
[&bar]() {
|
||||
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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user