C++ 创建的线程如何调用类函数

2024-11-15 22:37:16
推荐回答(2个)
回答(1):

把类指针做为参数传进去线程函数里,然后用参数调用类里的函数。

回答(2):

大概写了些,没调试过,以前用过。

static void CPPThread(LPVOID lpParameter)
{
CPPClass *pClass = (CPPClass *)lpParameter;
//add your code
pClass->Fun();
}

class CPPClass
{
public:
CPPClass():m_CPPThreadHandle(0){}
~CPPClass(){}
int CreateCPPThread();
int CloseCPPThread();
int Fun();
protected:
HANDLE m_CPPThreadHandle;
};

int CPPClass::CreateCPPThread()
{
m_CPPThreadHandle=(HANDLE)_beginthread(CPPThread,4096,this);
if(m_CPPThreadHandle==0) return false;
}

int CPPClass::CloseCPPThread()
{
if(m_CPPThreadHandle!=0)
{
TerminateThread(m_CPPThreadHandle,0);
m_CPPThreadHandle=0;
}
}

int CPPClass::Fun()
{
//add your code
}