这可能会做你想要的。我只是把它放在一起,所以如果有任何语法错误,我提前道歉。它解决了您的两个问题(不正确的第三个和第四个参数pthread_create()
)以及使用 RAII 进行分配管理:
#include <iostream>
#include <vector>
using namespace std;
struct Node
{
int value;
};
void *start(void* p)
{
Node* obj = (Node*)p;
cout << obj->value;
return NULL;
}
int main(int argc, char *argv[])
{
int n;
cin >> n;
if (n <= 0)
return EXIT_FAILURE;
std::vector<Node> nodes(n);
std::vector<pthread_t> threads(n);
for (int i=0;i<n;++i)
pthread_create(threads.data()+i, NULL, &start, nodes.data()+i);
std::for_each(threads.begin(), threads.end(),
[](pthread_t& t) { pthread_join(t, NULL); });
return EXIT_SUCCESS;
}
C++11 线程:他们的晚餐吃什么
我建议使用 C++11 线程类和对象(线程、互斥体、条件变量等)而不是使用 raw-pthreads。他们真的是蜜蜂的膝盖。类似的东西(尽管带有自动计算的 N)如下所示:
#include <iostream>
#include <vector>
#include <thread>
#include <memory>
using namespace std;
struct Node
{
int value;
Node() : value() {}
// member function we're using as thread proc
void thread_proc(int n)
{
value = n;
}
};
int main(int argc, char *argv[])
{
// allocate nodes
vector<Node> nodes(std::max(std::thread::hardware_concurrency()+1, 4U));
// starts threads
vector<thread> threads;
for (int i=0; i<nodes.size(); ++i)
threads.emplace_back(std::bind(&Node::thread_proc, nodes.data()+i, i+1));
// wait for all threads to complete.
for(auto &t : threads)
t.join();
// proof we really did hit *our* nodes in the threads.
for (auto& node : nodes)
cout << "Node value: " << node.value << endl;
return EXIT_SUCCESS;
}
输出
Node value: 1
Node value: 2
Node value: 3
Node value: 4
Node value: 5