(并行编程)如何:使用屏障来使并发操作保持同步

如何:使用屏障来使并发操作保持同步

.NET Framework 4
 
其他版本
 
此主题尚未评级 - 评价此主题
 

 

下面的示例演示如何使用 Barrier 同步并发任务。

以下程序旨在通过使用一种随机化算法将一个短语的单词打乱排列,从而计算两个线程需要多少迭代(或阶段)才能各自找出自己的解答。在每个线程排列好单词之后,关卡后期阶段操作将比较两个结果,查看完整句子是否以正确的单词顺序呈现。

C#
VB
 
//#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",  "jumped", "the", "fox", "quick"};
        static string[] words2 = new string[] { "dog", "lazy","the","over"};
        static string solution = "the quick brown fox jumped 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();
            }
        }
    }
}


Barrier 是一个对象,它可以在并行操作中的所有任务都达到相应的关卡之前,阻止各个任务继续执行。如果并行操作是分阶段执行的,并且每一阶段要求各任务之间进行同步,则可以使用该对象。在本示例中,操作共分为两个阶段。在第一阶段,每一项任务将使用数据填充其缓冲区部分。每项任务在填写完各自的部分之后,均会向关卡发出自己已准备好继续的信号,然后进行等待。在所有任务都已向关卡发出信号之后,将取消阻塞这些任务,并开始第二阶段。由于第二阶段要求每项任务都必须具有对此时已生成的所有数据的访问权,因此关卡是必需的。如果没有关卡,那么,先期完成的任务可能会尝试从尚未由其他任务填充的缓冲区中进行读取。通过这种方式,可以对任意数量的阶段进行同步。

转载于:https://www.cnblogs.com/xust/articles/2883292.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值