PROJECT NAME : multithread
In multithreadView.cpp
#include "stdafx.h"
#include "multithread.h"
#include "multithreadDoc.h"
#include "multithreadView.h"
#include "diathrd.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
// CMultithreadView
IMPLEMENT_DYNCREATE(CMultithreadView, CView)
BEGIN_MESSAGE_MAP(CMultithreadView, CView)
//{{AFX_MSG_MAP(CMultithreadView)
//}}AFX_MSG_MAP
// Standard printing commands
ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW,
CView::OnFilePrintPreview)
END_MESSAGE_MAP()
// CMultithreadView construction/destruction
CMultithreadView::CMultithreadView()
{ }
CMultithreadView::~CMultithreadView()
{ }
BOOL CMultithreadView::PreCreateWindow(CREATESTRUCT& cs)
{
return CView::PreCreateWindow(cs);
}
// CMultithreadView drawing
void CMultithreadView::OnDraw(CDC* pDC)
{
CMultithreadDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
Cdiathrd dlg;
dlg.DoModal();
}
// CMultithreadView printing
BOOL CMultithreadView::OnPreparePrinting(CPrintInfo* pInfo)
{
return DoPreparePrinting(pInfo);
}
// CMultithreadView diagnostics
#ifdef _DEBUG
void CMultithreadView::AssertValid() const
{
CView::AssertValid();
}
void CMultithreadView::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
CMultithreadDoc* CMultithreadView::GetDocument() // non-debug
version is inline
{
ASSERT(m_pDocument-
>IsKindOf(RUNTIME_CLASS(CMultithreadDoc)));
return (CMultithreadDoc*)m_pDocument;
}
#endif //_DEBUG
In diathrd.cpp
#include "stdafx.h"
#include "multithread.h"
#include "diathrd.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
// Cdiathrd dialog
Cdiathrd::Cdiathrd(CWnd* pParent /*=NULL*/)
: CDialog(Cdiathrd::IDD, pParent)
{
//{{AFX_DATA_INIT(Cdiathrd)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
}
void Cdiathrd::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(Cdiathrd)
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(Cdiathrd, CDialog)
//{{AFX_MSG_MAP(Cdiathrd)
ON_BN_CLICKED(IDC_BUTTON1, OnButton1)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
// Cdiathrd message handlers
int g_var=0;
UINT ComputeThreadProc(LPVOID pParam)
{
CString str;
int j;
for(j=1;j<=5;j++)
{
::InterlockedIncrement((long*)&g_var);
str.Format("Child g_var = %d",g_var);
CWnd w1;
w1.MessageBox(str);
try
{
Sleep(1000);
}
catch(CException e)
{}
}
return 0;
}
void Cdiathrd::OnButton1()
{
CString str1;
int I , g_var=0;
CWinThread*
pThread=AfxBeginThread(ComputeThreadProc,GetSafeHwnd(),THREAD
_PRIORITY_NORMAL);
for(i=1;i<=5;i++)
{
::InterlockedIncrement((long*)&g_var);
str1.Format("Main g_var = %d",g_var);
MessageBox(str1);
try
{
Sleep(1000);
}
catch(CException e)
{}
}
}
OUTPUT