MultiThread Of Member Functions
发现使用CreateThread()的方法无法对类地成员函数创建多线程。
【例如】
//该代码将直接导致程序崩溃:
//创建线程
////////////////////////////////////////////
void CMuti_2_ParamentsDlg::OnBnClickedOk()
{
DWORD ThreadID;
HANDLE hThread = CreateThread(
NULL,
0,
(LPTHREAD_START_ROUTINE)Add(1, 2),
0,
0,
&ThreadID);
}
//示例函数[成员函数]
//////////////////////////////////////////////////
const int CMuti_2_ParamentsDlg::Add(int a, int b)
{
return a + b;
}
DEBUG时弹出的错误是:
那么如何对于CLASS的Member Functions创建多线程呢?
方案1:
将要被创建多线程的成员函数声明为static型的。
因为在类中定义的成员函数,VC在编译时会强加一个this指针,所以才会出现异常。将该成员函数声明为static类型,可以将this指针除去,但static成员函数只能访问static成员。
Example:
#include<windows.h>
#include<stdio.h>
#include<process.h>
class test
{
int mx;
public:
test(int x):mx(x){}
static unsigned int __stdcall threadProc(void* pV) { test* p = (test*)pV;
p->func();
return 0;
}
void func()
{
printf("%d/n",mx);
}
};
int main()
{
test x(10);
_beginthreadex(0,0,test::threadProc,(void*)&x,0,0);
Sleep(100);
return 0;
}