Understanding non blocking thread synchronization and Thread.MemoryBarrier

后端 未结 1 965
耶瑟儿~
耶瑟儿~ 2021-01-18 16:29

In this threading online book: http://www.albahari.com/threading/part4.aspx

theres an example of Thread.MemoryBarrier()

   class Foo
{
         


        
相关标签:
1条回答
  • 2021-01-18 17:05

    The fact that instructions take time to execute does not imply that a thread is blocked. A thread is blocked when it is specifically put into a blocked state, which MemoryBarrier() does not do.

    The processor instructions that actually prevent instruction reordering and cache flushing take time, because they must wait for the caches to become coherent again. During that time, the thread is still considered running.

    Update: So let's take a look at what's actually happening in the example, and what each memory barrier actually does.

    As the link says, 1 and 4 ensure that the correct answers are produced. That's because 1 ensures that the answers are flushed into memory, and 4 ensures that the read caches are flushed prior to retrieving the variables.

    2 and 3 ensure that if A runs first, then B will always print the answers. Barrier 2 ensures that the write of true is flushed to memory, and barrier 3 ensures that the read cahces are flushed before testing _complete's value.

    The cache and memory flushing should be clear enough, so let's look at instruction reordering. The way the compiler, CLR and CPU know they can reorder instructions is by analyzing a set of instructions in sequence. When they see the barrier instruction in the middle of a sequence, they know that instructions can't move across that boundary. That ensures that in addition to cache freshness, the instructions occur in the correct order.

    0 讨论(0)
提交回复
热议问题