在循环中创建线程 [英] Create Threads in a loop

查看:186
本文介绍了在循环中创建线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是测试这样:

boost::thread workerThread1(boost::bind(&Class::Function, this, ...);
boost::thread workerThread2(boost::bind(&Class::Function, this, ...);

这样简化的代码看起来像这样:

and it works fine. What i now want, is to create as many Threads as i have objects in a list. I have experimentet with boost::foreach and this works fine. But i have problems with the names of the threads.

So simplified the code looks like this:

但是当然名字不能在循环中在这里,因为它覆盖自己,并且在循环后不能访问如何创建线程,

for { boost:thread name(...); }


推荐答案

你不能创建一个列表(或类似的)线程,然后创建它们并添加到列表中。

Can you not just create a list (or similar) of threads and then just create them and add to the list.

类似以下内容(很可能是更多的伪代码:-))

Something like the following (which is likely more pseudo code that anything :-) )

list<boost::thread*> threads;

for
{
    boost::thread* name = new boost::thread(...);
    threads.push_back(name);
}

如另一个答案中提到的,你可以使用智能指针,上面提到你有一个定义的线程数,所以一个数组/向量将是一个更好的选择,但正如我所说的代码上面是不完美

As mentioned in another answer you can use smart pointers which would be better and you mentioned you have a defined number of threads so an array/vector would be a better choice but as I said the code above isn't perfect anyway

这篇关于在循环中创建线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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