【问题标题】:Barrier class c#屏障类 c#
【发布时间】:2014-09-18 11:02:07
【问题描述】:

我确实了解 C# 中使用的 Barrier 类。但是,在下面的代码中,我不明白为什么 SignalAndWait() 被调用了两次?任务中的调用还不够吗?该代码基本上模拟了三个朋友(或任务)从 A 到 B、B 到 C 以及一些从 B 回到 A 而没有去 C 的情况。 请帮帮我。顺便说一句,这段代码来自书中:MCSD Certification Exam Toolkit(70-483)。非常感谢!

static void Main(string[] args) 
{
    var participants = 5;
    Barrier barrier = new Barrier(participants + 1,
        b => { // This method is only called when all the paricipants arrived.
            Console.WriteLine("{0} paricipants are at rendez-vous point {1}.",
                b.ParticipantCount -1, // We substract the main thread.
                b.CurrentPhaseNumber);
        });
    for (int i = 0; i < participants; i++) 
    {
        var localCopy = i;
        Task.Run(() => {
            Console.WriteLine("Task {0} left point A!", localCopy);
            Thread.Sleep(1000 * localCopy + 1); // Do some "work"
            if (localCopy % 2 == 0) {
                Console.WriteLine("Task {0} arrived at point B!", localCopy);
                barrier.SignalAndWait();
            }
            else 
            {
                Console.WriteLine("Task {0} changed its mind and went back!", localCopy);
                barrier.RemoveParticipant();
                return;
            }
            Thread.Sleep(1000 * (participants - localCopy)); // Do some "morework"
            Console.WriteLine("Task {0} arrived at point C!", localCopy);
            barrier.SignalAndWait(); 
        });
    }

    Console.WriteLine("Main thread is waiting for {0} tasks!",
    barrier.ParticipantCount - 1);
    barrier.SignalAndWait(); // Waiting at the first phase
    barrier.SignalAndWait(); // Waiting at the second phase
    Console.WriteLine("Main thread is done!");
}

【问题讨论】:

    标签: c# multithreading barrier


    【解决方案1】:

    您还会看到Console.WriteLine("{0} paricipants are at rendez-vous point {1}.",...) 行执行了两次。

    单个 Barrier 实例用于在 B 和 C 会合。(剩余的)任务调用 SignalAndWait() 来标记它们同时到达 B 和 C,因此是两个调用。

    简化代码:

       if (localCopy % 2 == 0) 
       {
            ...
            barrier.SignalAndWait();       // arrival at B
        }
        else 
        {
            ...
            barrier.RemoveParticipant();   // return to A
            return;
        }
        ...
        barrier.SignalAndWait();           // arrival at C
    

    【讨论】:

    • 谢谢亨克。我的问题是,为什么 Main 方法中有两次 SignalAndWait 调用?
    • 您可以从代码中看出主线程也是一个“参与者”。它默默地移动到那里的状态 A 和 B。这是一个小技巧,如果没有它,您将需要其他构造来使主线程等待其余部分。
    猜你喜欢
    • 2011-01-04
    • 2018-08-25
    • 2011-10-12
    • 2013-07-27
    • 2018-07-20
    • 2022-09-29
    • 2021-08-30
    • 2021-06-04
    • 1970-01-01
    相关资源
    最近更新 更多