Ran*_*tha 15 c# multithreading
public static int Add(ref int location1,int value)
Run Code Online (Sandbox Code Playgroud)
我试图使用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.
Run Code Online (Sandbox Code Playgroud)
xan*_*tos 32
因为变量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
Run Code Online (Sandbox Code Playgroud)