2014-07-26 3 views
2

C#에서 사용되는 Barrier 클래스에 대해 이해합니다. 그러나 아래 코드에서 SignalAndWait()이 두 번 호출 된 이유를 이해할 수 없습니까? 과제에 대한 호출이 충분하지 않습니까? 이 코드는 기본적으로 세 친구 (또는 할일)가 A에서 B, B에서 C로 여행하는 상황을 모델링하고 일부는 C로 가지 않고 B에서 A로 돌아갑니다. 도와주세요. 그건 그렇고,이 코드는 책에서 나온 것입니다 : MCSD Certification Exam Toolkit (70-483). 고마워요!배리어 클래스 C#

static void Main(string[] args) 
{ 
    var participants = 5; 
    Barrier barrier = new Barrier(participants + 1, 
     b => { // This method is only called when all the paricipants arrived. 
      Console.WriteLine("{0} paricipants are at rendez-vous point {1}.", 
       b.ParticipantCount -1, // We substract the main thread. 
       b.CurrentPhaseNumber); 
     }); 
    for (int i = 0; i < participants; i++) 
    { 
     var localCopy = i; 
     Task.Run(() => { 
      Console.WriteLine("Task {0} left point A!", localCopy); 
      Thread.Sleep(1000 * localCopy + 1); // Do some "work" 
      if (localCopy % 2 == 0) { 
       Console.WriteLine("Task {0} arrived at point B!", localCopy); 
       barrier.SignalAndWait(); 
      } 
      else 
      { 
       Console.WriteLine("Task {0} changed its mind and went back!", localCopy); 
       barrier.RemoveParticipant(); 
       return; 
      } 
      Thread.Sleep(1000 * (participants - localCopy)); // Do some "morework" 
      Console.WriteLine("Task {0} arrived at point C!", localCopy); 
      barrier.SignalAndWait(); 
     }); 
    } 

    Console.WriteLine("Main thread is waiting for {0} tasks!", 
    barrier.ParticipantCount - 1); 
    barrier.SignalAndWait(); // Waiting at the first phase 
    barrier.SignalAndWait(); // Waiting at the second phase 
    Console.WriteLine("Main thread is done!"); 
} 

답변

2

또한 Console.WriteLine("{0} paricipants are at rendez-vous point {1}.",...) 행이 두 번 실행됩니다.

B와 C 모두에서 단일 장애 인스턴스가 사용됩니다. (나머지) 작업자는 SignalAndWait()을 호출하여 B와 C 모두에 도달 했으므로 호출을 두 번 호출합니다.

다운 옷을 입고 코드 :

if (localCopy % 2 == 0) 
    { 
     ... 
     barrier.SignalAndWait();  // arrival at B 
    } 
    else 
    { 
     ... 
     barrier.RemoveParticipant(); // return to A 
     return; 
    } 
    ... 
    barrier.SignalAndWait();   // arrival at C 
+0

감사 헹크. 제 질문은 왜 Main 메서드에서 SignalAndWait을 두 번 호출해야합니까? – user3509153

+0

코드에서 주 스레드 또한 '참가자'임을 알 수 있습니다. 자동으로 A와 B 상태로 이동합니다. 그것은 약간의 트릭입니다. 메인 쓰레드가 나머지 쓰레드를 기다리는 데 필요한 다른 구조가 필요하지 않을 것입니다. –