编译错误:
ompiling...
ThreadDlg.cpp
D:\1\Thread\ThreadDlg.cpp(91) : error C2664: 'CreateThread' : cannot convert parameter 3 from 'unsigned long (void *)' to 'unsigned long (__cdecl *)(void *)'
None of the functions with this name in scope match the target type
D:\1\Thread\ThreadDlg.cpp(92) : error C2664: 'CreateThread' : cannot convert parameter 3 from 'unsigned long (void *)' to 'unsigned long (__cdecl *)(void *)'
None of the functions with this name in scope match the target type
Error executing clarm.exe.
ThreadDlg.obj - 2 error(s), 0 warning(s)
代码:
DWORD CThreadDlg::ThreadProc(PVOID pArg)
{
int i;
TCHAR tmp[10];
CListBox *pListBox;
pListBox=(CListBox*)pArg;
i=0;
while(1)
{
_itow(i,tmp,10);
pListBox->AddString (tmp); //显示当前线程的计数值
i++; //增加计数值
Sleep(200); //延时200Ms
}
return i;
}
void CThreadDlg::OnBtnexec()
{
// TODO: Add your control notification handler code here
DWORD dwThreadId1,dwThreadId2;
HANDLE handle1,handle2;
CListBox *pListOne;
CListBox *pListTwo;
pListOne=(CListBox*)GetDlgItem(IDC_LISTONE);
pListTwo=(CListBox*)GetDlgItem(IDC_LISTTWO);
//创建线程
handle1=CreateThread(NULL,0,ThreadProc,pListOne,0,&dwThreadId1);
handle2=CreateThread(NULL,0,ThreadProc,pListTwo,0,&dwThreadId2);
if(!handle1)
{
AfxMessageBox(_T("Thread 1 create failed"));
}
if(!handle2)
{
AfxMessageBox(_T("Thread 2 Create failed"));
}
CloseHandle(handle1);
CloseHandle(handle2);
}
使用全局函数作为线程的执行函数,而不是放在类里面。
比如
UINT ThreadProc(LPVOID para)
{
.....
}
void CThreadDlg::OnBtnexec()
{
// TODO: Add your control notification handler code here
DWORD dwThreadId1,dwThreadId2;
HANDLE handle1,handle2;
CListBox *pListOne;
CListBox *pListTwo;
pListOne=(CListBox*)GetDlgItem(IDC_LISTONE);
pListTwo=(CListBox*)GetDlgItem(IDC_LISTTWO);
//创建线程
handle1=CreateThread(NULL,0,ThreadProc,pListOne,0,&dwThreadId1);
handle2=CreateThread(NULL,0,ThreadProc,pListTwo,0,&dwThreadId2);
}
他说线程的执行函数ThreadProc方法,不要作为一个类的函数,应该是一个全局的。即UINT ThreadProc(LPVOID para)
而不是
DWORD CThreadDlg::ThreadProc(PVOID pArg)
也可以写成静态函数,用static,但需要对ThreadProc里面用到的类成员变量的引用做必要的修改,才能正确编程