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

时间:2015-10-14 08:01:23

标签: c++ pthreads friend

我在sending类中有startSending过程和友元函数(sender)。我想从一个新线程调用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调用发送的正确方法是什么?

3 个答案:

答案 0 :(得分:2)

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

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

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

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

extern "C" void* sending (void * callerobj){
}

答案 1 :(得分:2)

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);

答案 2 :(得分:0)

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

OR

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