Windows活动字段中的进度条?

时间:2016-03-15 22:26:47

标签: c++ progress-bar progress

我编写了一个执行耗时计算的c ++程序,我希望用户能够在程序在后台运行时看到进度(最小化)。

我想在下载文件时使用与chrome相同的效果:

chrome progress

如何访问此功能?我可以在我的c ++程序中使用它吗?

1 个答案:

答案 0 :(得分:-1)

如果可以在循环内执行耗时的操作,并且取决于它是否是计数控制循环,您可以使用threadatomic来解决您的问题。 如果您的处理器体系结构支持多线程,则可以使用线程同时运行计算。线程的基本用法是与主线程并行运行一个函数,这些操作可以同时有效地完成,这意味着您可以使用主线程来检查耗时计算的进度。使用并行线程会出现数据争用的问题,其中如果两个线程试图访问或编辑相同的数据,则它们可能会错误地执行此操作并破坏内存。这可以通过atomic来解决。您可以使用atomic_int来确保两个操作永远不会导致数据竞争。

一个可行的例子:

#include <thread>
#include <mutex>
#include <atomic>
#include <iostream>

//function prototypes
void foo(std::mutex * mtx, std::atomic_int * i);

//main function
int main() {
    //first define your variables
    std::thread bar;
    std::mutex mtx;
    std::atomic_int value;
    //store initial value just in case
    value.store(0);


    //create the thread and assign it a task by passing a function and any parameters of the function as parameters of thread
    std::thread functionalThread;
    functionalThread = std::thread(foo/*function name*/, &mtx, &value/*parameters of the function*/);

    //a loop to keep checking value to see if it has reached its final value

    //temp variable to hold value so that operations can be performed on it while the main thread does other things
    int temp = value.load();

    //double to hold percent value
    double percent;
    while (temp < 1000000000) {
        //calculate percent value
        percent = 100.0 * double(temp) / 1000000000.0;

        //display percent value
        std::cout << "The current percent is: " << percent << "%" << std::endl;

        //get new value for temp
        temp = value.load();
    }
    //display message when calculations complete
    std::cout << "Task is done." << std::endl;

    //when you join a thread you are essentially waiting for the thread to finish before the calling thread continues
    functionalThread.join();

    //cin to hold program from completing to view results
    int wait;
    std::cin >> wait;

    //end program
    return 0;
}

void foo(std::mutex * mtx, std::atomic_int * i) {
    //function counts to 1,000,000,000 as fast as it can
    for (i->store(0); i->load() < 1000000000; i->store(i->load() + 1)) {
        //keep i counting
        //the first part is the initial value, store() sets the value of the atomic int
        //the second part is the exit condition, load() returns the currently stored value of the atomic
        //the third part is the increment
    }

}