如何创建自定义互斥
本文关键字:自定义 创建 何创建 | 更新日期: 2023-09-27 18:22:21
面试问题:
创建您自己的互斥对象:
我的实现:
公共静态类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);
}
}
解释:
如果互斥锁处于锁定状态,则线程将排队,然后线程将进入睡眠模式,持续无限的时间跨度。检查和分配是原子式的,这样第一个进入的线程就会"锁定"在任何其他人获得机会之前的状态(带有1标志)。
问题是,当一个线程退出队列时,另一个线程可以在locked_state标记为0之前进入并调用waitOne();出于这个原因,我有一个内部自旋循环,它阻塞2个线程来同时更改队列。
*另一个问题是,我如何让线程进入睡眠状态,然后像我尝试的那样将其唤醒在这里执行(但我不能像使用thread.Start()那样使用它抛出异常)以及线程挂起和恢复已被弃用。
所以一般来说(我真的不知道如何实现互斥)任何关于如何做到这一点的提示、想法或有用的链接都将不胜感激。
要至少回答部分问题,以下是我如何处理暂停/恢复线程:
// In the thread to be suspended:
// This will return false if the thread needs to end immediately.
// This will return true if normal operation should continue.
private bool SuspendCurrentThread()
{
try
{
for (;;)
{
Thread.Sleep(Timeout.Infinite);
}
}
catch (ThreadInterruptedException)
{
// Resume normal operation.
return true;
}
catch (ThreadAbortException)
{
return false;
}
}
// ...
// ...
// ...
// In the thread that is to trigger the resume:
private Thread OtherThread = /* something */;
private void ResumeOtherThread()
{
OtherThread.Interrupt();
}
private void KillOtherThread()
{
OtherThread.Abort(); // Fire a ThreadAbortException in the other thread if it is in a waiting state.
OtherThread.Join(); // Wait until the other thread has exited before continuing.
}