我有一個代碼,我測試了多少時間將執行10個線程。C++線程的執行時間和執行線程在另一個線程
#include <iostream>
#include <thread>
#include <chrono>
#include <time.h>
using namespace std;
void pause_thread(int n){
this_thread::sleep_for(chrono::seconds(n));
cout << "pause of " << n << " seconds ended\n";
}
int main(){
clock_t EndTime = clock();
thread threads[10];
cout << "Spawning 10 threads...\n";
for (int i = 0; i<10; ++i)
threads[i] = thread(pause_thread, i + 1);
cout << "Done spawning threads. Now waiting for them to join:\n";
for (int i = 0; i<10; ++i)
threads[i].join();
cout << "All threads joined!\n";
cout << "==================================================\n";
cout << "Time of executing threads: " << (double)(clock() - EndTime)/CLOCKS_PER_SEC << endl;
system("pause");
return 0;
}
輸出是這樣的:
Spawning 10 threads...
Done spawning threads. Now waiting for them to join:
pause of 1 seconds ended
pause of 2 seconds ended
pause of 3 seconds ended
pause of 4 seconds ended
pause of 5 seconds ended
pause of 6 seconds ended
pause of 7 seconds ended
pause of 8 seconds ended
pause of 9 seconds ended
pause of 10 seconds ended
All threads joined!
==================================================
Time of executing threads: 10.041
首先的問題是:爲什麼該程序的執行需要10041秒如果每個線程之間的暫停是1秒?該程序發生了什麼,執行額外的0.041s? 第二個問題是:這是正確的方式來執行線程在另一個線程?
threads[i] = thread(...);
這是否意味着線程在線程中?
如果不是,怎麼辦(在另一個線程中執行線程)?
關於你的第一個問題,暫停時間並不能保證是你設置的時間(在本例中爲1秒)。該線程將阻止*至少* 1秒,也許更多一點。有關更多詳細信息,請參閱http://en.cppreference.com/w/cpp/thread/sleep_for。 –