简体   繁体   中英

Find which thread currently owns a lock so I can kill it

I need to find out which thread currently owns the lock.

I'm writing a multithread server using ThreadPool that hosts independent application instances. When shutting down an application instance I call Monitor.TryEnter to either acquire the lock or timeout. If a timeout occurs I need to get which thread owns the lock so I can abort it.

If there are no bugs in the applications I would never need to do this as each worker would lock and unlock the application instance on entry and exit to the application. But if there IS a bug, and for whatever reason the worker doesn't exit and is either deadlocked or stuck in an endless loop I want to be able to kill that thread and application instance, while letting the rest of my server live on. The application instance at this point is a lost cause.

Seems like a pretty straight forward requirement, but couldn't find anything built in to do it.

One workaround would be to add a Thread member in the same context as the lock and have each thread update it as it acquires the lock. But that relies on everyone ALWAYS remembering to update it when a lock is acquired.

You think the thread control as a top down hierarchy, but this is not the right way of thinking in the matter of multithreaded applications. If a Thread has a timeout or something else went wrong during its execution, the thread itself has to take care of releasing the lock and ending itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM