[英]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 我希望每5个线程一起进入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. 这是一些示例代码,显示了如何使用Barrier
类等待5个线程在代码中的所有相同点之前被允许继续执行。
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. 要进行尝试,请先运行它,然后运行^ C以将其停止一段时间,然后检查线程通过屏障的时间。 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). 您会看到它一直等到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.