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

本文关键字:线程 计算 | 更新日期: 2023-09-27 18:03:02

Grant Crofton对"无序线程问题"的回答有注释:

"如果你取消锁,最终计数可能少于100。"

为什么?

下面是context 的代码
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);
        }
    }
}

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

如果没有锁,就会发生这样的情况:

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

这些被称为竞态条件,并通过使操作原子

来解决。
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

因为锁保护count变量不受多个线程试图同时增加它的影响。如果发生这种情况,可能会给你奇怪的结果。

锁确保线程一次只能进入一个函数,因此每次只能执行一个函数内的操作。

如果你删除它,那么线程可以同时进入,在任何这些操作的中间被中断,并给你奇怪的结果,乱序的结果,等等