This question already has answers here:
Undefined reference to a static member
                                
                                    (4个答案)
                                
                        
                                3年前关闭。
            
                    
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()''
 和对“ Customer :: A()”的未定义引用。

我想创建一个类Customer对象的数组,并使用multi_thread在类Customer中执行run函数,我不知道如何处理这些错误。谢谢。

我在Xcode中使用C ++,在Linux中进行编译。

-----------------更新-------------------

现在,我仍然遇到错误“对`Customer :: id的未定义引用”。

不知道为什么。

最佳答案

我建议您使用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
}

关于c++ - 类中的Pthread_create调用函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36195473/

10-11 22:53
查看更多