1 year ago

#362162

test-img

Qwertyluk

Why SpinLock doesn't support recursion

I wonder why SpinLock doesn't support recursion.

Let's say I have a simple program with Monitor that locks and releases a block of instructions in a recursive way:

class Program
{
    private static readonly object lockObj = new object();

    private static void Recursion(int x)
    {
        bool lockWasTaken = false;
        try
        {
            Monitor.Enter(lockObj, ref lockWasTaken);
            Console.WriteLine(x);
        }
        finally
        {
            if (x > 0)
            {
                Recursion(x - 1);
            }
            if (lockWasTaken) Monitor.Exit(lockObj);
        }
    }

    static void Main(string[] args)
    {
        Recursion(5);

        Console.ReadKey();
    }
}

If I do the same with SpinLock:

class Program
{
    private static SpinLock sl = new SpinLock(true);

    private static void Recursion(int x)
    {
        bool lockWasTaken = false;
        try
        {
            sl.Enter(ref lockWasTaken);
            Console.WriteLine(x);
        }
        finally
        {
            if (x > 0)
            {
                Recursion(x - 1);
            }
            if (lockWasTaken) sl.Exit();
        }
    }

    static void Main(string[] args)
    {
        Recursion(5);

        Console.ReadKey();
    }
}

It throws an excpetion which says the calling thread already has a lock - and it is obviously true. But my question is why Monitor can acquire a lock multiple times by the same thread while SpinLock cannot? I can't find any reasons why a thread that has already locked a critical section can't enter it again.

c#

multithreading

locking

spinlock

0 Answers

Your Answer

Accepted video resources