如何创建自定义互斥锁

时间:2012-02-04 03:58:53

标签: c# mutex

采访问题:

创建自己的互斥锁:

我的实施:

  

公共静态类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()像我做它抛出异常) 和线程暂停和恢复已被弃用。

所以总的来说(我真的不知道如何实现互斥锁) 任何有关如何实现这一目标的提示,想法或有用的链接都将非常受欢迎。

1 个答案:

答案 0 :(得分:0)

要回答至少部分问题,请按以下步骤暂停/恢复某个帖子:

// 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.
}