Skip to content

Instantly share code, notes, and snippets.

@Shikugawa
Created December 15, 2019 15:18
Show Gist options
  • Save Shikugawa/e7b1209907225fe9f65d13ba45f26387 to your computer and use it in GitHub Desktop.
Save Shikugawa/e7b1209907225fe9f65d13ba45f26387 to your computer and use it in GitHub Desktop.
マルチスレッドな進捗バー
#include <iostream>
#include <string>
#include <thread>
#include <atomic>
#include <unistd.h>
#include <mutex>
std::atomic<bool> end_flag = false;
std::atomic<bool> out_flag = false;
std::atomic<double> current_time = 0;
std::mutex mtx;
std::string bar;
double max = 10;
void output() {
std::unique_lock<std::mutex> lock(mtx);
if (current_time != 0) {
double pers = (current_time / max) * 100;
bar += "====";
std::cout << pers << "% [" << bar << ">\r" << std::flush;
}
}
void thread1() {
for (int i = 0; i < max; ++i) {
sleep(1);
current_time = current_time + 1.0;
out_flag = true;
}
end_flag = true;
}
void thread2() {
while (!end_flag) {
if (out_flag) {
out_flag = false;
output();
}
}
}
int main() {
std::thread t1(thread1);
std::thread t2(thread2);
t1.join();
t2.join();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment