Barrier类的使用,可作为多线程间的信号量

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace BarrierDemo { class Program { static void Main(string[] args) { var t1 = new Thread(() => PlayGame("the player", "on line", 5)); var t2 = new Thread(() => PlayGame("the game", "opening", 2)); t1.Start(); t2.Start(); Console.ReadKey(); }static Barrier _barrier = new Barrier(2, b => Console.WriteLine($"End of phase{b.CurrentPhaseNumber + 1}")); static void PlayGame(string name, string message, int seconds) { for(int i = 1; i < 3; i++) { Console.WriteLine("---------------------------------------------"); Thread.Sleep(TimeSpan.FromSeconds(seconds)); Console.WriteLine($"{name} starts to {message}"); Thread.Sleep(TimeSpan.FromSeconds(seconds)); Console.WriteLine($"{name} finishes to {message}"); _barrier.SignalAndWait(); } } } }

【Barrier类的使用,可作为多线程间的信号量】当设定了_barrier实例中参与线程的数量,其中任何一个线程发出了信号_barrier.SignalAndWait()并开始等待,直到剩下的所有线程都发出信号,才开始往下走。可以理解为:一辆车在等人,人齐了就走,人不齐就所有人都等着。

    推荐阅读