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

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

采用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; 
        }

  

posted @ 2019-05-23 07:53  Charltsing  阅读(501)  评论(0编辑  收藏  举报