다음을 통해 공유


장벽(.NET Framework)

장벽은 알고리즘에서 여러 스레드가 동시에 단계별로 작동하도록 하는 사용자 정의 동기화 기본 형식(또는 참가자)입니다. 각 참가자는 코드의 장벽 지점에 도달할 때까지 실행됩니다. 장벽은 한 작업 단계의 끝을 나타냅니다. 참가자가 장벽에 도달하면 모든 참가자가 동일한 장벽에 도달할 때까지 차단됩니다. 모든 참가자가 장벽에 도달한 후에는 선택적으로 단계 후 작업을 호출할 수 있습니다. 이 단계 후 작업은 다른 스레드가 모두 차단된 상태에서 특정 스레드의 작업을 수행하는 데 사용할 수 있습니다. 작업이 실행된 후에는 모든 참가자의 차단이 해제됩니다.

다음 코드 조각에서는 기본 장벽 패턴을 보여 줍니다.


' Create the Barrier object, and supply a post-phase delegate 
' to be invoked at the end of each phase.
Dim barrier = New Barrier(2, Sub(bar)
                                 ' Examine results from all threads, determine 
                                 ' whether to continue, create inputs for next phase, etc. 
                                 If (someCondition) Then
                                     success = True
                                 End If
                             End Sub)



' Define the work that each thread will perform. (Threads do not
' have to all execute the same method.)
Sub CrunchNumbers(ByVal partitionNum As Integer)

    ' Up to System.Int64.MaxValue phases are supported. We assume
    ' in this code that the problem will be solved before that.
    While (success = False)

        ' Begin phase:
        ' Process data here on each thread, and optionally
        ' store results, for example:
        results(partitionNum) = ProcessData(myData(partitionNum))

        ' End phase:
        ' After all threads arrive,post-phase delegate
        ' is invoked, then threads are unblocked. Overloads
        ' accept a timeout value and/or CancellationToken.
        barrier.SignalAndWait()
    End While
End Sub

' Perform n tasks to run in in parallel. For simplicity
' all threads execute the same method in this example.
Shared Sub Main()

    Dim app = New BarrierDemo()
    Dim t1 = New Thread(Sub() app.CrunchNumbers(0))
    Dim t2 = New Thread(Sub() app.CrunchNumbers(1))
    t1.Start()
    t2.Start()
End Sub

 // Create the Barrier object, and supply a post-phase delegate 
 // to be invoked at the end of each phase.
 Barrier barrier = new Barrier(2, (bar) => 
     {
         // Examine results from all threads, determine 
         // whether to continue, create inputs for next phase, etc. 
         if (someCondition)
             success = true;
     });       


 // Define the work that each thread will perform. (Threads do not
 // have to all execute the same method.)
 void CrunchNumbers(int partitionNum)
 {
     // Up to System.Int64.MaxValue phases are supported. We assume
     // in this code that the problem will be solved before that.
     while (success == false)
     {
         // Begin phase:
         // Process data here on each thread, and optionally
         // store results, for example:
         results[partitionNum] = ProcessData(data[partitionNum]);

         // End phase:
         // After all threads arrive,post-phase delegate
         // is invoked, then threads are unblocked. Overloads
         // accept a timeout value and/or CancellationToken.
         barrier.SignalAndWait();
     }
 }

 // Perform n tasks to run in in parallel. For simplicity
// all threads execute the same method in this example.
 static void Main()
 {
     var app = new BarrierDemo();
     Thread t1 = new Thread(() => app.CrunchNumbers(0));
     Thread t2 = new Thread(() => app.CrunchNumbers(1));
     t1.Start();
     t2.Start();

 }

전체 예제는 방법: 동시 작업을 배리어와 동기화를 참조하십시오.

참가자 추가 및 제거

Barrier를 만들 때 참가자 수를 지정합니다. 또한 언제든지 동적으로 참가자를 추가하거나 제거할 수 있습니다. 예를 들어 한 참가자 해당 문제 부분을 해결하면 결과를 저장하고, 해당 스레드에서 실행을 중지하고, RemoveParticipant를 호출하여 장벽의 참가자 수를 줄일 수 있습니다. AddParticipant를 호출하여 참가자를 추가하면 반환 값에 의해 새 참가자의 작업을 초기화하는 데 유용할 수 있는 현재 단계 번호가 지정됩니다.

손상된 장벽

한 참가자가 장벽에 도달하는 데 실패하면 교착 상태가 발생할 수 있습니다. 이러한 교착 상태를 방지하려면 SignalAndWait 메서드의 오버로드를 사용하여 제한 시간과 취소 토큰을 지정합니다. 이러한 오버로드는 모든 참가자가 다음 단계로 이동하기 전에 확인할 수 있는 부울 값을 반환합니다.

단계 후 예외

단계 후 대리자가 예외를 throw하면 해당 대리자는 BarrierPostPhaseException 개체에 래핑되고, 여기서 다시 모든 참가자에 전파됩니다.

장벽과 ContinueWhenAll

장벽은 스레드가 루프에서 여러 단계를 수행할 때 특히 유용합니다. 코드에 한 단계 또는 두 단계의 작업만 필요한 경우 다음과 같은 암시적 조인과 함께 System.Threading.Tasks.Task 개체를 사용할지 여부를 고려해야 합니다.

자세한 내용은 방법: 연속 작업을 사용하여 여러 작업 연결을 참조하십시오.

참고 항목

작업

방법: 동시 작업을 배리어와 동기화

기타 리소스

스레딩 개체 및 기능