34

我想学习如何使用新的 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();
    }

}
4

2 回答 2

73

没有什么花哨的要求;只需使用分配。在你的循环中,写

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

它应该可以工作。

于 2012-05-19T05:13:07.663 回答
-4

对于 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++;
}

编辑:如果你真的想自己处理内存分配并使用指针数组(即向量不是你的东西),那么我不能高度推荐 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;
}
于 2012-05-19T03:06:48.657 回答