How to execute a class member function in a separate thread using C++11 thread class?

我只是一个虾纸丫 提交于 2019-11-28 10:50:46

The instance should be the second argument, like so:

std::thread t1(&SomeClass::threadFunction, *this, arg1, arg2);

I still had problems with the above answer (I think it was complaining it could not copy over a smart pointer?), so rephrased it with a lambda:

void SomeClass::otherFunction() {
  thread t1([this,arg1,arg2](){ threadFunction(arg1,arg2); });
  t1.detach();
}

Then it compiled and ran fine. AFAIK, this is just as efficient, and personally I find it more readable.

(Note: I've also changed join() to detach() as I expect that was the intent.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!