#include "afxmt.h" //线程函数 int data1=0; int data2=0; int data3=0; int data4=0; bool isTermiateThread=false;//结束线程使用 CCriticalSection CriticalSection;//使用线程互斥 UINT Thread_Add(LPVOID param)//加法线程函数 { isTermiateThread=false; while (++data1) { if (isTermiateThread)return 0; CString str; str.Format("%d",data1); CWnd *pWnd=AfxGetApp()->GetMainWnd(); pWnd->GetDlgItem(IDC_EDIT1)->SetWindowText(str); ::Sleep(10); } return 0; } UINT Thread_Sub(LPVOID param)//减法线程函数 { isTermiateThread=false; while (--data2) { if (isTermiateThread)return 0; CString str; str.Format("%d",data2); CWnd *pWnd=AfxGetApp()->GetMainWnd(); pWnd->GetDlgItem(IDC_EDIT2)->SetWindowText(str); ::Sleep(10); } return 0; } UINT Thread_Mutex1(LPVOID param) { isTermiateThread=false; while (1) { CriticalSection.Lock(); do { if (isTermiateThread)//当线程结束时此处需要解锁,否则再次启动时进程时不能访问资源 { CriticalSection.Unlock(); return 0; } CString str; str.Format("%d",data3++); CWnd *pWnd=AfxGetApp()->GetMainWnd(); pWnd->GetDlgItem(IDC_EDIT3)->SetWindowText(str); ::Sleep(100); }while (data3<100); CriticalSection.Unlock(); } return 0; } UINT Thread_Mutex2(LPVOID param) { isTermiateThread=false; while (1) { CriticalSection.Lock(); do { if (isTermiateThread)//当线程结束时此处需要解锁,否则再次启动时进程时不能访问资源 { CriticalSection.Unlock(); return 0; } CString str; str.Format("%d",data3--); CWnd *pWnd=AfxGetApp()->GetMainWnd(); pWnd->GetDlgItem(IDC_EDIT3)->SetWindowText(str); ::Sleep(100); }while (data3>0); CriticalSection.Unlock(); } return 0; } UINT Thread_NoMutex1(LPVOID param) { isTermiateThread=false; while (1) { do { if (isTermiateThread) return 0; CString str; str.Format("%d",data4++); CWnd *pWnd=AfxGetApp()->GetMainWnd(); pWnd->GetDlgItem(IDC_EDIT4)->SetWindowText(str); ::Sleep(10); }while (data4<100); } return 0; } UINT Thread_NoMutex2(LPVOID param) { isTermiateThread=false; while (1) { do { if (isTermiateThread)return 0; CString str; str.Format("%d",data4--); CWnd *pWnd=AfxGetApp()->GetMainWnd(); pWnd->GetDlgItem(IDC_EDIT4)->SetWindowText(str); ::Sleep(10); }while (data4>0); } return 0; } void CThreadDlg::OnBeginThread() //创建两个独立的线程 { // TODO: Add your control notification handler code here HWND hWnd=GetSafeHwnd(); AfxBeginThread(Thread_Add,hWnd); AfxBeginThread(Thread_Sub,hWnd); } void CThreadDlg::OnThreadMutex() //创建互斥线程 { // TODO: Add your control notification handler code here HWND hWnd=GetSafeHwnd(); AfxBeginThread(Thread_Mutex1,hWnd); AfxBeginThread(Thread_Mutex2,hWnd); } void CThreadDlg::OnNoThreadMutex() //创建两个互斥但相互受影响的线程 { // TODO: Add your control notification handler code here HWND hWnd=GetSafeHwnd(); AfxBeginThread(Thread_NoMutex1,hWnd); AfxBeginThread(Thread_NoMutex2,hWnd); } void CThreadDlg::OnEndThread() //结束线程 { // TODO: Add your control notification handler code here isTermiateThread=1; }