gpt4 book ai didi

c# - 计算带锁和不带锁的线程 (c#)

转载 作者:太空宇宙 更新时间:2023-11-03 19:17:16 25 4
gpt4 key购买 nike

Grant Crofton's answer对“无序线程问题”的问题有评论:

"And if you remove the lock the final count might be less than 100."

为什么?

这是上下文的代码

class Program
{
static object locker = new object();
static int count=0;

static void Main(string[] args)
{
for (int j = 0; j < 100; j++)
{
(new Thread(new ParameterizedThreadStart(dostuff))).Start(j);
}
Console.ReadKey();
}

static void dostuff(object Id)
{
lock (locker)
{
count++;
Console.WriteLine("Thread {0}: Count is {1}", Id, count);
}
}
}

最佳答案

这是可能没有锁的情况:

Count = 0

ThreadA Reads Count As 0
ThreadB Reads Count As 0
ThreadA Writes New Incremented Count As 0 + 1
ThreadB Writes New Incremented Count As 0 + 1

Count = 1

这些被称为 Race Conditions并通过执行操作 Atomic 来解决

Count = 0

ThreadB Wins Race To Lock()
ThreadB Reads Count As 0
ThreadB Writes New Incremented Count As 0 + 1
ThreadB Unlocks

ThreadA Next for Lock()
ThreadA Reads Count As 1
ThreadA Writes New Incremented Count As 1 + 1
ThreadA Unlocks

Count = 2

关于c# - 计算带锁和不带锁的线程 (c#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15312397/

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