详解C#如何使用屏障实现多线程并发操作保持同步

 更新时间:2024年01月24日 09:04:09   作者:rjcql  
这篇文章主要为大家详细介绍了C#如何使用屏障实现多线程并发操作保持同步,文中的示例代码简洁易懂,具有一定的借鉴价值,有需要的小伙伴可以参考下

写在前面

以下是微软官方对屏障类的介绍,System.Threading.Barrier 可用来作为实现并发同步操作的基本单元,让多个线程(参与者)分阶段并行处理目标算法。在达到代码中的屏障点之前,每个参与者将继续执行,屏障表示工作阶段的末尾;单个参与者到达屏障后将被阻止,直至所有参与者都已达到同一障碍。 所有参与者都已达到屏障后,你可以选择调用阶段后操作。 此阶段后操作可由单线程用于执行操作,而所有其他线程仍被阻止。执行此操作后,所有参与者将不受阻止,继续执行直到满足退出条件。

下面的程序用于统计两个线程使用随机算法重新随机选择字词,分别在同一阶段查找一半解决方案时所需的迭代次数(或阶段数)。在每个线程随机选择字词后,屏障后阶段操作会比较两个结果,以确定整个句子是否按正确的字词顺序呈现。

关键代码如下:

barrier.SignalAndWait()

设置了代码屏障点,代码运行到这里会等待所有参与的线程都执行完之前的代码。

代码实现

//#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();
            }
        }
    }
}

调用示例

到此这篇关于详解C#如何使用屏障实现多线程并发操作保持同步的文章就介绍到这了,更多相关C#多线程并发内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • c# 通过WinAPI播放PCM声音

    c# 通过WinAPI播放PCM声音

    这篇文章主要介绍了c# 通过WinAPI播放PCM声音的方法,帮助大家更好的理解和使用c#编程语言,感兴趣的朋友可以了解下
    2020-12-12
  • C#:foreach与yield语句的介绍

    C#:foreach与yield语句的介绍

    C#:foreach与yield语句的介绍,需要的朋友可以参考一下
    2013-03-03
  • C# 字符串与unicode互相转换实战案例

    C# 字符串与unicode互相转换实战案例

    这篇文章主要介绍了C# 字符串与unicode互相转换实战案例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-01-01
  • C#通过NPOI操作Excel的实例代码

    C#通过NPOI操作Excel的实例代码

    C#操作Excel的方法有很多种,本文介绍了C#通过NPOI操作Excel,具有一定的参考价值,有兴趣的可以了解一下。
    2017-01-01
  • C#实现定时关机小应用

    C#实现定时关机小应用

    这篇文章主要为大家详细介绍了C#实现定时关机小应用,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-07-07
  • C#并行库Task类介绍

    C#并行库Task类介绍

    这篇文章介绍了C#并行库Task类,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-06-06
  • C# GroupBy的基本使用教程

    C# GroupBy的基本使用教程

    这篇文章主要给大家介绍了关于C# GroupBy的基本使用教程,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-02-02
  • C#交换两个变量值的几种方法总结

    C#交换两个变量值的几种方法总结

    这篇文章介绍了C#交换两个变量值的几种方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-10-10
  • C#单例模式(Singleton Pattern)详解

    C#单例模式(Singleton Pattern)详解

    这篇文章主要为大家详细介绍了C#单例模式Singleton Pattern的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-08-08
  • 用C#写的ADSL拨号程序的代码示例

    用C#写的ADSL拨号程序的代码示例

    用C#写的ADSL拨号程序的代码示例...
    2007-11-11

最新评论