C# 기술
[C#] 여러 개 Thread 사용 시 주의사항 (파라메터 사용 시)
bryan.oh
2021. 10. 30. 14:49
반응형
여러 개 Thread 사용 시 주의사항
(파라메터 주의)
For 문에서 여러 Thread 를 실행할 때
Thread 에 parameter 를 넘길때 주의할 점이 있습니다.
우선 코드를 보고 결과를 예상해 보세요.
using System;
using System.Collections.Generic;
using System.Threading;
namespace TestConsole
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
List<Thread> threadList = new List<Thread>();
for(int i=0; i < 100; i++)
{
Thread thread = new Thread(() => myThreadFunction(i));
threadList.Add(thread);
thread.Start();
}
foreach (Thread thread in threadList)
{
thread.Join();
}
Console.WriteLine("Done");
}
private static void myThreadFunction(int param)
{
Console.WriteLine("param = {0}", param);
}
}
}
0부터 99까지 돌면서 myThreadFunction에 그 값을 넘깁니다.
for(int i=0; i < 100; i++)
{
Thread thread = new Thread(() => myThreadFunction(i));
threadList.Add(thread);
thread.Start();
}
그리고 myThreadFunction 이라는 함수는 파라메터로 받은 숫자를 콘솔에 찍습니다.
0 부터 99 까지 순서없이 찍히겠죠?
라고 생각하셨으면 틀렸습니다.
실행해본 결과는
이렇습니다.
중복된 숫자가 많이 보이네요;;
위 코드를 아래와 같이 바꾸면 예상했던 결과가 나옵니다.
for(int i=0; i < 100; i++)
{
int index = i;
Thread thread = new Thread(() => myThreadFunction(index));
threadList.Add(thread);
thread.Start();
}
thread 라서 순서대로 나오지는 않지만 처음처럼 중복되는 오류는 발생하지 않습니다.
또는 ParameterizedThreadStart 를 사용합니다.
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
List<Thread> threadList = new List<Thread>();
for(int i=0; i < 100; i++)
{
int index = i;
//Thread thread = new Thread(() => myThreadFunction(index));
Thread thread = new Thread(new ParameterizedThreadStart(myThreadFunction)); // 이거 사용
threadList.Add(thread);
thread.Start(i); // start 에서 파라메터 넘기도록 수정
}
foreach (Thread thread in threadList)
{
thread.Join();
}
Console.WriteLine("Done");
}
public static void myThreadFunction(object param) // object type으로 수정
{
Console.WriteLine("param = {0}", param);
}
이 결과도, 중복없이 잘 실행됩니다.
ParameterizedThreadStart 또는 ThreadStart 참고
728x90
반응형