標籤:user task barrier should div 使用 span array date
手動進行線程同步
1>使用WaitHandle做資料同步或者資料等待 根據的是
AutoResetEvent() 是否阻塞 如果沒有阻塞則正常 waitall是全部沒有阻塞就可以通過 waitall是一個沒有阻塞就通過
using System;using System.Threading;public sealed class App { // Define an array with two AutoResetEvent WaitHandles. static WaitHandle[] waitHandles = new WaitHandle[] { new AutoResetEvent(false), new AutoResetEvent(false) }; // Define a random number generator for testing. static Random r = new Random(); static void Main() { // Queue up two tasks on two different threads; // wait until all tasks are completed. DateTime dt = DateTime.Now; Console.WriteLine("Main thread is waiting for BOTH tasks to complete."); ThreadPool.QueueUserWorkItem(new WaitCallback(DoTask), waitHandles[0]); ThreadPool.QueueUserWorkItem(new WaitCallback(DoTask), waitHandles[1]); WaitHandle.WaitAll(waitHandles); // The time shown below should match the longest task. Console.WriteLine("Both tasks are completed (time waited={0})", (DateTime.Now - dt).TotalMilliseconds); // Queue up two tasks on two different threads; // wait until any tasks are completed. dt = DateTime.Now; Console.WriteLine(); Console.WriteLine("The main thread is waiting for either task to complete."); ThreadPool.QueueUserWorkItem(new WaitCallback(DoTask), waitHandles[0]); ThreadPool.QueueUserWorkItem(new WaitCallback(DoTask), waitHandles[1]); int index = WaitHandle.WaitAny(waitHandles); // The time shown below should match the shortest task. Console.WriteLine("Task {0} finished first (time waited={1}).", index + 1, (DateTime.Now - dt).TotalMilliseconds); } static void DoTask(Object state) { AutoResetEvent are = (AutoResetEvent) state; int time = 1000 * r.Next(2, 10); Console.WriteLine("Performing a task for {0} milliseconds.", time); Thread.Sleep(time); are.Set(); }}
2> C# 4.0 Barrier類
public static void Speak() { for (int i = 0; i < 5; i++) { Console.Write(i + ""); d.SignalAndWait();//等待 當有3個線程進入了這個方法的時候就可以繼續 } } /// <summary> /// 當到達3個線程觸發Action<Barrier>中的內容 第一個是要求達到的線程數 /// </summary> static Barrier d = new Barrier(3, d1 => { Console.WriteLine(""); }); static void Main(string[] args) { new Thread(Speak).Start(); new Thread(Speak).Start(); new Thread(Speak).Start(); Console.ReadKey(); }
資料同步 線程 c#