我有一个代码,我正在测试执行10个线程需要多长时间。
#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
第一个问题是:如果每个线程之间的暂停时间为1秒,为什么执行程序需要10,041秒?该程序发生了什么,并执行了额外的0.041? 第二个问题是:这是在另一个线程中执行线程的正确方法吗?
threads[i] = thread(...);
这是否意味着线程在线程中?
如果没有,怎么办(在另一个线程中执行线程)?
答案 0 :(得分:0)
Brandon Haston的评论很好地回答了第一个问题。
对第二个问题的回答不符合评论。
threads[i] = thread(...);
表示已创建std :: thread并且已将其代表性std :: thread对象分配给std :: thread数组中的插槽。这提出了一个问题,当我有一个编译器可以使用时,我将不得不自己查看:刚被覆盖的线程发生了什么?
无论如何,新线程不在另一个线程内。线程没有任何所有权相互的概念。进程拥有线程,但线程没有。线程可以启动另一个线程。例如,
void pause_thread(int n){
this_thread::sleep_for(chrono::seconds(n));
cout << "pause of " << n << " seconds ended\n";
if (! cows_are_home)
{
thread newthread(pause_thread, 1);
newthread.detach();
}
}
每个新线程将等待大约1秒钟,然后创建一个等待一秒钟并创建另一个线程的线程,这将持续到奶牛回家。