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