2013-12-22 8 views
2

나는 다음과 같은 코드를 실행하면 : I 출력이 볼MaxDegreeOfParallelism = 2는 3 개 스레드

public static double SumRootN(int root) 
    { 
     double result = 0; 
     for (int i = 1; i < 10000000; i++) 
     { 
      result += Math.Exp(Math.Log(i)/root); 
     } 
     return result; 
    } 

static void Main() 
{ 
    ParallelOptions options = new ParallelOptions(); 
    options.MaxDegreeOfParallelism = 2; // -1 is for unlimited. 1 is for sequential. 

    try 
    { 
     Parallel.For(
       0, 
       9, 
       options, 
       (i) => 
     { 
      var result = SumRootN(i); 
      Console.WriteLine("Thread={0}, root {0} : {1} ",Thread.CurrentThread.ManagedThreadId, i, result); 
     }); 
      ); 

    } 
    catch (AggregateException e) 
    { 
     Console.WriteLine("Parallel.For has thrown the following (unexpected) exception:\n{0}", e); 
    } 
} 

을 : enter image description here

3 개 스레드 ID가 여기에 있습니다,하지만 난 MaxDegreeOFParallelism 것을 지정한 단지 2. 왜 3 스레드가 2 대신에 작업을 수행합니까?

+0

http://stackoverflow.com/questions/9538452/what-does-maxdegreeofparallelism-do – christiandev

+0

나는 '스레드'에 관한 것이 아니라고 생각하며, 동시에 얼마나 많은 스레드가 있는지 생각합니다. 그래서 나는 스레드를 '재사용'하는 것을 보장하지 않을 것이라고 생각합니다. – Silvermind

+0

그래서 한 번에 2 개의 스레드 만 실행되며 이드는 관련이 없다고 말하는 것입니까? –

답변

4

견적 기본적으로 http://msdn.microsoft.com/en-us/library/system.threading.tasks.paralleloptions.maxdegreeofparallelism(v=vs.110).aspx

에서, 및 foreach는 너무 많은 동시 작업이 사용 방법 기본에서만 한계를 MaxDegreeOfParallelism을 변경, 기본 스케줄러가 제공하는 그러나 많은 스레드를 활용합니다.

번역 : 주어진 순간에 2 개의 스레드 만 실행되지만 스레드 풀에서 2 개 이상 (또는 더 적은) 2 개를 사용할 수 있습니다. 작업의 시작 부분에 다른 writeline을 사용하여이를 테스트 할 수 있습니다. 그러면 3 개의 스레드가 동시에 입력되지 않음을 알 수 있습니다.