【问题标题】:Progress bar in Windows activity field?Windows活动字段中的进度条?
【发布时间】:2016-03-15 22:26:47
【问题描述】:

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

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

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

【问题讨论】:

  • 这就是所谓的“任务栏进度指示器”;它作为一项新功能添加到 Windows 7 中,并通过 ITaskbarList3 接口公开。
  • Windows 7 中添加了很多Taskbar extensions
  • @JonathanPotter 完美!我可能在搜索时使用了错误的术语。

标签: c++ progress-bar progress


【解决方案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
    }

}

【讨论】:

  • 我很好奇你认为这个答案与这个问题有什么相关性?
  • 重读问题后,我似乎误解了问题
猜你喜欢
  • 2015-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-18
  • 1970-01-01
  • 2010-11-15
  • 2021-07-21
相关资源
最近更新 更多