
When T1 is done with the lock it sets the lock back to 0 so T2 is able to acquire the lock. Then T2 would have spun because when it tried to place 1 into the lock variable the previous value was already 1, not 0. While(0 != InterlockedCompareExchange(&lock, 1, 0))įollowing the steps above T1 would have exchanged 1 into the lock location.
T2 – Stops spinning and finishes acquireĪ spinlock can be as simple as a while loop using InterlockedCompareExchange to place 1 into the variable as long as the value at the time of exchange is 0. T2 – Attempts to acquire access for read – BLOCKED and spins, burning CPU and not making forward progress. Let’s look at a simple pattern of a single path synchronization object. The idea behind a reader, writer synchronization object is to allow reader parallelization in conjunction with writer synchronization. A common technique used in multi-threaded coding is a reader, writer lock. There are hundreds of locations throughout the SQL Server code base that must account for multi-threaded access. (Thread.currentThread().This post is not about a specific SQL Server object but instead outlines a technique used in various locations to reduce contention while still providing thread synchronization.
(Thread.currentThread().getName() +" started to WRITE") Private static Semaphore sm = new Semaphore(2) Private static final Random rand = new Random() Private static Thread t1, t2, t3, t4, t5 When writing is finished, then 2 readers can read at once. What it must do, that it has 1 book, only 1 writer can write a new line there and while he is writing, no1 else can access it. So i've found an example of how to use Semaphore and made my code into there for Readers-Writers problem.