⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 threaddata.cpp

📁 Visual_C++[1].NET_Bible1 Visual_C++宝典书中的全部源码
💻 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 + -