我写了一个C++程序执行耗时的计算,我希望用户能够看到进步的程序在后台(最小化)运行时。Windows活动字段中的进度条?
我想使用相同的效果铬下载文件时使用:
我如何使用此功能?我可以在我的C++程序中使用它吗?
我写了一个C++程序执行耗时的计算,我希望用户能够看到进步的程序在后台(最小化)运行时。Windows活动字段中的进度条?
我想使用相同的效果铬下载文件时使用:
我如何使用此功能?我可以在我的C++程序中使用它吗?
如果耗时的操作可以在一个循环内执行,并且取决于它是否是一个计数控制循环,您可能可以使用thread
和atomic
来解决您的问题。 如果您的处理器架构支持多线程,你可以使用线程同时运行的计算。基本使用线程的是平行于主线程运行的函数,这些操作可能在同一时间被有效地完成,这意味着你将能够使用主线程来检查你的耗时的计算进度。随着并行线程来的数据竞争的问题,其中,如果两个线程试图访问或修改相同的数据,他们可以这样做不正确的和腐败的记忆。这可以通过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
}
}
我很好奇你认为这个答案对这个问题有什么相关性? –
重读这个问题后,似乎我误解了这个问题 – Stephen
这就是被称为 “任务栏进度指示器”;它被添加到Windows 7作为一项新功能,并通过'ITaskbarList3'界面公开。 –
很多[任务栏扩展]的(https://msdn.microsoft.com/en-us/library/windows/desktop/dd378460.aspx)在Windows 7 –
@JonathanPotter完美的加入!我在搜索时可能使用了错误的术语。 – TcAcS