从假设无法原子地增加计数器和锁定互斥锁(或获取它的ty)开始,是否有任何多线程库允许读取互斥锁上的等待线程数?
答案 0 :(得分:0)
我不知道您编写的是哪种编程语言,但在C#中,您可以try to get an exclusive lock在一个没有阻塞的对象上,因此您的Mutex实现将如下所示:
class MyMutex
{
public int LockedThreadsCount
{
get { lock (countLock) { return waitingThreads; } }
}
public void WaitOne()
{
if (!Monitor.TryEnter(mainLock))
{
lock (countLock) { waitingThreads++; }
Monitor.Enter(mainLock);
lock (countLock) { waitingThreads--; }
}
}
public void Release()
{
Monitor.Exit(mainLock);
}
private int waitingThreads = 0;
private object countLock = new object();
private object mainLock = new object();
}