如何获得等待输入锁的线程数量? [英] How to get the amount of threads waiting to enter a lock?

查看:86
本文介绍了如何获得等待输入锁的线程数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能获得一个值,该值指示有多少线程正在等待获取某个对象的锁?

Is it possible to get a value which indicates how many threads are waiting to acquire a lock on a certain object?

推荐答案

否,但是您可以将锁封装在具有以下功能的类中:

No, but you could incapsulate the lock in a class that does:

Interlocked.Increment

在输入柜台锁之前和

Interlocked.Decrement

获得锁定后

例如:

public sealed class SimpleCountedLock
{
    private readonly object obj = new object();

    private int counter;

    public int Counter
    {
        get
        {
            // Guaranteed to return the last value
            return Interlocked.CompareExchange(ref counter, 0, 0);
        }
    }

    public void Enter(ref bool lockTaken)
    {
        int cnt = int.MinValue;

        try
        {
            try
            {
            }
            finally
            {
                // Finally code can't be interrupted by asyncronous exceptions
                cnt = Interlocked.Increment(ref counter);
            }

            Monitor.Enter(obj, ref lockTaken);
        }
        finally
        {
            // There could be an asynchronous exception (Thread.Abort for example)
            // between the try and the Interlocked.Increment .
            // Here we check if the Increment was done
            if (cnt != int.MinValue)
            {
                Interlocked.Decrement(ref counter);
            }
        }
    }

    public void Exit()
    {
        Monitor.Exit(obj);
    }
}

使用:

SimpleCountedLock cl = new SimpleCountedLock();

,然后在各个线程中:

bool lockTaken = false;

try
{
    cl.Enter(ref lockTaken);
    // Your code. The lock is taken
}
finally
{
    if (lockTaken)
    {
        cl.Exit();
    }
}

引用锁定的原因在这里:监视.输入.

The reasoning for the ref lockTaken is here: Monitor.Enter.

这篇关于如何获得等待输入锁的线程数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆