多线程实例4
此实例演示你的机器最多能创建多少个线程。此实例程序相当简单。
线程函数:
- volatile BOOL m_bRUN = TRUE; //表示是否能继续添加线程
- DWORD WINAPI ThreadProc(LPVOID lpParam)
- {
- while (m_bRUN)
- {
- Sleep(2000);
- }
- return 0;
- }
主线程函数:
- void CMthread4Dlg::OnStart()
- {
- // TODO: Add your control notification handler code here
- DWORD threadID;
- long nCount = 0;
- m_nCount = 0;
- UpdateData(FALSE);
- GetDlgItem(IDC_START)->EnableWindow(FALSE);
- while (m_bRUN)
- {
- if (CreateThread(NULL,0,ThreadProc,NULL,0,&threadID) == NULL)
- {
- m_bRUN = FALSE;
- break;
- }
- else
- {
- nCount++;
- }
- }
- m_nCount = nCount;
- UpdateData(FALSE);
- Sleep(5000);
- GetDlgItem(IDC_START)->EnableWindow(TRUE);
- m_bRUN = TRUE;
- }
说明:当m_bRUN一直为TRUE的时候,程序一直创建线程,直至创建的线程到达最大值。
执行结果:
多线程实例五
此实例演示,创建了一个线程类,线程类继承自CWinThread。主线程通过AfxBeginThread函数调用线程类。
主线程调用线程类:
- void CMthread6Dlg::OnUiThread()
- {
- // TODO: Add your control notification handler code here
- CWinThread *pThread = AfxBeginThread(RUNTIME_CLASS(CUIThread));
- }
头文件中类定义:
class CMthread6Dlg : public CDialog
线程类:
- // UIThread.cpp : implementation file
- //
- #include "stdafx.h"
- #include "Mthread6.h"
- #include "UIThread.h"
- #ifdef _DEBUG
- #define new DEBUG_NEW
- #undef THIS_FILE
- static char THIS_FILE[] = __FILE__;
- #endif
- /
- // CUIThread
- IMPLEMENT_DYNCREATE(CUIThread, CWinThread)
- CUIThread::CUIThread()
- {
- }
- CUIThread::~CUIThread()
- {
- }
- BOOL CUIThread::InitInstance()
- {
- // TODO: perform and per-thread initialization here
- m_dlg.Create(IDD_UITHREADDLG);
- m_dlg.ShowWindow(SW_SHOW);
- m_pMainWnd = &m_dlg;
- return TRUE;
- }
- int CUIThread::ExitInstance()
- {
- // TODO: perform any per-thread cleanup here
- m_dlg.DestroyWindow();
- return CWinThread::ExitInstance();
- }
- BEGIN_MESSAGE_MAP(CUIThread, CWinThread)
- //{{AFX_MSG_MAP(CUIThread)
- // NOTE - the ClassWizard will add and remove mapping macros here.
- //}}AFX_MSG_MAP
- END_MESSAGE_MAP()
- /
- // CUIThread message handlers
InitInstance函数中,创建了一个对话框。
运行结果:
源代码下载地址: