本文以四个demo为例,对MFC的多线程进行学习。学习的过程中写了四个demo,将其做成笔记,发布在csdn上面。
mfc多线程demo1
cpp
volatile BOOL m_bRun;
CEdit* edit;
void ThreadFunc(){
CTime time;
CString strTime;
m_bRun = true;
while(m_bRun){
time = CTime::GetCurrentTime();
strTime = time.Format("%H:%M:%S");
//::SetDlgItemText(AfxGetMainWnd()->m_hWnd,IDC_EDIT1,strTime);
edit->SetWindowText(strTime);
Sleep(1000);
}
}
void CmfcMultiThread02Dlg::OnBnClickedButton1()
{
// 作死卡死
edit = &m_list;
hThread = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ThreadFunc,NULL,0,&ThreadID);
btn1.EnableWindow(FALSE);
btn2.EnableWindow(TRUE);
}
void CmfcMultiThread02Dlg::OnBnClickedButton2()
{
// TODO: 在此添加控件通知处理程序代码
m_bRun = FALSE;
btn1.EnableWindow(TRUE);
btn2.EnableWindow(FALSE);
}
mfc多线程demo2
cpp
volatile BOOL m_bRun;
CEdit* edit;
void ThreadFunc(int n){
int i ;
for( i = 0;i< n;i++){
Sleep(1000);
}
}
void CmfcMultiThread02Dlg::OnBnClickedButton1()
{
// 作死卡死
UpdateData(TRUE);
int n=2;
hThread=CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ThreadFunc, (VOID*)n, 0, &ThreadID);
btn1.EnableWindow(FALSE);
WaitForSingleObject(hThread,INFINITE);
btn2.EnableWindow(TRUE);
}
void CmfcMultiThread02Dlg::OnBnClickedButton2()
{
// TODO: 在此添加控件通知处理程序代码
m_bRun = FALSE;
btn1.EnableWindow(TRUE);
btn2.EnableWindow(FALSE);
}
mfc多线程demo3
cpp
struct threadInfo{
UINT nMilliSecond;
CProgressCtrl* pctrlProgress;
};
threadInfo info;
UINT ThreadFunc(LPVOID lpParam){
threadInfo* pInfo = (threadInfo*)lpParam;
for(int i = 0;i < 100;i++){
int nTemp = pInfo->nMilliSecond;
pInfo->pctrlProgress->SetPos(i);
Sleep(nTemp);
}
return 0;
}
void CmfcMultiThread02Dlg::OnBnClickedButton1()
{
// 作死卡死
UpdateData(TRUE);
info.nMilliSecond = 50;
info.pctrlProgress = &progress1;
hThread = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ThreadFunc, &info, 0, &ThreadID);
}
mfc创建线程数统计demo4
cpp
volatile BOOL m_bRunFlag = TRUE;
DWORD WINAPI threadFunc(LPVOID threadNum){
while(m_bRunFlag){
Sleep(3000);
}
return 0;
}
void CmfcMultiThread02Dlg::OnBnClickedButton1()
{
// 作死卡死
DWORD threadID;
btn1.EnableWindow(FALSE);
long nCount = 0;
while(m_bRunFlag){
if(CreateThread(NULL,0,threadFunc,NULL,0,&threadID) == NULL){
m_bRunFlag = false;
break;
}else{
nCount++;
}
}
UpdateData(FALSE);
Sleep(5000);
btn1.EnableWindow(TRUE);
CString tempPort;
tempPort.Format(_T("%d"), nCount );
m_list.SetWindowText(tempPort);
m_bRunFlag = TRUE;
}
mfc创建线程进度条
cpp
struct threadInfo{
UINT nMillSecond;
CProgressCtrl* pctrlProgress;
}info;
UINT ThreadFunc(LPVOID lpParam){
threadInfo* pInfo = (threadInfo*) lpParam;
for(int i = 0;i< 100;i++){
int nTemp = pInfo->nMillSecond;
pInfo->pctrlProgress->SetPos(i);
Sleep(nTemp);
}
return 0;
}
void CmfcMultiThread02Dlg::OnBnClickedButton1()
{
// 作死卡死
UpdateData(TRUE);
info.nMillSecond = 10;
info.pctrlProgress = &progress1;
pThread = AfxBeginThread(ThreadFunc,&info);
}