difference between lock, memory barrier, semaphore

前端 未结 3 1119
甜味超标
甜味超标 2021-01-31 23:34

This article: http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf (page 12) seems to make a difference between a lock and a memory barrier

I would like to know w

3条回答
  •  醉梦人生
    2021-02-01 00:30

    Simples explanation for now.

    Lock

    Is an atomic test for whether this piece of code can proceed

    lock (myObject)
    {
        // Stuff to do when I acquire the lock
    }
    

    This is normally a single CPU instruction that tests and sets a variable as a single atomic operation. More here, http://en.wikipedia.org/wiki/Test-and-set#Hardware_implementation_of_test-and-set_2

    Memory Barrier

    Is a hint to the processor that it can not execute these instructions out of order. Without it, the instructions could be executed out of order, like in double checked locking, the two null checks could be executed before the lock has.

    Thread.MemoryBarrier();
    public static Singleton Instance()
    {
        if (_singletonInstance == null)
        {
            lock(myObject)
            {
                if (_singletonInstance == null)
                {
                    _singletonInstance = new Singleton();
                }
            }
        }
    }
    

    This are also a set of CPU instructions that implement memory barriers to explicitly tell a CPU it can not execute things out of order.

    Semaphores

    Are similar to locks except they normally are for more than one thread. I.e. if you can handle 10 concurrent disk reads for example, you'd use a semaphore. Depending on the processor this is either its own instruction, or a test and set instruction with load more work around interrupts (for e.g. on ARM).

提交回复
热议问题