📄 threaddata.cpp
字号:
#include "stdafx.h"
#using <mscorlib.dll>
#include <tchar.h>
#include <math.h>
using namespace System;
using namespace System::Threading;
__gc class CWorkerThread
{
public:
CWorkerThread(int iThreadId, int nTasksToPerform);
public:
void Start();
protected:
void ThreadFunction();
protected:
Thread* m_pThread;
protected:
int m_iThreadId;
int m_nTasksToPerform;
};
CWorkerThread::CWorkerThread(int iThreadId, int nTasksToPerform)
: m_iThreadId(iThreadId), m_nTasksToPerform(nTasksToPerform)
{
// Create thread
m_pThread = new Thread(new ThreadStart(this, &CWorkerThread::ThreadFunction));
}
void CWorkerThread::Start()
{
// Start thread
if (m_pThread)
{
m_pThread->Start();
}
}
void CWorkerThread::ThreadFunction()
{
Console::WriteLine("[CWorkerThread::ThreadFunction] Thread {0} has initialized to do {1} tasks",
__box(this->m_iThreadId),
__box(this->m_nTasksToPerform));
for (int i = 0; i < m_nTasksToPerform; i++)
{
Console::WriteLine("[CWorkerThread::ThreadFunction] Thread {0} Performing task {1} of {2}",
__box(m_iThreadId),
__box(i+1),
__box(m_nTasksToPerform));
Thread::Sleep(500);
}
Console::WriteLine("[CWorkerThread::ThreadFunction] Thread {0} finished working",
__box(m_iThreadId));
}
int _tmain(void)
{
CWorkerThread* pWorkerThread;
for (int i = 0; i < 2; i++)
{
Console::WriteLine("[_tmain] Starting thread {0}",
__box(i));
System::Random* pRandom = new System::Random();
pWorkerThread = new CWorkerThread((i+1),
(int)Math::Round(pRandom->NextDouble()*10));
if (i == 0) pWorkerThread = new CWorkerThread((i+1), 3);
else pWorkerThread = new CWorkerThread((i+1), 7);
pWorkerThread->Start();
}
Console::WriteLine("[_tmain] Finished creating threads");
Console::ReadLine();
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -