[英]C++ Join multiple threads
I would like to do a for-loop which creates more threads. 我想做一个for循环,创建更多线程。
I've tried with: 我尝试过:
int i;
for (i = 0; i < 10; i++) {
thread t1(nThre);
t1.join();
cout << "Joined thread n'" << i << '\n';
}
But it does not work. 但这行不通。
nThre
is called sequentially (it is a simple void
routine). nThre
被顺序调用(这是一个简单的void
例程)。
I'm also asking if I can use a pre-increment as i
is just an int
, so: ++i
insted of i++
, which should be more performant. 我还问我是否可以使用pre-increment,因为
i
只是一个int
,所以: ++i
插入了i++
,这应该性能更好。
Your problem is that you start a thread, and join it before starting the next one. 您的问题是您启动了一个线程,并在开始下一个线程之前将其加入。 You should do like this :
您应该这样做:
int i;
vector<thread> threads;
for (i = 0; i < 10; i++) {
threads.push_back(thread(nThre));
cout << "Started thread n'" << i << "\n";
}
for (i = 0; i < 10; i++) {
threads[i].join();
cout << "Joined thread n'" << i << "\n";
}
First, you start all your threads, then you wait until they are finished. 首先,启动所有线程,然后等待直到完成。
For the difference between i++
and ++i
, since i
is a integer, it makes no difference here. 对于
i++
和++i
之间的区别,由于i
是整数,因此在这里没有区别。 See this answer for more details. 有关更多详细信息,请参见此答案 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.