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

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

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

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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 @   Charltsing  阅读(510)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示