Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using c++ 11 multithreading on non-static member function

So, my problem is this:

  • I have a class called NetworkInterface that is built using the RakNet networking library.
  • It holds a method that uses the while loop that RakNet uses to send and receive data.

Now, I made the NetworkInterface class a singleton because I want it to only exist once throughout my game I'm writing.

But, if I'd just call the method with the while loop it would stop my whole gqme so thqt's why I wanted it to run on a different thread so it doesn't interfere with the game mechanics. Now, I used the std::thread object to start the method in NetworkInterface on a different thread but it throws the C3867 error which states that the method needs to be static or some sort (I found this on Google already) but I don't know how to fix this because I have variables that are used in that method that can't be static as well.

I hope this is clear. In short, how would I implement a non-static method from a class in a seperate thread of my program. Or is there a better way? (I don't want to use the Boost library if that pops up)

like image 699
Dries Avatar asked Mar 26 '14 10:03

Dries


1 Answers

You need to provide an object for you to call a non-static member function, just as you can't call method() on its own. To provide that object, pass it to std::thread's constructor after the argument where you put the function.

struct Test {
    void func(int x) {}
};


int main() {
    Test x;
    std::thread t(&Test::func, &x, 42);
    t.join();
}

LIVE EXAMPLE

Notice that I've passed &x. This is because non-static class functions accepts a pointer to the object where it is being called from, and this pointer is the this pointer. The rest, which is 42, is the arguments that corresponds to the method's parameter declaration with 42 coinciding with int x in the example.

like image 108
Mark Garcia Avatar answered Oct 21 '22 15:10

Mark Garcia