我有一个代码,我测试了多少时间将执行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。 –