简体   繁体   English

在非静态成员函数上使用c ++ 11多线程

[英]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. 我有一个名为NetworkInterface的类,它使用RakNet网络库构建。
  • It holds a method that uses the while loop that RakNet uses to send and receive data. 它拥有一个使用RakNet用来发送和接收数据的while循环的方法。

Now, I made the NetworkInterface class a singleton because I want it to only exist once throughout my game I'm writing. 现在,我将NetworkInterface类设为单例,因为我希望它在我写的游戏中只存在一次。

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. 但是,如果我只是用while循环调用方法,它将停止我的整个gqme所以这就是为什么我希望它在不同的线程上运行,所以它不会干扰游戏机制。 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. 现在,我使用std :: thread对象在另一个线程上的NetworkInterface中启动方法,但它抛出C3867错误,该错误表明该方法需要是静态的或某种类型(我已经在Google上发现了这个)但是我不知道我知道如何解决这个问题,因为我在该方法中使用的变量也不能是静态的。

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) (如果弹出,我不想使用Boost库)

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. 您需要提供一个对象来调用非静态成员函数,就像您不能自己调用method() To provide that object, pass it to std::thread 's constructor after the argument where you put the function. 要提供该对象,请在放置函数的参数后将其传递给std::thread的构造函数。

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 . 请注意,我已通过&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. 这是因为非静态类函数接受指向它的对象的指针,并且该指针是this指针。 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. 其余的, 42 ,是与方法的参数声明相对应的参数,其中42与示例中的int x一致。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM