您的位置:首页 > 编程语言 > C语言/C++

c++多线程(三)

2013-11-10 22:28 253 查看
多线程实例4

此实例演示你的机器最多能创建多少个线程。此实例程序相当简单。

线程函数:

[cpp] view
plaincopy

volatile BOOL m_bRUN = TRUE; //表示是否能继续添加线程

DWORD WINAPI ThreadProc(LPVOID lpParam)

{

while (m_bRUN)

{

Sleep(2000);

}

return 0;

}

主线程函数:

[cpp] view
plaincopy

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函数调用线程类。

主线程调用线程类:

[cpp] view
plaincopy

void CMthread6Dlg::OnUiThread()

{

// TODO: Add your control notification handler code here

CWinThread *pThread = AfxBeginThread(RUNTIME_CLASS(CUIThread));

}

线程类:

头文件中类定义:

class CMthread6Dlg : public CDialog

线程类:

[cpp] view
plaincopy

// 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: