您的位置:首页 > 其它

创建线程,让线程函数回调函数也像成员函数一样

2014-09-01 11:30 134 查看
// 这里只作最简单的提示
void CMfcDlg_StudyDlg::showTip(CString strTip)
{
AfxMessageBox(strTip);
}

struct ThreadData
{
void* _this;
CString strName;
};

DWORD WINAPI TestThreadProc(LPVOID lpParameter)
{
ThreadData* pThreadData = (ThreadData*)lpParameter;

CMfcDlg_StudyDlg* _this = (CMfcDlg_StudyDlg*)pThreadData->_this;
CString strTip = pThreadData->strName;

// 只要要调用里加上 _this来访问, 基本上也类似于成员函数
// 说白了, 成员函数也不过是编译器默认添加了一个this指针而已
_this->showTip(strTip);

delete lpParameter; // 如果创建线程成功, 这里也得把内存释放掉

// do other ...

return 0;
}

void CMfcDlg_StudyDlg::OnBnClickedOk()
{
// TODO: Add your control notification handler code here

ThreadData* pThreadData = new ThreadData;
pThreadData->_this = this;
pThreadData->strName = "test...";

DWORD dwThreadId;
HANDLE hThread = CreateThread(NULL, 1024 * 1024 * 20, TestThreadProc, pThreadData, 0, &dwThreadId);

if (hThread == NULL)
{
delete pThreadData;	// 记得创建线程不能成功, 把内存释放掉
AfxMessageBox(TEXT("Create Thread Failed.."));
}

//OnOK();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: