对于参数“1”到“void* sending(void*)”,C++ 无法将“sender”转换为“void*”

C++ cannot convert ‘sender’ to ‘void*’ for argument ‘1’ to ‘void* sending(void*)’

我在 sender class 中有 startSending 过程和一个友元函数 (sending)。我想从一个新线程调用 friend 函数,所以我在 startSending 过程中创建了一个新线程。

class sender{
    public:
    void startSending();

    friend void* sending (void * callerobj);
}

void sender::startSending(){
    pthread_t tSending;
    pthread_create(&tSending, NULL, sending(*this), NULL);
    pthread_join(tSending, NULL);
}

void* sending (void * callerobj){
}

但是我遇到了这个错误

cannot convert ‘sender’ to ‘void*’ for argument ‘1’ to ‘void* sending(void*)’

从 pthread_create 调用发送的正确方法是什么?

根据documentation of pthread_create,您必须传入要执行的函数,而不是它的调用:

pthread_create(&tSending, NULL, &sending, this);

线程将调用该函数的参数作为第 4 个参数传递给 pthread_create,因此在您的情况下它是 this.

并且(虽然对于大多数常见平台上的大多数实用编译器来说这实际上不是必需的)严格遵守规则,因为 pthread_create 是一个 C 函数,你发送给它的函数应该有 C 语言联动太:

extern "C" void* sending (void * callerobj){
}
pthread_create(&tSending, NULL, sending, this);

pthread_create(&tSending, NULL, &sending, this);

pthread_create 签名看起来像这样:

int pthread_create(pthread_t *thread, //irrelevant
                   const pthread_attr_t *attr, //irrelevant
                   void *(*start_routine) (void *), //the pointer to the function that is going to be called
                   void *arg); //the sole argument that will be passed to that function

所以在你的例子中,指向 sending 指针 必须作为第三个参数传递,并且 this (将传递给sending) 需要作为最后一个参数传递:

pthread_create(&tSending, NULL, &sending, this);