class Customer{
public:
Customer(){};
Customer(int i)
{id=i;}
~Customer(){...};
static void* run(void* arg)
{
//code for execution
return NULL;
}
private:
static int id;
}
int main(void)
{
int index;
int status;
//Create Customer Threads
pthread_t Customer_Threads[50];
Customer *Customers;
Customers=new Customer[50];
// create 50 Customer threads
for (index = 0; index < 50; index++) {
Customers[index]=*new Customer(index);
status = pthread_create (&Customer_Threads[index], NULL, Customers[index].run, NULL);
assert(0 ==status);
}
}
我的问题是,当我尝试使用pthread_create来调用Customer类中的函数时,会弹出一个关于未定义的对Customer ::〜A()&#39;&#39;&#39; 和&#39;未定义的引用`Customer :: A()&#39;&#39;。
我想创建一个Customer对象的数组,并使用multi_thread来执行Customer类中的run函数,我不知道如何处理这些错误。感谢。
我在Xcode中使用C ++并在linux中编译。
-----------------更新-------------------
现在我仍然面临一个错误&#39;未定义的引用`Customer :: id&#39;&#39;。
不确定原因。
答案 0 :(得分:0)
我建议您使用stl容器而不是C数组。
Customer :: run是静态函数,所以你不需要像这样传递这个函数:
status = pthread_create (..., Customers[index].run, ...);
要将静态函数传递给pthread,需要将指针传递给静态函数:
status = pthread_create(..., &Customers::run, ...);
好的,我们传递函数,但我想你希望将具体的Customer对象传递给线程
status = pthread_create(..., &Customers::run, (void *)Customers[index]);
代码的最终版本看起来像
void *Customer::run(void *arg)
{
Customer *this_ = (Customer *)arg;
// Do something
}
std::list<pthread_t> pthreads(50);
std::list<Customer *> Customers(50);
for (size_t i = 0; i < pthreads.size(); ++i)
{
Customers[i] = new Customer();
status = pthread_create(&pthreads[i], &Customer::run, (void *)Customers[i]);
...
}
for (size_t i = 0; i < pthreads.size(); ++i)
{
pthread_join(pthreads[i]); // block until thread end
delete Customers[i]; // free mem
}