这可能会做你想做的。我只是把它扔在一起,所以我提前道歉,如果有任何语法错误。它涉及您的两个问题(不正确的第三个和第四个参数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线程类和对象(线程,mutex,condition_variable等)来使用raw-pthread。他们真的是蜜蜂的膝盖。类似的东西(尽管有自动计算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
使用'nodeObj + i',而不是'nodeObj [I]'。并且在'pthread_create()'调用中抛出cast-to-void *;它只会工作(尽管你可能想**加入**这些线程,并在完成时清理该分配)。 – WhozCraig
嗨@WhozCraig感谢您的快速回复。我试着做你说的话,但我仍然得到以下错误:初始化'int pthread_create(pthread_t *,const pthread_attr_t *,void *(*)(void *),void *)'参数3' –
函数应返回void *,不是void。 – WhozCraig