用类的静态函数作为线程函数
//使用类的静态函数作为线程函数,缺点无法当问类的保护和私有成员
//下面几行 是在类的成员函数里面调用的,开启了一个线程,Start_RedTest作为线程函数
DWORD tid;
HANDLE hHand = ::CreateThread(NULL,0,&Start_RedTest,(PVOID)this,0,&tid);
if(hHand!=INVALID_HANDLE_VALUE) CloseHandle(hHand);
<img src="https://img-blog.csdn.net/20160217171143213?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="" />
用类的非静态函数作为线程函数
解决上面用法的限制
union 先回顾一下它在此的作用:共用一个内存地址
我们在类外:
union {
unsigned int (__stdcall *ThreadPorc)(void*); //a
unsigned int (__stdcall dlg_mainframe::*MemberProc)(); //b
}StdcallProc;
unsigned int (__stdcall *ThreadPorc)(void*); //a
unsigned int (__stdcall dlg_mainframe::*MemberProc)(); //b
}StdcallProc;
在给类添加一个和 unsigned int (__stdcall dlg_mainframe::*MemberProc)(); 相似的函数
声明 unsigned int __stdcall listenThreadFunction();
实现:
unsigned int __stdcall dlg_mainframe::listenThreadFunction()
{
this->任何成员函数();
return 0;
}
{
this->任何成员函数();
return 0;
}
创建线程:
//用类的非静态函数作为线程函数来解决问题
//注意作为线程的非静态成员函数是没有参数的,因为非静态成员函数有一个默认的this参数
// 即,函数参数列表为空的非静态成员函数已经有了一个参数,那就在创建线程的时候将this作为参数值传入即可.
StdcallProc.MemberProc =&dlg_mainframe::listenThreadFunction;
CloseHandle((HANDLE)_beginthreadex(NULL, 0, StdcallProc.ThreadPorc, (void*)this, 0, NULL));
//注意作为线程的非静态成员函数是没有参数的,因为非静态成员函数有一个默认的this参数
// 即,函数参数列表为空的非静态成员函数已经有了一个参数,那就在创建线程的时候将this作为参数值传入即可.
StdcallProc.MemberProc =&dlg_mainframe::listenThreadFunction;
CloseHandle((HANDLE)_beginthreadex(NULL, 0, StdcallProc.ThreadPorc, (void*)this, 0, NULL));