如何实现类的成员函数创建线程
class CMySocket
{
public:
DWORD WINAPI WorkThread(LPVOID CompletetionPortID);
...
};
有如上类,在类中某函数想以函数(WorkThread)
CreateThread(NULL, 0, WorkThread, ¶m, 0, &ThreadID))
编译会报错:cannot convert parameter 3 from unsigned long (void *) to unsigned long (__stdcall *)(void *) None of the functions with this name in scope match the target type
解决方法:
1。
这种情况,一般是将线程函数申明为静态,如:
class CRealtimeTask
{
public:
static UINT taskmain(LPVOID param);
BOOL StartTask();
};
在类中定义的成员函数,VC在编译时会强加一个this指针,所以才会出现上边的情况。将该成员函数声明为static类型,可以将this指针除去,但static成员函数只能访问static成员。2。
以将线程函数申明成友员函数,这样可以传入该类的指针,访问类的成员;
class CRealtimeTask
{
public:
friend UINT taskmain(LPVOID param);
BOOL StartTask();
};
UINT taskmain(LPVOID param)
{
CRealtimeTask * pTaskMain = (CRealtimeTask *) param;
//通过pTaskMain指针引用。
return TRUE;
}
BOOL CRealtimeTask::StartTask()
{
AfxBeginThread(taskmain,this);
}3。
可以对成员函数实现回调,并访问非静态成员的,如下所示,这是为了实现线程函数访问类成员而实现的类。比MFC的实现方法好象要好一点。
class base;
typedef int (base::*fnCallBack)(void *p);
struct callback(void *param;fnCallBack *pfuc;base *pThis;};
class base{
static int myThreadfuc(void *p){
struct callback *p1=(struct callback *)p;
base *pthis=p1->base;fnCallBack *pfuc=p1->pfuc;void *param=p1->param;
int i=(pthis->*pfuc)(param);delete p;
return i;
}
public:
void myCreateThread(fnCallBack pfuc,void *param){
struct callback *p=new struct callback;
p.param=param;p.pThis=this;p.pfuc=pfuc;
::CreateThread(myThreadfuc,p);
}
virtual int myCallBack(void *p){printf("Its base class. ");return 0;}
};
class derived:public base{
int myCallBack(void *p){printf("Its derived class ");}
};
void myCreateThreadImitate(fnCallBack fuc,void *p)
{
(*fuc)(p);
}
void main()
{
base p;char *param;
p.myCreateThread(&(base::myCallBack),param);
derived p2;p2.myCreateThread(&(base::myCallBack),param);
}
补充:软件开发 , Vc ,