c# - 屏障类c#

标签 c# multithreading barrier

我确实了解 C# 中使用的 Barrier 类。但是,在下面的代码中,我不明白为什么 SignalAndWait() 被调用了两次?任务中的调用还不够吗?该代码基本上模拟了这样的情况:三个 friend (或任务)从 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!");
}

最佳答案

您还会看到行 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

关于c# - 屏障类c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24975239/

相关文章:

c++ - 测试 MPI_Barrier C++

C#小数取上限2

c# - 实时 555 c# 包装器

c# - TreeViewItems 和键绑定(bind)

c# - IIS/WCF 客户端证书到用户的一对一映射 & 内部服务器错误

multithreading - 640 企业库缓存线程 - 如何?

webserver - MPI_SEND 在 MPI_BARRIER 之后停止工作

c++ - 多线程访问全局变量: should I use mutex

java - 当有两个以上线程运行时,如何使两个线程仅相互响应 - Java

multithreading - 为什么与信号量解决方案会合不能推广(我们使用屏障代替)?