用C++写个进度条

实现一个命令行进度条,使用线程,不会换行欧。支持自定义进度条的条的字符,可以暂停和继续。
在写的过程中还遇到一个错误,之前多线程写的少不知道,贴出来给大家看一下:

terminate called without an active exception

这是线程异常终止了,在我的代码里就是线程没结束主线程结束了,就直接抛错了。解决方法就是加个join

class ProgressBar{
private:
	class Logic{
	public:
		static int barLen;
		static int curLen;
		static string str;
		static condition_variable _cv;
		static char ch;
		void operator()(){
			unique_lock<mutex> lock(barMutex);
			for(int i=0;i<=barLen;i++){
				_cv.wait(lock,[]()->bool{
					return !ProgressBar::_pause;
				});
				str[i]=ch;
				cout<<"\r|"<<str<<"| "<<(int)i*100/barLen<<"%";
				Sleep(200);
			}
		}
	};
public:
	static void Start(const int _barLen = 100, const char _ch = '='){
		ProgressBar::Logic::barLen=_barLen;
		ProgressBar::Logic::ch=_ch;
		ProgressBar::_pause=false;
		ProgressBar::Logic::str=string(_barLen,' ');
		ProgressBar::run = thread(Logic());
	}
	// static void Start(){run.join();}
    static void Pause(){
		ProgressBar::_pause=true;
	}
    static void Continue(){
		ProgressBar::_pause=false;
		Logic::_cv.notify_one();
	}
public:
	static bool _pause;
    static mutex barMutex;
    static thread run;
};

int ProgressBar::Logic::barLen = 100;
int ProgressBar::Logic::curLen = 0;
thread ProgressBar::run;
string ProgressBar::Logic::str = "";
bool ProgressBar::_pause = false;
char ProgressBar::Logic::ch = '=';
condition_variable ProgressBar::Logic::_cv;
mutex ProgressBar::barMutex;
int main(){
    // ProgressBar::Init();
    ProgressBar::Start(50,'+');
    Sleep(2000);
    ProgressBar::Pause();
    Sleep(5000);
    ProgressBar::Continue();
    ProgressBar::run.join();
    return 0;
}

你可能感兴趣的:(小demo,c++)