【问题标题】:Interlocked in c#在 C# 中互锁
【发布时间】:2023-02-01 20:42:46
【问题描述】:

我试图在线程同步中理解 C# 中的 Interlocked

public int MethodUsedByMultipleThreads()
{
    var id = CreateNextId();
    return id;
}

private long CreateNextId()
{
    long id = 0;
    Interlocked.Exchange(ref id , this._nextId);
    Interlocked.Increment(ref this._nextId);
    return id;
}

是线

Interlocked.Exchange(ref id , this._nextId);

如果我直接使用是多余的

Interlocked.Increment(ref this._nextId);
return _nextId;

它会起到同样的作用吗?

【问题讨论】:

  • 您的变量是方法的本地变量。未共享
  • @DanielA.White this._nextId 显然是?
  • 一般来说,你想使用原子操作。看起来你应该只在共享变量上使用 Increment使用该操作的返回值而不是再次回到变量。您正在破坏原子操作的意义。

标签: c# thread-synchronization interlocked


【解决方案1】:
long CreateNextId() => Interlocked.Increment(ref this._nextId);

这就是以线程安全的方式生成顺序 ID 所需的全部内容。

【讨论】:

    猜你喜欢
    • 2022-07-31
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-21
    • 2011-08-10
    相关资源
    最近更新 更多