处理大量并发问题

在日常业务里面,我们可能会遇到类似这样的需求,有1万个座位,同时有1万人过来买票,如何在最短时间内,完成这1人1张票的分发。

大概写了一个单元测试,发起1万个并行任务,跑了一下,200毫秒以内,可以完成这个分发功能。代码如下:

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
namespace Jack.Pay.UnitTest
{
    [TestClass]
    public class ThreadTest
    {
        [TestMethod]
        public void Test()
        {
        //生成1万个对象 ObjectItem[] items
= new ObjectItem[10000]; for(int i = 0; i < items.Length; i ++) { items[i] = new ObjectItem(); } Stopwatch stopWatch = new Stopwatch(); stopWatch.Start();         
        //同时发起1万个并行任务,去抢占对象 ParallelLoopResult result
= Parallel.For(0 , items.Length , (i)=>{ start(i + 1, items); }); stopWatch.Stop(); items = items.OrderBy(m => m.Owner).ToArray(); for (int i = 0; i < items.Length; i++) { if(items[i].Owner - i != 1) { throw new Exception("结果错误"); } } var elapsedTime = stopWatch.ElapsedMilliseconds; } void start(int yourId, ObjectItem[] items) { for (int j = 0; j < items.Length; j++) {
          //用原子性的函数做判断,如果Owner是0,把yourId写入Owner,这个方法是防止并发的
int originalValue = Interlocked.CompareExchange(ref items[j].Owner, yourId, 0); if (originalValue == 0) { //证明成功占用这个item return; } else { //失败了,别人已经认领 } } } } class ObjectItem { public int Owner; public override string ToString() { return Owner.ToString(); } } }

主要是使用Interlocked.CompareExchange来判断对象是否被占用,用lock也是可以的,但是速度比较慢。

原文地址:https://www.cnblogs.com/IWings/p/9295905.html