繁体   English   中英

C#(.net 3.5)一起运行线程

[英]C# (.net 3.5) run thread together

如何同步线程以使其一起运行。 例如:

code
Code section A
code

我希望每5个线程一起进入A节

这是一些示例代码,显示了如何使用Barrier类等待5个线程在代码中的所有相同点之前被允许继续执行。

要进行尝试,请先运行它,然后运行^ C以将其停止一段时间,然后检查线程通过屏障的时间。 您会看到它一直等到5个线程全部处于障碍状态,然后立即全部释放它们(随后,障碍将等待下一个5个线程准备就绪)。

using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
            Barrier barrier = new Barrier(5); // 5 == #participating threads.
            Action[] actions = new Action[10];
            var sw = Stopwatch.StartNew();
            ThreadPool.SetMinThreads(12, 12); // Prevent delay on starting threads.
                                              // Not recommended for non-test code!
            for (int i = 0; i < actions.Length; ++i)
                actions[i] = () => test(barrier, sw);

            Parallel.Invoke(actions);
        }

        static void test(Barrier barrier, Stopwatch sw)
        {
            int id = Thread.CurrentThread.ManagedThreadId;
            Random rng = new Random(id);

            while (true)
            {
                int wait = 5000 + rng.Next(5000);
                Console.WriteLine($"[{sw.ElapsedMilliseconds:000000}] Thread {id} is sleeping for {wait} ms.");
                Thread.Sleep(wait);
                Console.WriteLine($"[{sw.ElapsedMilliseconds:000000}] Thread {id} is waiting at the barrier.");
                barrier.SignalAndWait();
                Console.WriteLine($"[{sw.ElapsedMilliseconds:000000}] Thread {id} passed the barrier.");
                Thread.Sleep(1000); // This is the equivalent of your "Section A".
            }
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM