如何在 C++11 中创建线程对象数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10661792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:18:43  来源:igfitidea点击:

How to create an array of thread objects in C++11?

c++arraysmultithreadingconstructorc++11

提问by Squall

I want to learn how to create multiple threads with the new C++ standard library and store their handles into an array.
How can I start a thread?
The examples that I saw start a thread with the constructor, but if I use array, I cannot call the constructor.

我想学习如何使用新的 C++ 标准库创建多个线程并将它们的句柄存储到数组中。
我怎样才能开始一个线程?
我看到的示例使用构造函数启动了一个线程,但是如果我使用数组,则无法调用构造函数。

#include <iostream>
#include <thread>

void exec(int n){
    std::cout << "thread " << n << std::endl;
}

int main(int argc, char* argv[]){

    std::thread myThreads[4];

    for (int i=0; i<4; i++){
        //myThreads[i].start(exec, i); //?? create, start, run
        //new (&myThreads[i]) std::thread(exec, i); //I tried it and it seems to work, but it looks like a bad design or an anti-pattern.
    }
    for (int i=0; i<4; i++){
        myThreads[i].join();
    }

}

回答by Nevin

Nothing fancy required; just use assignment. Inside your loop, write

不需要任何花哨的东西;只需使用赋值。在你的循环中,写

myThreads[i] = std::thread(exec, i);

and it should work.

它应该工作。

回答by Kionmaru

With C++0x / C++11, try using vectors instead of arrays of threads; something like this:

在 C++0x/C++11 中,尝试使用向量而不是线程数组;像这样:

vector<thread> mythreads;
int i = 0;
for (i = 0; i < 8; i++)
{
   mythreads.push_back(dostuff, withstuff);
}
auto originalthread = mythreads.begin();
//Do other stuff here.
while (originalthread != mythreads.end())
{
   originalthread->join();
   originalthread++;
}

Edit: If you really want to handle memory allocation yourself and use an array of pointers (i.e. vectors just aren't your thing) then I can't recommend valgrind highly enough. It has memory allocation checkers and thread checkers, etc, etc. Priceless for this kind of thing. In any case, here's an example program using an array of manually allocated threads, and it cleans up after itself (no memory leaks):

编辑:如果你真的想自己处理内存分配并使用指针数组(即向量不是你的东西),那么我不能高度推荐 valgrind。它有内存分配检查器和线程检查器等等。这种东西是无价的。无论如何,这是一个使用手动分配线程数组的示例程序,它会自行清理(无内存泄漏):

#include <iostream>
#include <thread>
#include <mutex>
#include <cstdlib>

// globals are bad, ok?
std::mutex mymutex;


int pfunc()
{
  int * i = new int;
  *i = std::rand() % 10 + 1;

  // cout is a stream and threads will jumble together as they actually can
  // all output at the same time. So we'll just lock to access a shared
  // resource.
  std::thread::id * myid = new std::thread::id;
  *myid = std::this_thread::get_id();
  mymutex.lock();
  std::cout << "Hi.\n";
  std::cout << "I'm threadID " << *myid << std::endl;
  std::cout << "i is " << *i << ".\n";
  std::cout << "Bye now.\n";
  mymutex.unlock();

  // Now we'll sleep in the thread, then return.
  sleep(*i);
  // clean up after ourselves.
  delete i;
  delete myid;
  return(0);
}


int main ()
{

  std::thread * threadpointer = new std::thread[4];
  // This seed will give us 5, 6, 4, and 8 second sleeps...
  std::srand(11);
  for (int i = 0; i < 4; i++)
    {
      threadpointer[i] = std::thread(pfunc);
    }
  for (int i = 0; i < 4; i++)
      // Join will block our main thread, and so the program won't exit until
      // everyone comes home.
    {
      threadpointer[i].join();
    }
  delete [] threadpointer;
}