Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pthread_create - invalid use of non-static member function [duplicate]

Tags:

c++

pthreads

I've been trying to learn how to use threads, and I'm getting stuck on creating one. I'm having the thread get created in a class constructor like this...

Beacon::Beacon() {
    pthread_create(&send_thread,NULL, send, NULL);
}

The send function isn't doing anything yet, but here's what it looks like.

void Beacon::send(void *arg){
    //Do stuff
}

Everytime I run the code I get an invalid use of non-static member funciton error. I've tried using &send, and that didn't work. I also had the last NULL parameter set to this, but that didn't work. I've been looking at other example code to try and mimmick it, but nothing seems to work. What am I doing wrong?

like image 786
ThatBoiJo Avatar asked Jul 06 '16 12:07

ThatBoiJo


1 Answers

If you can't use std::thread I recommend you create a static member function to wrap your actual function, and pass this as the argument to the function.

Something like

class Beacon
{
    ...

    static void* send_wrapper(void* object)
    {
        reinterpret_cast<Beacon*>(object)->send();
        return 0;
    }
};

Then create the thread like

pthread_create(&send_thread, NULL, &Beacon::send_wrapper, this);
like image 144
Some programmer dude Avatar answered Oct 14 '22 07:10

Some programmer dude