2016-03-15 110 views
0

我寫了一個C++程序執行耗時的計算,我希望用戶能夠看到進步的程序在後臺(最小化)運行時。Windows活動字段中的進度條?

我想使用相同的效果鉻下載文件時使用:

chrome progress

我如何使用此功能?我可以在我的C++程序中使用它嗎?

+2

這就是被稱爲 「任務欄進度指示器」;它被添加到Windows 7作爲一項新功能,並通過'ITaskbarList3'界面公開。 –

+0

很多[任務欄擴展]的(https://msdn.microsoft.com/en-us/library/windows/desktop/dd378460.aspx)在Windows 7 –

+0

@JonathanPotter完美的加入!我在搜索時可能使用了錯誤的術語。 – TcAcS

回答

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

} 
+0

我很好奇你認爲這個答案對這個問題有什麼相關性? –

+0

重讀這個問題後,似乎我誤解了這個問題 – Stephen