为什么这 4 个线程在使用信号量时会被锁定?

Why are these 4 threads locking up when using a semaphore?

在一个可能有很多很多线程的系统中,我试图确保一次只实例化 class 的四个实例,并可能在 5-60 秒后释放。实例在每个线程开始时创建,并在线程中的进程结束时销毁。

我还想防止一次只构建一个实例。所以我的逻辑是在对象实例化期间使用锁,但也用信号量包装整个线程逻辑。

private static readonly object padlock = new object();
private static readonly Semaphore mutablelock = new Semaphore(0, 4);

// called at the start of a long running thread
public static Object GetNewInstance()
{
    // semaphore used to prevent more than 4 objects from existing at any time
    mutablelock.WaitOne();

    // lock used to prevent more than one object being instantiated at a time
    lock (padlock)
    {
        var instance = new Object();
        return instance;
    }
}

// called at the end of a long running thread
public static void ReleaseInstance()
{
    mutablelock.Release();
}

该程序有四个线程(当使用调试停止点查看时)每个线程都在 mutablelock.WaitOne(); 行停止并且不再继续。

您构建 Semaphore 的方式是所有条目都已保留。 Semaphore constructor taking two arguments 是这样说的:

If initialCount is less than maximumCount, the effect is the same as if the current thread had called WaitOne (maximumCount minus initialCount) times. If you do not want to reserve any entries for the thread that creates the semaphore, use the same number for maximumCount and initialCount.

因此进行此更改:

private static readonly Semaphore mutablelock = new Semaphore(4, 4);