Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can SpinLock.Enter fail to acquire the lock?

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?)

like image 258
Roy T. Avatar asked Oct 16 '15 07:10

Roy T.


People also ask

How do you unlock a spinlock?

Unlocking a Spin LockUse the pthread_spin_unlock(3C) function to release a locked spin lock.

What is spinlock problem?

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.

How does a spinlock work?

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.

What is the concept behind strong semaphore and spinlock?

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.


1 Answers

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);
}
like image 93
nikita Avatar answered Oct 20 '22 17:10

nikita