gpt4 book ai didi

c# - 为什么 Interlocked.Add() 方法必须返回一个值?

转载 作者:可可西里 更新时间:2023-11-01 03:14:17 25 4
gpt4 key购买 nike

public static int Add(ref int location1,int value)

我试图在多线程场景中使用 Interlocked.Add(ref int location1,int value) 方法以原子方式添加到数字。但是我对自己有一个疑问:为什么该方法再次返回 location1 值?相反,我们可以直接使用作为“ref”传递的变量。

下面是一些伪代码:

int a = 6;
int b = 7;

// some thing else

Interlocked.Add(ref a, b);

// Use the variable 'a' here.

最佳答案

因为变量 ref a 可能会在 Interlocked 返回之前(或者甚至在它返回之后和您使用 a 之前)“再次”改变。该函数反而返回它计算出的值。

例子:

int a = 5;

// on thread 1
int b = Interlocked.Add(ref a, 5); // b = 10

// on thread 2, at the same time
int c = Interlocked.Add(ref a, 5); // c = 15

// on thread 1
Thread.Sleep(1000); // so we are "sure" thread 2 executed
Thread.MemoryBarrier(); // just to be sure we are really reading a
bool x1 = (b == 10); // true
bool x2 = (a == 15); // true

关于c# - 为什么 Interlocked.Add() 方法必须返回一个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28850481/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com