您的位置:首页 > 编程语言 > C语言/C++

C++类中定义线程

2015-12-07 17:51 363 查看
1. C++ 中如何定义线程函数

有两种方法:a. 定义线程函数为全局函数 b. 定义线程函数为类的静态成员函数

2. C++中的线程函数如何访问类中的成员变量

针对线程函数为类的静态成员进行说明。如果是静态数据成员,当然可以直接访问,但是如果要访问非静态数据成员,直接访问是做不到的。如果要想在线程函数中访问和操作类的非静态成员变量,可以把线程函数作为一个适配器,在适配器中调用类的非静态成员函数。例如:

class CMyClass

{

public:

void TestFunc();

static int ThreadFunc(LPVOID pParam);// Adapter

protected:

int ThreadFuncKernal();// Kernal

}

void CMyClass::TestFunc()

{

AfxBeginThread(TreadFunc, this);

}

// Thread function Adapter

int CMyClass::ThreadFunc(LPVOID pParam)

{

CMyClass *pObj = (CMyClass *)pParam;

return pObj->ThreadFuncKernal();

}

// Thread function kernal

int CMyClass::ThreadFuncKernal()

{

while(1)

{

// my thread

// to control class non-static member

}

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: