Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Locking on current thread: Possible WTF?

While looking into some old code, We came across the following code:

lock (System.Threading.Thread.CurrentThread) // Critical Section - no interrupting.

Our first reaction was "WTF" - the code is locking on the current thread, which is a different object on each thread (except in the case of recursion, which would just be silly to lock on, then). It doesn't seem like this lock serves any purpose whatsoever. We were wondering whether this was indeed a WTF, or whether it actually serves some purpose.

like image 305
Smashery Avatar asked Feb 28 '11 04:02

Smashery


People also ask

What happens when you lock a thread?

A lock allows you to force multiple threads to access a resource one at a time, rather than all of them trying to access the resource simultaneously. As you note, usually you do want threads to execute simultaneously. However, imagine that you have two threads and they are both writing to the same file.

What does it mean for a thread to be locked?

The LOCK THREAD statement ensures that no other thread executes. This condition remains in effect until the thread is unlocked (with UNLOCK THREAD) or the thread terminates.

Can you lock a thread?

For a thread to work on an object, it must have control over the lock associated with it, it must “hold” the lock. Only one thread can hold a lock at a time. If a thread tries to take a lock that is already held by another thread, then it must wait until the lock is released.

Can two threads acquire a lock at the same time?

Only one thread at a time may hold a lock on a monitor. Any other threads attempting to lock that monitor are blocked until they can obtain a lock on that monitor. A thread t may lock a particular monitor multiple times; each unlock reverses the effect of one lock operation.


1 Answers

It looks like a WTF from just that line of code, but if the thread object is ever passed to other threads and used as a lock, that makes some sense. However, using a thread as a lock seems like a pretty bad practice.

like image 166
NG. Avatar answered Sep 20 '22 04:09

NG.