當需要利用類成員函數( 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指回自己。