zoukankan      html  css  js  c++  java
  • 并发情况下取唯一流水号的写法

        readonly object _Syn = new object();
        int Seed = 0;
        
        public  int TreadValueGet()
        {
          // 5 Critical Section
          // Enter 和 Exit 方法提供的功能与 C# lock 语句提供的功能相同,
          // 区别在于 lock 将 Enter(Object, Boolean) 方法重载和 Exit 方法包装在 try…finally 块中以确保释放监视器
          //int _retValue = 0;
          //while (!System.Threading.Monitor.TryEnter(_Syn, 2))//TryEnter可以防御线程死锁
          //{
    
          //}
          //try
          //{
          //  _retValue = Seed + 1;
          //  Seed = _retValue;
          //  return _retValue;
          //}
          //finally
          //{
          //  System.Threading.Monitor.Exit(_Syn);
          //}
    
           // 4
          return System.Threading.Interlocked.Increment(ref Seed);
    
          // 3
          //return System.Threading.Interlocked.Add(ref Seed, 1);
    
          // 2 乐观锁,判断旧值未被修改后,用新值替换旧值.
          //   Interlocked.CompareExchange提供原子性的比较替换操作
          //int _seed;
          //int _retValue = 0;
          //do
          //{
          //  _seed = Seed;
          //  _retValue = _seed + 1;
          //} while (_seed != System.Threading.Interlocked.CompareExchange(ref Seed, _retValue, _seed));
          //return _retValue;
    
          // 1 最常用方法
          //lock (_Syn)
          //{
          //  return Seed++;
          //}
        }
    

      

    System.Threading.Interlocked资料

    http://msdn.microsoft.com/zh-cn/library/system.threading.interlocked.aspx

  • 相关阅读:
    python——集合
    python——字典
    python——用递归的方法求x的y次幂
    python——全局变量&局部变量
    python——组织列表
    Linux显示网络相关信息
    Linux里的发消息
    Linux中各种压缩文件
    Linux中的man
    Linux的find命令
  • 原文地址:https://www.cnblogs.com/Grart/p/4084955.html
Copyright © 2011-2022 走看看