多线程(Barrier)

Barrier使多个任务能够通过多个阶段并行协作处理算法。

Barrier的所有公共和受保护成员都是线程安全的,可以从多个线程同时使用,Dispose除外,只有当Barrier上的所有其他操作完成后才能使用。

 

一组任务通过一系列阶段进行合作,其中组中的每个阶段都指示它已经在给定阶段抵达Barrier并等待所有其他阶段到达。相同的Barrier可以用于多个阶段。https://msdn.microsoft.com/en-us/library/system.threading.barrier(v=vs.110).aspx


using System;

using System.Threading;

using staticSystem.Console;

using staticSystem.Threading.Thread;

namespace barrierLearn

{

    class Program

    {

        static Barrier _barrier = newBarrier(2,b=>Console.WriteLine($"End of phase {b.CurrentPhaseNumber +1}"));//每一代运行完有一个回掉函数

        static void PlayMusic(stringname,string message,int secounds)

        {

            for (int i = 0; i < 3; i++)

            {

               WriteLine("------------------------------------");

               Sleep(TimeSpan.FromSeconds(secounds));A

                WriteLine($"{name} startsto {message}");

               Sleep(TimeSpan.FromSeconds(secounds));

                WriteLine($"{name}finishes to {message}");

                _barrier.SignalAndWait();

 

            }

        }

        static void Main(string[] args)

        {

            var t1 = newThread(()=>PlayMusic("The guitarist","play an amzingsolo",5));

            var t2 = newThread(()=>PlayMusic("The singer","sing his song",2));

            t1.Start();

            t2.Start();

        }

    }

}



运行结果:

------------------------------------
------------------------------------
The singer starts to sing his song
The singer finishes to sing his song
The guitarist starts to play an amzing solo
The guitarist finishes to play an amzing solo
End of phase 2
------------------------------------
------------------------------------
The singer starts to sing his song
The singer finishes to sing his song
The guitarist starts to play an amzing solo
The guitarist finishes to play an amzing solo
End of phase 3

猜你喜欢

转载自blog.csdn.net/u010676526/article/details/80001897