在循环中创建线程

时间:2012-01-05 14:38:31

标签: c++ multithreading

我刚测试了类似的东西:

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

它工作正常。我现在想要的是创建尽可能多的线程,因为我在列表中有对象。我用boost :: foreach进行了实验,这很好用。但是我对线程的名称有疑问。

如此简化代码如下:

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

但当然,名字不能在循环中,因为它会覆盖自身并且在循环后无法访问。如何创建线程,以便我可以在创建所有线程之后加入它们?

5 个答案:

答案 0 :(得分:12)

为什么不使用boost::thread_group?您可以创建/添加/删除线程并将它们全部加入(boost::thread_group::join_all())。

boost::thread_group tgroup;
for(...)
{
  tgroup.create_thread(boost::bind(&Class::Function, this, ...)) ;
}
tgroup.join_all();

但要注意你创建的数字线程,太多线程可能导致OutOfMemory

答案 1 :(得分:3)

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

如下所示(可能更多的伪代码:-))

list<boost::thread*> threads;

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

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

答案 2 :(得分:3)

您可以将它们保存在一个数组中:

size_t const thread_count = 5;
boost::thread threads[thread_count];
for (size_t i = 0; i < thread_count; ++i) {
    threads[i] = boost::bind(&Class::Function, this, ...));
}

在C ++ 11中,您可以将std::thread保留在友好的容器中,例如std::vector

std::vector<std::thread> threads;
for (int i = 0; i < 5; ++i) {
    threads.push_back(std::thread(boost::bind(&Class::Function, this, ...))));
}

这不适用于C ++ 03中的boost::thread,因为boost::thread不可复制;我的示例中的临时赋值是有效的,因为有些Boost魔法可以模拟移动语义。我也无法在C ++ 11中使用boost::thread,但这可能是因为我没有最新版本的Boost。所以在C ++ 03中,你坚持使用一个数组或一个容器(最好是智能)指针。

答案 3 :(得分:2)

为什么不将线程放入自己的容器中,例如向量(通过智能指针假设它们是不可复制的)?

答案 4 :(得分:0)

免责声明:我不使用boost,但如果它像其他C ++一样工作,我相信这可能是正确的。如果这是垃圾,将删除。

boost::thread** threads;
threads = new boost::thread*[THREAD_COUNT];

for(int i = 0; i < THREAD_COUNT; i++)
{
   threads[i] = new boost::thread(...);
}

...

for(int i = 0; i < THREAD_COUNT; i++)
   delete threads[i];

delete[] threads;

...

这个想法只是根据你想要的数量动态地为你的对象类型分配一个指针数组。然后,为每个动态创建一个并在循环中调用适当的构造函数。最终,您/可能需要清理它们,因此您可以使用delete []调用。我不明白为什么malloc()/ free()和/或矢量类型也不起作用。

相关问题