How to get the amount of threads waiting to enter a lock?

戏子无情 提交于 2019-12-11 11:31:00

问题


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


回答1:


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

Interlocked.Increment

before entering the lock on a counter and

Interlocked.Decrement

after attaining the lock

For example:

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

Use:

SimpleCountedLock cl = new SimpleCountedLock();

and then in the various threads:

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.



来源:https://stackoverflow.com/questions/28784953/how-to-get-the-amount-of-threads-waiting-to-enter-a-lock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!