Roy T.
Roy T.

Reputation: 9638

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

Upvotes: 7

Views: 1460

Answers (1)

nikita
nikita

Reputation: 2817

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);
}

Upvotes: 8

Related Questions