How are semaphores and test-and-set instructions connected? Cheers, so my textbook explains these parts very poorly, so I would gladly take any advice! I am confused between the test-and-set instructions, which per my book is a very common CPU instruction set, and the use of semaphores for which my book says that: a flag implemented using this way, is a semaphore. Does that mean that semaphores are a part of these instructions or the opposite? Also, if a operating system does not support semaphores, can it support test-and-set instructions and if yes, can you reach mutual exclusion this way? Thanks!
Semaphores are an abstract mechanism to control access to a shared resource. Other such mechanisms exist, for example locks and monitors. These are the counterparts of abstract data structures – they specify an API for a mechanism and its semantics, but not its implementation.
Implementing such mechanisms correctly requires hardware support. One way to implement semaphores is using test-and-set. Another popular instruction is compare-and-swap. Both of these are examples of atomic instructions, which are instructions performing several operations that cannot be interrupted in the middle. Such atomic instructions are necessary to correctly implement mechanisms such as semaphores.
Typically these control mechanisms are implemented by the operating system. For example, POSIX-compliant systems implement POSIX semaphores. Semaphores are just one more service provided by the operating system. Under the hood, semaphores are implemented using atomic instructions provided by the CPU.