爱收集资源网

线程问题导致主线程提前结束

网络 2023-07-02 03:01

实现一个命令行进度条,使用线程,不会换行欧。支持自定义进度条的条的字符,可以暂停和继续。

在写的过程中还碰到一个错误,之前多线程写的少不知道,贴下来给你们看一下:

terminate called without an active exception

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

进度条c语言代码_播放器进度条看不到_c++实现进度条

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;
}

播放器进度条看不到
上一篇:一键流畅,游戏体验超实用! 下一篇:没有了
相关文章