Answers:
正如其他人所推荐的那样,它们的Interlocked.Increment
性能将优于lock()
。只需看一下IL和Assembly,您将看到它Increment
变成了“总线锁定”语句,并且其变量直接增加(x86)或“增加”到(x64)。
该“总线锁定”语句锁定总线,以防止在调用CPU进行操作时另一个CPU访问该总线。现在,看一下C#lock()
语句的IL。在这里,您将看到调用以Monitor
开始或结束一个部分。
换句话说,.Net lock()
语句的作用远远超过.Net Interlocked.Increment
。
因此,如果您要做的只是增加一个变量,Interlock.Increment
它将更快。查看所有“互锁”方法,以查看可用的各种原子操作并找到适合您需求的操作。使用lock()
时,你想去做多个相互关联的递增/递减,或者连续访问更复杂的事情,是不是整数更复杂的资源。
我建议您在System.Threading库中使用.NET的内置互锁增量。
以下代码将通过引用增加一个长变量,并且完全是线程安全的:
Interlocked.Increment(ref myNum);
如前所述,使用 Interlocked.Increment
来自MS的代码示例:
下面的示例确定要生成具有中点值的1,000个随机数,需要多少个从0到1,000的随机数。为了跟踪中点值的数量,将变量MidpointCount设置为等于0,并在每次随机数生成器返回中点值时递增,直到其达到10,000。由于三个线程生成随机数,因此调用Increment(Int32)方法以确保多个线程不会同时更新midpointCount。注意,锁还用于保护随机数生成器,并且CountdownEvent对象用于确保Main方法在三个线程之前不会完成执行。
using System;
using System.Threading;
public class Example
{
const int LOWERBOUND = 0;
const int UPPERBOUND = 1001;
static Object lockObj = new Object();
static Random rnd = new Random();
static CountdownEvent cte;
static int totalCount = 0;
static int totalMidpoint = 0;
static int midpointCount = 0;
public static void Main()
{
cte = new CountdownEvent(1);
// Start three threads.
for (int ctr = 0; ctr <= 2; ctr++) {
cte.AddCount();
Thread th = new Thread(GenerateNumbers);
th.Name = "Thread" + ctr.ToString();
th.Start();
}
cte.Signal();
cte.Wait();
Console.WriteLine();
Console.WriteLine("Total midpoint values: {0,10:N0} ({1:P3})",
totalMidpoint, totalMidpoint/((double)totalCount));
Console.WriteLine("Total number of values: {0,10:N0}",
totalCount);
}
private static void GenerateNumbers()
{
int midpoint = (UPPERBOUND - LOWERBOUND) / 2;
int value = 0;
int total = 0;
int midpt = 0;
do {
lock (lockObj) {
value = rnd.Next(LOWERBOUND, UPPERBOUND);
}
if (value == midpoint) {
Interlocked.Increment(ref midpointCount);
midpt++;
}
total++;
} while (midpointCount < 10000);
Interlocked.Add(ref totalCount, total);
Interlocked.Add(ref totalMidpoint, midpt);
string s = String.Format("Thread {0}:\n", Thread.CurrentThread.Name) +
String.Format(" Random Numbers: {0:N0}\n", total) +
String.Format(" Midpoint values: {0:N0} ({1:P3})", midpt,
((double) midpt)/total);
Console.WriteLine(s);
cte.Signal();
}
}
// The example displays output like the following:
// Thread Thread2:
// Random Numbers: 2,776,674
// Midpoint values: 2,773 (0.100 %)
// Thread Thread1:
// Random Numbers: 4,876,100
// Midpoint values: 4,873 (0.100 %)
// Thread Thread0:
// Random Numbers: 2,312,310
// Midpoint values: 2,354 (0.102 %)
//
// Total midpoint values: 10,000 (0.100 %)
// Total number of values: 9,965,084
下面的示例与上一个示例相似,不同之处在于它使用Task类而不是线程过程来生成50,000个随机中点整数。在此示例中,lambda表达式替换了GenerateNumbers线程过程,并且对Task.WaitAll方法的调用消除了对CountdownEvent对象的需求。
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
public class Example
{
const int LOWERBOUND = 0;
const int UPPERBOUND = 1001;
static Object lockObj = new Object();
static Random rnd = new Random();
static int totalCount = 0;
static int totalMidpoint = 0;
static int midpointCount = 0;
public static void Main()
{
List<Task> tasks = new List<Task>();
// Start three tasks.
for (int ctr = 0; ctr <= 2; ctr++)
tasks.Add(Task.Run( () => { int midpoint = (UPPERBOUND - LOWERBOUND) / 2;
int value = 0;
int total = 0;
int midpt = 0;
do {
lock (lockObj) {
value = rnd.Next(LOWERBOUND, UPPERBOUND);
}
if (value == midpoint) {
Interlocked.Increment(ref midpointCount);
midpt++;
}
total++;
} while (midpointCount < 50000);
Interlocked.Add(ref totalCount, total);
Interlocked.Add(ref totalMidpoint, midpt);
string s = String.Format("Task {0}:\n", Task.CurrentId) +
String.Format(" Random Numbers: {0:N0}\n", total) +
String.Format(" Midpoint values: {0:N0} ({1:P3})", midpt,
((double) midpt)/total);
Console.WriteLine(s); } ));
Task.WaitAll(tasks.ToArray());
Console.WriteLine();
Console.WriteLine("Total midpoint values: {0,10:N0} ({1:P3})",
totalMidpoint, totalMidpoint/((double)totalCount));
Console.WriteLine("Total number of values: {0,10:N0}",
totalCount);
}
}
// The example displays output like the following:
// Task 3:
// Random Numbers: 10,855,250
// Midpoint values: 10,823 (0.100 %)
// Task 1:
// Random Numbers: 15,243,703
// Midpoint values: 15,110 (0.099 %)
// Task 2:
// Random Numbers: 24,107,425
// Midpoint values: 24,067 (0.100 %)
//
// Total midpoint values: 50,000 (0.100 %)
// Total number of values: 50,206,378
https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.interlocked.increment?view=netcore-3.0