The SpinLock structure in .Net can be used to manage access to resources from multiple threads. Other than a normal lock it uses a busy waiting, which is faster if the expected wait time is very low (but consumes more resources).
Other threading primitives such as a Monitor
and lock(...){}
always acquire the lock (or wait forever to acquire it). But the SpinLock.Enter
method uses a ref bool
parameters to indicate wether or not acquiring the lock failed.
What is the ref bool lockTaken
needed and in what cases can Monitor.Enter
fail (and thus set lockTaken
to false?)
Unlocking a Spin LockUse the pthread_spin_unlock(3C) function to release a locked spin lock.
In software engineering, a spinlock is a lock that causes a thread trying to acquire it to simply wait in a loop ("spin") while repeatedly checking whether the lock is available. Since the thread remains active but is not performing a useful task, the use of such a lock is a kind of busy waiting.
Spinlock is a locking system mechanism. It allows a thread to acquire it to simply wait in loop until the lock is available i.e. a thread waits in a loop or spin until the lock is available. Spinlock is held for a short period of time. Spinlock are useful in multiprocessor system.
A spinlock enforces a thread trying to access it to wait in a loop. The thread doesn't perform a task during this wait time. It only checks if the lock is available or not. On the other hand, a semaphore achieves process synchronization without busy waiting. Its wait operation puts the process into sleep.
This 'lockTaken' pattern is used in order to be sure about that lock is really taken by thread sync construct. Thing is - Monitor and SpinLock internally exit in finally block and lock is taken in try block.
Now, if thread has entered try block and was aborted before it was taken lock then it shouldn't be released in finally block. That problem is solved via ref bool
variable.
Boolean taken = false;
try {
// An exception (such as ThreadAbortException) could occur here...
Monitor.Enter(this, ref taken);
}
finally {
if (taken) Monitor.Exit(this);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With