我目前是编程新手,不知道如何让程序在加载栏运行时进行处理。 我想显示加载栏并检查程序是否已完成处理。如果没有,那么处理栏应该再次开始填充。
我的代码现在只显示一次加载栏,然后开始处理。这没什么用。
我在 Google 和这里研究了堆栈溢出,但我只从那里得到了加载栏,而不是在我的程序中有用的集成。
我只需要一种简单的方法来检查,除了加载栏之外是否还有输出,我需要在加载栏的同时运行程序的其余部分,以节省时间。
#include <iostream>
#include <windows.h>
#include <unistd.h>
#include <string>
#include <thread>
using namespace std;
static void loading(){
system("Color 0A");
cout<<"\t\n\n";
char a=177, b=219;
cout<<"\t";
for (int i=0;i<=50;i++)
cout<<a;
cout<<"\r";
cout<<"\t";
for (int i=0;i<=50;i++){
cout<<b;
for (int j=0;j<=2e7;j++);
}
cout << "\n\n";
}
int main(){
//ProjectEuler Problem___
loading();
int j=0;
do{
j++;
}while(j<=1e9); //just an example to see when it is processing
cout << "hi" << endl;
return 0;
}
我很感激任何帮助。
最佳答案
您正在寻找的典型模式类似于:
void do_expensive_work(std::atomic<bool>& done) {
... something expensive goes here...
done = true;
}
int main() {
std::atomic<bool> done = false;
auto t = std::thread(do_expensive_work, std::ref(done));
while (!done) {
... update your progress bar ...
... sleep a bit ...
}
t.join();
return 0;
}
具体如何将计算结果传回调用线程等由您决定。类似地,理论上您可以对完成状态使用全局原子,或者将计算包装在一个跟踪状态并管理线程执行的类中。上面的代码已大大简化,但给出了一个通用模式。
关于C++ 在控制台加载栏时使用处理能力/时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51007870/