C++ 类的 std::thread 调用方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10998780/
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
std::thread calling method of class
提问by kobra
Possible Duplicate:
Start thread with member function
可能的重复:
使用成员函数启动线程
I have a small class:
我有一个小班:
class Test
{
public:
void runMultiThread();
private:
int calculate(int from, int to);
}
How its possible to run method calculate
with two differents set of parametrs(for example calculate(0,10)
, calculate(11,20)
) in two threads from method runMultiThread()
?
如何在方法的两个线程中calculate
使用两个不同的参数集(例如calculate(0,10)
,calculate(11,20)
)运行方法runMultiThread()
?
PS Thanks I have forgotten that I need pass this
, as parameter.
PS 谢谢我忘了我需要 pass this
,作为参数。
回答by Kerrek SB
Not so hard:
没那么难:
#include <thread>
void Test::runMultiThread()
{
std::thread t1(&Test::calculate, this, 0, 10);
std::thread t2(&Test::calculate, this, 11, 20);
t1.join();
t2.join();
}
If the result of the computation is still needed, use a futureinstead:
如果仍然需要计算结果,请改用未来:
#include <future>
void Test::runMultiThread()
{
auto f1 = std::async(&Test::calculate, this, 0, 10);
auto f2 = std::async(&Test::calculate, this, 11, 20);
auto res1 = f1.get();
auto res2 = f2.get();
}