Delegateを使ってマルチスレッドをおこなうサンプルコード

forループしながら数字を出力し続ける関数を二つ作り、それぞれ別スレッドを立てて実行。
しかし無駄なステップが多いんじゃないかなこの作業・・・


1.ThreadStartに関数を登録(デリゲート化)
2.ThreadにThreadStart型の関数を登録
3.Thread型の関数->Startでスレッド開始


#引数と戻り値これどうやって使うんだろ
#ThreadStartはvoid Function(void)だから、もしかして使えない?

ソースは続きを読むからどうぞ:

// Delegateでマルチスレッドを行うサンプル

#include "stdafx.h"

using namespace System;

//Function1, Function2は同じもの
//0〜99の値をforループで順番に出力し続ける関数
void Function1(void)
{
	int n = 0;

	for(int i = 0; i < 100; i++){
		Console::WriteLine("Function1: {0}", n);
		n++;

		System::Threading::Thread::Sleep(100);
	}
}

void Function2(void)
{
	int n = 0;

	for(int i = 0; i < 100; i++){
		Console::WriteLine("Function2: {0}", n);
		n++;
		System::Threading::Thread::Sleep(100);
	}
}


int main(array<System::String ^> ^args)
{
	//ThreadStartのオブジェクトoDelegateFunction1に、Function1を登録する
	System::Threading::ThreadStart^ oDelegateFunction1 = gcnew System::Threading::ThreadStart(&Function1);

	//ThreadのオブジェクトnewThread1に、Function1の登録されたoDelegateFunction1を登録する
	System::Threading::Thread^ newThread1 = gcnew System::Threading::Thread(oDelegateFunction1);

	//newThread1内のStartを呼び出すことで、Function1が別スレッドとして稼動する
	newThread1->Start();

	//Function2についても同様の手順
	System::Threading::ThreadStart^ oDelegateFunction2 = gcnew System::Threading::ThreadStart(&Function2);
	System::Threading::Thread^ newThread2 = gcnew System::Threading::Thread(oDelegateFunction2);
	newThread2->Start();

	//メイン関数自体はここで終了
	Console::WriteLine(L"メインスレッドはここで終了です");

    return 0;
}