<分区>
面试问题:
创建你自己的互斥锁:
我的实现:
public static class MyMutex {
static Queue<Thread> queue = new Queue<Thread>();
static int locked_state = 0 ;
static int inner_proc = 0;
public static void WaitOne()
{
// spin loop untill inner proccess are complete
while (Interlocked.Equals(inner_proc ,1))
{}
Interlocked.Exchange(ref inner_proc, 1);
// if in a locked state queue current thread and set to inifinite sleep
if (Interlocked.Exchange(ref locked_state, 1) == 1)
{
queue.Enqueue(Thread.CurrentThread);
Thread.Sleep(-1);
}
Interlocked.Exchange(ref inner_proc, 0);
}
public static void ReleaseMutex()
{
// spin loop untill inner proccess are complete
while (Interlocked.Equals(inner_proc ,1))
{}
// lock inner process (change to queue)
Interlocked.Exchange(ref inner_proc, 1);
if( queue.Count > 0 )
{
Thread t = queue.Dequeue();
t.Start();
}
if (queue.Count == 0)
{
Interlocked.Exchange(ref locked_state, 0);
}
// end lock inner process ( change to queue )
Interlocked.Exchange(ref inner_proc, 0);
}
}
解释:
如果互斥量处于锁定状态,则线程将排队,然后线程进入无限时间跨度的 sleep 模式。 检查和分配是自动进行的,以便第一个进入的线程将“锁定” 在任何其他人获得机会之前的状态(带有 1 标志)。
问题是当一个线程出队时,另一个线程可能会在 locked_state 被标记为 0 之前进入并调用 waitOne() ; 出于这个原因,我有一个内部自旋循环,它阻止 2 个线程同时改变队列。
*另一个问题是我怎样才能让线程休眠并唤醒它,就像我尝试的那样 在这里做(但我不能像我那样使用 thread.Start() 它会抛出异常) 并且线程挂起和恢复已被弃用。
所以一般来说(我真的不知道如何实现互斥量) 任何有关如何实现此目的的提示、想法或有用的链接都将不胜感激。