在多线程程序中,无论我们使用AfxBeginThread ,CreateThread,_beginthread构造线程函数,因为线程函数只能是全局函数或静态函数,下面拿静态函数来举例说明,静态函数中可以直接访问静态成员,但是访问类的非静态函数或成员变量就必须做一个适配器,代码如下:
class CStaticThread
{
public:
static int ThreadFunc(LPVOID pParam);/
protected:
int ThreadFuncKernal();
}
void CStaticThread::Func()
{
AfxBeginThread(TreadFunc, this);
}
int CStaticThread::ThreadFunc(LPVOID pParam)
{
CStaticThread*pObj = (CStaticThread*)pParam;
return pObj->ThreadFuncKernal();
}
// Thread function kernal
int CStaticThread::ThreadFuncKernal()
{
while(1)
{
// my thread
// to control class non-static member
}
return 0;
}
网上找的答案。互相学习 |