C ++连接多个线程 [英] C++ Join multiple threads
问题描述
我想做一个for循环,创建更多线程.
I would like to do a for-loop which creates more threads.
我尝试过:
int i;
for (i = 0; i < 10; i++) {
thread t1(nThre);
t1.join();
cout << "Joined thread n'" << i << '\n';
}
但是它不起作用.依次调用nThre
(这是一个简单的void
例程).
But it does not work. nThre
is called sequentially (it is a simple void
routine).
我还问我是否可以使用预增量,因为i
只是一个int
,所以:
++i
插入了i++
,应该会表现得更好.
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.
推荐答案
您的问题是您启动了一个线程,并在启动下一个线程之前将其加入.您应该这样做:
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.
对于i++
和++i
之间的差异,由于i
是整数,因此在这里没有区别.请参阅此答案了解更多信息.
For the difference between i++
and ++i
, since i
is a integer, it makes no difference here. See this answer for more details.
这篇关于C ++连接多个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!