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 _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};
|
{
|
||||||
if (_completed) return;
|
std::unique_lock<std::mutex> lock{_mutex};
|
||||||
_progress = value;
|
if (_completed) return;
|
||||||
if (static_cast<int>(_progress) == 100) {
|
_progress = value;
|
||||||
_completed = true;
|
if (static_cast<int>(_progress) == 100) {
|
||||||
|
_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);
|
||||||
}
|
}
|
||||||
|
|||||||
22
test/bar.cpp
22
test/bar.cpp
@@ -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;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user