如何:使用屏障同步處理並行作業
下列範例示範如何使用 Barrier 同步處理並行工作。
範例
下列程式的目的是計算兩個執行緒需要多少反覆項目 (或階段),才能讓兩者透過使用隨機演算法重新排列文字,來找到其另外一半的解決方案。 在各執行緒打散其文字之後,屏障的後續階段作業會比較兩個結果,以查看完整的句子是否已以正確的文字順序顯示。
//#define TRACE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace BarrierSimple
{
class Program
{
static string[] words1 = new string[] { "brown", "jumps", "the", "fox", "quick"};
static string[] words2 = new string[] { "dog", "lazy","the","over"};
static string solution = "the quick brown fox jumps over the lazy dog.";
static bool success = false;
static Barrier barrier = new Barrier(2, (b) =>
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < words1.Length; i++)
{
sb.Append(words1[i]);
sb.Append(" ");
}
for (int i = 0; i < words2.Length; i++)
{
sb.Append(words2[i]);
if(i < words2.Length - 1)
sb.Append(" ");
}
sb.Append(".");
#if TRACE
System.Diagnostics.Trace.WriteLine(sb.ToString());
#endif
Console.CursorLeft = 0;
Console.Write("Current phase: {0}", barrier.CurrentPhaseNumber);
if (String.CompareOrdinal(solution, sb.ToString()) == 0)
{
success = true;
Console.WriteLine("\r\nThe solution was found in {0} attempts", barrier.CurrentPhaseNumber);
}
});
static void Main(string[] args)
{
Thread t1 = new Thread(() => Solve(words1));
Thread t2 = new Thread(() => Solve(words2));
t1.Start();
t2.Start();
// Keep the console window open.
Console.ReadLine();
}
// Use Knuth-Fisher-Yates shuffle to randomly reorder each array.
// For simplicity, we require that both wordArrays be solved in the same phase.
// Success of right or left side only is not stored and does not count.
static void Solve(string[] wordArray)
{
while(success == false)
{
Random random = new Random();
for (int i = wordArray.Length - 1; i > 0; i--)
{
int swapIndex = random.Next(i + 1);
string temp = wordArray[i];
wordArray[i] = wordArray[swapIndex];
wordArray[swapIndex] = temp;
}
// We need to stop here to examine results
// of all thread activity. This is done in the post-phase
// delegate that is defined in the Barrier constructor.
barrier.SignalAndWait();
}
}
}
}
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Threading
Imports System.Threading.Tasks
Class Program
Shared words1() = New String() {"brown", "jumps", "the", "fox", "quick"}
Shared words2() = New String() {"dog", "lazy", "the", "over"}
Shared solution = "the quick brown fox jumps over the lazy dog."
Shared success = False
Shared barrier = New Barrier(2, Sub(b)
Dim sb = New StringBuilder()
For i As Integer = 0 To words1.Length - 1
sb.Append(words1(i))
sb.Append(" ")
Next
For i As Integer = 0 To words2.Length - 1
sb.Append(words2(i))
If (i < words2.Length - 1) Then
sb.Append(" ")
End If
Next
sb.Append(".")
System.Diagnostics.Trace.WriteLine(sb.ToString())
Console.CursorLeft = 0
Console.Write("Current phase: {0}", barrier.CurrentPhaseNumber)
If (String.CompareOrdinal(solution, sb.ToString()) = 0) Then
success = True
Console.WriteLine()
Console.WriteLine("The solution was found in {0} attempts", barrier.CurrentPhaseNumber)
End If
End Sub)
Shared Sub Main()
Dim t1 = New Thread(Sub() Solve(words1))
Dim t2 = New Thread(Sub() Solve(words2))
t1.Start()
t2.Start()
' Keep the console window open.
Console.ReadLine()
End Sub
' Use Knuth-Fisher-Yates shuffle to randomly reorder each array.
' For simplicity, we require that both wordArrays be solved in the same phase.
' Success of right or left side only is not stored and does not count.
Shared Sub Solve(ByVal wordArray As String())
While success = False
Dim rand = New Random()
For i As Integer = 0 To wordArray.Length - 1
Dim swapIndex As Integer = rand.Next(i + 1)
Dim temp As String = wordArray(i)
wordArray(i) = wordArray(swapIndex)
wordArray(swapIndex) = temp
Next
' We need to stop here to examine results
' of all thread activity. This is done in the post-phase
' delegate that is defined in the Barrier constructor.
barrier.SignalAndWait()
End While
End Sub
End Class
Barrier 是一種物件,可防止平行作業中的個別工作繼續執行,直到所有的工作都到達屏障為止。 當階段中發生平行作業,且各階段要求在工作之間進行同步處理時,它會很有用。 在此範例中,作業有兩個階段。 在第一個階段中,每個工作都會使用資料填入其緩衝區區段。 當每個工作完成填入其區段時,工作會向屏障發出訊號,告知它已準備好繼續進行,然後等候。 當所有的工作都已向屏障發出訊號,就會將工作解除封鎖,並開始第二階段。 屏障是必要的,因為第二階段要求每個工作都擁有此點已產生之所有資料的存取權。 若沒有屏障,第一個要完成的工作可能會嘗試從其他工作尚未填入的緩衝區讀取。 您可以此種方式同步處理任何數目的階段。