C ++连接多个线程 [英] C++ Join multiple threads

查看:80
本文介绍了C ++连接多个线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做一个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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆