Search code examples
operating-systemcritical-sectioninstructions

How could the test_and_set() instruction still work on a multiprocessor?


Dear stack overflow community,

I'm reading Operating System Concepts (2012) by Silberschatz, Galvin and Gagne, it says "if two test_and_set() instructions are executed simultaneously (each on a different CPU), they will be executed sequentially in some arbitrary order." on page 210, I cannot understand why two such institutions will be executed sequentially even on a multiprocessor. What if each instruction is executed on a different processor? To the best of my knowledge, these two institutions be executed simultaneously.

My understanding of the atomicity of instructions and the multiprocessor stays at a quite superficial level, so I may take the problem for granted. Could anyone help me out here?


Solution

  • The whole point of test-and-set is that one processor will execute it first, and then the other processor will execute it, and they will not do it simultaneously.

    To achieve this, there will be some communication between both processors. Basically, one processor will load the cache line including the memory location from memory, and tell the other processor that it can't have that cache line until both test and set are finished.