gpt4 book ai didi

c# - 当锁没有竞争时, lock(...) 的开销是多少?

转载 作者:IT王子 更新时间:2023-10-29 04:30:17 27 4
gpt4 key购买 nike

在研究双重检查锁定时,我看到了许多建议,即跳过第一次检查并立即获取锁,取而代之的是检查。

这让我想知道,lock (this.padlock) 在没有竞争时是否“便宜”?

最佳答案

我们可以测试一下...

我得到:

1000000000; 2164 (no lock)
1000000000; 23258 (lock)
21.094ns per lock

代码:

using System;
using System.Diagnostics;

static class P
{
static void Main()
{

Test(1); // for JIT
Test(1000000);
}
static readonly object syncLock = new object();
static void Test(int count)
{
int j = 0;
var watch = Stopwatch.StartNew();
for(int i = 0 ; i < count ; i++)
{
for (int z = 0; z < 1000; z++)
j++;
}
watch.Stop();
long withoutMillis = watch.ElapsedMilliseconds;
Console.WriteLine("{0}; {1} (no lock)", j, watch.ElapsedMilliseconds);

j = 0;
watch = Stopwatch.StartNew();
for (int i = 0; i < count; i++)
{
for (int z = 0; z < 1000; z++ )
lock (syncLock)
{
j++;
}
}
watch.Stop();
long withMillis = watch.ElapsedMilliseconds;
Console.WriteLine("{0}; {1} (lock)", j, watch.ElapsedMilliseconds);

long deltaNano = (withMillis - withoutMillis) * 1000000;
// nano = 1000 micro = 1000000 milli
double perLockNano = deltaNano/(1000.0 * count);
Console.WriteLine("{0}ns per lock", perLockNano);
}
}

关于c# - 当锁没有竞争时, lock(...) 的开销是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8788479/

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