0

I have startSending procedure and a friend function (sending) inside sender class. I want to call the friend function from a new thread, so I create a new thread inside startSending procedure.

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){
}

But I got this error

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

What is the correct way to call sending from pthread_create?

Ilya
  • 4,583
  • 4
  • 26
  • 51
ZZZ
  • 1,415
  • 5
  • 16
  • 29

3 Answers3

2

As per documentation of pthread_create, you must pass in the function to be executed, not its invocation:

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

The argument with which the thread will call the function is passed as the 4th parameter to pthread_create, so in your case it's this.

And (while this is not actually necessary with most practical compilers on most common platforms) going strictly by the rules, since pthread_create is a C function, the function which you send to it should have C language linkage too:

extern "C" void* sending (void * callerobj){
}
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
2

pthread_create signature looks like this:

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

So in your case, the pointer to sending must be passed as the third argument, and this (the argument that will be passed to sending) nees to be passed as the last argument:

pthread_create(&tSending, NULL, &sending, this);
SingerOfTheFall
  • 29,228
  • 8
  • 68
  • 105
0
pthread_create(&tSending, NULL, sending, this);

OR

pthread_create(&tSending, NULL, &sending, this);
user1
  • 4,031
  • 8
  • 37
  • 66