简体   繁体   中英

C# (.net 3.5) run thread together

How can I sync threads to run together. For example:

code
Code section A
code

I want that every 5 thread will enter together to the Section A

Here's some sample code which shows how to use the Barrier class to wait for 5 threads to all be at the same point in the code before being allowed to carry on.

To try it out, run it and then ^C to stop it after a while, and inspect the times when the threads pass the barrier. You'll see that it is waiting until 5 threads are all at the barrier, then they are all released at once (whereupon the Barrier waits for the next 5 threads to be ready).

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".
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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