When to use 'volatile' or 'Thread.MemoryBarrier()' in threadsafe locking code? (C#)

前端 未结 4 477
伪装坚强ぢ
伪装坚强ぢ 2020-12-09 04:25

When should I use volatile/Thread.MemoryBarrier() for thread safety?

4条回答
  •  轮回少年
    2020-12-09 05:00

    What's wrong with

    private static readonly object syncObj = new object();
    private static int counter;
    
    public static int NextValue()
    {
        lock (syncObj)
        {
            return counter++;
        }
    }
    

    ?

    This does all necessary locking, memory barriers, etc. for you. It's well understood and more readable than any custom synchronization code based on volatile and Thread.MemoryBarrier().


    EDIT

    I can't think of a scenario in which I'd use volatile or Thread.MemoryBarrier(). For example

    private static volatile int counter;
    
    public static int NextValue()
    {
        return counter++;
    }
    

    is not equivalent to the code above and is not thread-safe (volatile doesn't make ++ magically become thread-safe).

    In a case like this:

    private static volatile bool done;
    
    void Thread1()
    {
        while (!done)
        {
            // do work
        }
    }
    
    void Thread2()
    {
        // do work
        done = true;
    }
    

    (which should work) I'd use a ManualResetEvent to signal when Thread2 is done.

提交回复
热议问题