詳解C#如何使用屏障實現(xiàn)多線程并發(fā)操作保持同步
寫在前面
以下是微軟官方對屏障類的介紹,System.Threading.Barrier 可用來作為實現(xiàn)并發(fā)同步操作的基本單元,讓多個線程(參與者)分階段并行處理目標(biāo)算法。在達(dá)到代碼中的屏障點之前,每個參與者將繼續(xù)執(zhí)行,屏障表示工作階段的末尾;單個參與者到達(dá)屏障后將被阻止,直至所有參與者都已達(dá)到同一障礙。 所有參與者都已達(dá)到屏障后,你可以選擇調(diào)用階段后操作。 此階段后操作可由單線程用于執(zhí)行操作,而所有其他線程仍被阻止。執(zhí)行此操作后,所有參與者將不受阻止,繼續(xù)執(zhí)行直到滿足退出條件。
下面的程序用于統(tǒng)計兩個線程使用隨機(jī)算法重新隨機(jī)選擇字詞,分別在同一階段查找一半解決方案時所需的迭代次數(shù)(或階段數(shù))。在每個線程隨機(jī)選擇字詞后,屏障后階段操作會比較兩個結(jié)果,以確定整個句子是否按正確的字詞順序呈現(xiàn)。
關(guān)鍵代碼如下:
barrier.SignalAndWait()
設(shè)置了代碼屏障點,代碼運行到這里會等待所有參與的線程都執(zhí)行完之前的代碼。
代碼實現(xiàn)
//#define TRACE using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace BarrierSimple { class Program { static string[] words1 = new string[] { "brown", "jumps", "the", "fox", "quick" }; static string[] words2 = new string[] { "dog", "lazy", "the", "over" }; static string solution = "the quick brown fox jumps over the lazy dog."; static bool success = false; static Barrier barrier = new Barrier(2, (b) => { StringBuilder sb = new StringBuilder(); for (int i = 0; i < words1.Length; i++) { sb.Append(words1[i]); sb.Append(" "); } for (int i = 0; i < words2.Length; i++) { sb.Append(words2[i]); if (i < words2.Length - 1) sb.Append(" "); } sb.Append("."); #if TRACE System.Diagnostics.Trace.WriteLine(sb.ToString()); #endif Console.CursorLeft = 0; Console.Write("Current phase: {0}", barrier.CurrentPhaseNumber); if (String.CompareOrdinal(solution, sb.ToString()) == 0) { success = true; Console.WriteLine("\r\nThe solution was found in {0} attempts", barrier.CurrentPhaseNumber); } }); static void Main(string[] args) { Thread t1 = new Thread(() => Solve(words1)); Thread t2 = new Thread(() => Solve(words2)); t1.Start(); t2.Start(); // Keep the console window open. Console.ReadLine(); } // Use Knuth-Fisher-Yates shuffle to randomly reorder each array. // For simplicity, we require that both wordArrays be solved in the same phase. // Success of right or left side only is not stored and does not count. static void Solve(string[] wordArray) { while (success == false) { Random random = new Random(); for (int i = wordArray.Length - 1; i > 0; i--) { int swapIndex = random.Next(i + 1); string temp = wordArray[i]; wordArray[i] = wordArray[swapIndex]; wordArray[swapIndex] = temp; } // We need to stop here to examine results // of all thread activity. This is done in the post-phase // delegate that is defined in the Barrier constructor. barrier.SignalAndWait(); } } } }
調(diào)用示例
到此這篇關(guān)于詳解C#如何使用屏障實現(xiàn)多線程并發(fā)操作保持同步的文章就介紹到這了,更多相關(guān)C#多線程并發(fā)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#中Array與ArrayList用法及轉(zhuǎn)換的方法
C#中Array與ArrayList用法及轉(zhuǎn)換的方法,需要的朋友可以參考一下2013-03-03C#使用RenderControl將GridView控件導(dǎo)出到EXCEL的方法
這篇文章主要介紹了C#使用RenderControl將GridView控件導(dǎo)出到EXCEL的方法,是C#應(yīng)用程序設(shè)計中非常實用的一個功能,需要的朋友可以參考下2014-08-08C#與C++?dll之間傳遞字符串string?wchar_t*?char*?IntPtr問題
C#與C++?dll之間傳遞字符串string?wchar_t*?char*?IntPtr問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-11-11