thread和mem_fn的使用

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章