当需要利用类成员函数( MyClass::thread_func )来创建子线程时,需如下码码:
std::thread t(std::mem_fn(&MyClass::thread_func), Object, args..);
例子如下:
#include <iostream>
#include <thread>
void fun()
{
std::cout << "hello world" << std::endl;
}
class cls
{
public:
void funcls()
{
std::cout << "cls hello" << std::endl;
}
};
int main()
{
cls m_cls;
//std::thread t(fun);
std::thread t(std::mem_fn(&cls::funcls), &m_cls);// 类成员函数需用mem_fn
if(t.joinable())
t.join();
return 0;
}
类似的
void MyTestCls::test()
{
m_threadTest = std::thread(std::mem_fn(&MyTestCls::testFun),this,nIndex);
}
void MyTestCls::testFun(int nTndex)
{
...
}
如果thread_func为static,则不用写object。否则需要,如主进程所调函数也为该类成员,则传入this指回自己。