用锁定计数线程(c#)

时间:2013-03-09 15:27:57

标签: c# .net multithreading asynchronous synchronization

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

  

“如果您取消锁定,最终计数可能会少于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);
        }
    }
}

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:2)

因为锁保护count变量免受多个线程的影响,试图立即递增它。如果发生这种情况,可能会给你带来奇怪的结果。

锁定确保线程一次只能输入一个函数,因此一次只能在其中执行一个操作。

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