在多线程中,获取一个唯一的索引数字

在多线程处理中,我们有时需要给每个线程获取一个唯一的数字用作索引。

采用Interlocked.CompareExchange做原子判断,当原来的计数索引没有被其它线程改变时,给计数索引赋予新值。这个操作是原子的,所以不会发生线程冲突。

 

        private static volatile int IndexOfNumber = 1;        //计数索引。注意volatile限定。
        /// <summary>
        /// 使用线程安全的方法,使IndexNumber按照指定步长变化。默认步长=1
        /// 返回值:新的索引值。
        /// </summary>
        /// <returns></returns>
        private static int GetNewIndexNumberSafe(int step = 1)
        {
            //下面的代码保证返回的索引号是唯一的。
            //https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.interlocked.compareexchange?view=netframework-4.8
            int CurrentIndexValue;
            int NewIndexValue;
            do
            {
                CurrentIndexValue = IndexNumber;       //记录当前的索引号 
                NewIndexValue = IndexNumber + step;    //更新后的索引号

                //如果CurrentIndexValue不等于IndexNumber,说明其它线程改变了索引值
                //返回值是被其它线程更新的IndexNumber,不等于CurrentIndexValue,循环继续。
            } while (CurrentIndexValue != Interlocked.CompareExchange(ref IndexNumber, NewIndexValue, CurrentIndexValue));
            //参数1和参数3比较,如果相等,把参数2赋值给参数1。返回值是原始的参数1。

            //如果CurrentIndexValue等于IndexNumber,说明没有其它线程改变索引值,
            //则返回更新后的索引NewIndexValue给IndexOfNumber,相当于索引+step。 
            //返回值是原来的CurrentIndexValue,等于更新前的IndexNumber,循环结束。 
            return NewIndexValue; 
        }

  

转载于:https://www.cnblogs.com/Charltsing/p/CompareExchange.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值