|
发表于 2019-7-19 14:47:53
|
显示全部楼层
本帖最后由 Croper 于 2019-7-19 15:01 编辑
在比如,在进行一个耗时较长的运算时(比如从1加到1000000000),会耗时很长的时间,这个时候,可以利用thread给它加一个进度条
- #include<iostream>
- #include<thread>
- #include<mutex>
- #include<windows.h>
- using namespace std;
- mutex m_cursor; //移动光标再打印时最好加个锁,否则可能出现进程A移动光标->进程B移动光标->进程A打印->进程B打印导致的排版混乱
- //移动控制台光标的函数
- void gotoxy(int x, int y) {
- COORD coord = { x,y };
- HANDLE hscr = GetStdHandle(STD_OUTPUT_HANDLE);
- SetConsoleCursorPosition(hscr, coord);
- }
- //绘制进度条的函数
- void PrintProcess(volatile int* pnum, int den) {
- volatile int& num = *pnum;
- m_cursor.lock();
- gotoxy(0, 1);
- cout << "计算中..";
- gotoxy(0, 3);
- for (int i = 0; i < 100; ++i) {
- cout << "-";
- }
- m_cursor.unlock();
- for (int i = 0; i < 100; ++i) {
- while ((double)num / den * 100 < i) {
- Sleep(10);
- }
- m_cursor.lock();
- gotoxy(i, 3);
- cout << "|";
- m_cursor.unlock();
- }
- }
- int main() {
- long long sum = 0;
- volatile int i; //使用volatile告诉编辑器不要优化,否则可能出现进程间的数据不一致
- int maxi = 1000000000;
- thread thr(PrintProcess, &i, maxi); //注意向函数传递参数的方法,不能直接传递引用
- for (i = 0; i < maxi; ++i) {
- sum += i;
- }
- thr.join();
- m_cursor.lock();
- gotoxy(0, 1);
- cout << "计算完毕,答案是" << sum;
- gotoxy(0, 5);
- m_cursor.unlock();
- system("pause");
- }
复制代码 |
|