c++多线程(三)

多线程实例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
从上边的代码中,自建的线程类CUIThread重写了CWinThread类的InitInstance和ExitInstance函数

  InitInstance函数中,创建了一个对话框。

   运行结果:

   



源代码下载地址:

    http://download.csdn.net/detail/richerg85/4218429

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值