C++ 将成员函数传递给 std::thread
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11057800/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing member functions to std::thread
提问by Whyrusleeping
Possible Duplicate:
Start thread with member function
可能的重复:
使用成员函数启动线程
I have recently been playing around with the new std::thread library in c++11 and I came across a problem. When i try to pass a classes function into a new thread, it gives me an error (I dont have the exact error text right now since im away from home) I had a class like this
我最近一直在使用 c++11 中的新 std::thread 库,但遇到了一个问题。当我尝试将一个类函数传递给一个新线程时,它给了我一个错误(因为我不在家,我现在没有确切的错误文本)我有一个这样的类
class A
{
void FunctA();
void FunctB();
void run()
{
std::thread t(FunctA);
std::thread r(FunctB);
}
}
What am I doing wrong?
我究竟做错了什么?
回答by Griwes
class A
{
void FunctA();
void FunctB();
void run()
{
std::thread t(&A::FunctA, this);
std::thread r(&A::FunctB, this);
}
};
Pointers to member functions are different from pointers to functions, syntax of calling them is different, as well, and requires instance of class. You can just pass pointer to instance as second argument of std::thread
constructor.
指向成员函数的指针与指向函数的指针不同,调用它们的语法也不同,并且需要类的实例。您可以将指向实例的指针作为std::thread
构造函数的第二个参数传递。
回答by Egor Shkorov
I think, the problem is that you can't get pointer to member function in a way similar to functions. Hereyou will find more information about this.
我认为,问题在于您无法以类似于函数的方式获取指向成员函数的指针。在这里,您将找到更多关于此的信息。
Also, it would be much easier to answer, if you provided compipler error text.
此外,如果您提供编译器错误文本,回答起来会容易得多。