Barrier

Shapley發表於2024-10-23
 internal class Program
 {
     static bool isOutput = true;
     static int index1 = 0;
     static int index2 = 100;
     static Barrier barrier = new Barrier(2, b =>
     {
         if (index1 == index2)
         {
             Console.WriteLine($"index1與index2相同,比對結束。");
             isOutput = false;
         }
         else
         {
             Console.WriteLine($"index1與index2不同!~");
         }
     });
     static void Main(string[] args)
     {
         var t = Task.Run(() => {
             while (isOutput)
             {
                 index1 = index1 + 2;
                 Console.WriteLine("index1:" + index1);
                 barrier.SignalAndWait();
             }
         });
         var t2 = Task.Run(() =>{
             while (isOutput)
             {
                 index2++;
                 Console.WriteLine("index2:" + index2);
                 barrier.SignalAndWait();
             }
         });

         Console.ReadLine();
     }
 }