5

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?

ThatBoiJo
  • 319
  • 2
  • 14
  • 2
    Very simplified, all non-member function have a hidden first argument that becomes the `this` variable. I recommend you look into [`std::thread`](http://en.cppreference.com/w/cpp/thread/thread) instead. – Some programmer dude Jul 06 '16 at 12:57

1 Answers1

10

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);
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621