Silverlight ReaderWriterLock实现好/坏?

时间:2009-03-04 22:32:00

标签: c# silverlight multithreading

我为Silverlight实现了一个简单的(没有升级或超时)ReaderWriterLock的adopted实现,我想知道具有正确专业知识的任何人都可以通过设计来验证它是好还是坏。对我来说它看起来很不错,它的工作方式与广告一样,但我对多线程代码的经验有限。

public sealed class ReaderWriterLock
{
    private readonly object syncRoot = new object();    // Internal lock.
    private int i = 0;                                  // 0 or greater means readers can pass; -1 is active writer.
    private int readWaiters = 0;                        // Readers waiting for writer to exit.
    private int writeWaiters = 0;                       // Writers waiting for writer lock.
    private ConditionVariable conditionVar;             // Condition variable.

    public ReaderWriterLock()
    {
        conditionVar = new ConditionVariable(syncRoot);
    }

    /// <summary>
    /// Gets a value indicating if a reader lock is held.
    /// </summary>
    public bool IsReaderLockHeld
    {
        get
        {
            lock ( syncRoot )
            {
                if ( i > 0 )
                    return true;
                return false;
            }
        }
    }

    /// <summary>
    /// Gets a value indicating if the writer lock is held.
    /// </summary>
    public bool IsWriterLockHeld
    {
        get
        {
            lock ( syncRoot )
            {
                if ( i < 0 )
                    return true;
                return false;
            }
        }
    }

    /// <summary>
    /// Aquires the writer lock.
    /// </summary>
    public void AcquireWriterLock()
    {
        lock ( syncRoot )
        {
            writeWaiters++;
            while ( i != 0 )
                conditionVar.Wait();      // Wait until existing writer frees the lock.
            writeWaiters--;
            i = -1;             // Thread has writer lock.
        }
    }

    /// <summary>
    /// Aquires a reader lock.
    /// </summary>
    public void AcquireReaderLock()
    {
        lock ( syncRoot )
        {
            readWaiters++;
            // Defer to a writer (one time only) if one is waiting to prevent writer starvation.
            if ( writeWaiters > 0 )
            {
                conditionVar.Pulse();
                Monitor.Wait(syncRoot);
            }
            while ( i < 0 )
                Monitor.Wait(syncRoot);
            readWaiters--;
            i++;
        }
    }

    /// <summary>
    /// Releases the writer lock.
    /// </summary>
    public void ReleaseWriterLock()
    {
        bool doPulse = false;
        lock ( syncRoot )
        {
            i = 0;
            // Decide if we pulse a writer or readers.
            if ( readWaiters > 0 )
            {
                Monitor.PulseAll(syncRoot); // If multiple readers waiting, pulse them all.
            }
            else
            {
                doPulse = true;
            }
        }
        if ( doPulse )
            conditionVar.Pulse();                     // Pulse one writer if one waiting.
    }

    /// <summary>
    /// Releases a reader lock.
    /// </summary>
    public void ReleaseReaderLock()
    {
        bool doPulse = false;
        lock ( syncRoot )
        {
            i--;
            if ( i == 0 )
                doPulse = true;
        }
        if ( doPulse )
            conditionVar.Pulse();                     // Pulse one writer if one waiting.
    }

    /// <summary>
    /// Condition Variable (CV) class.
    /// </summary>
    public class ConditionVariable
    {
        private readonly object syncLock = new object(); // Internal lock.
        private readonly object m;                       // The lock associated with this CV.

        public ConditionVariable(object m)
        {
            lock (syncLock)
            {
                this.m = m;
            }
        }

        public void Wait()
        {
            bool enter = false;
            try
            {
                lock (syncLock)
                {
                    Monitor.Exit(m);
                    enter = true;
                    Monitor.Wait(syncLock);
                }
            }
            finally
            {
                if (enter)
                    Monitor.Enter(m);
            }
        }

        public void Pulse()
        {
            lock (syncLock)
            {
                Monitor.Pulse(syncLock);
            }
        }

        public void PulseAll()
        {
            lock (syncLock)
            {
                Monitor.PulseAll(syncLock);
            }
        }

    }

} 

如果它很好,它也可能对其他人有帮助,因为Silverlight目前缺少读写器类型的锁。感谢。

3 个答案:

答案 0 :(得分:4)

我深入解释Vance Morrison's ReaderWriterLock(在.NET 3.5中成为ReaderWriterLockSlim)on my blog(降至x86级别)。这可能对您的设计有所帮助,特别是了解事情的确如何运作。

答案 1 :(得分:1)

您的IsReadorLockHeld和IsWriterLockHeld方法在概念层面都存在缺陷。虽然可以确定在给定时间点特定锁定是否被保持,但除非您继续持有锁定(在代码中不是这种情况),否则没有这些信息绝对没有任何安全措施。

这些方法更准确地命名为WasReadLockHeldInThePast和WasWriterLockHeldInThePast。一旦您将方法重命名为更准确地表示它们的作用,就会更清楚它们不是非常有用。

答案 2 :(得分:0)

这个类对我来说似乎更简单,并提供相同的功能。它的性能可能略低,因为它总是PulsesAll(),但逻辑理解起来要简单得多,而且我怀疑它的性能是否很好。

public sealed class ReaderWriterLock()
{
    private readonly object internalLock = new object();
    private int activeReaders = 0;
    private bool activeWriter = false;

    public void AcquireReaderLock()
    {
        lock (internalLock)
        {
            while (activeWriter)
                Monitor.Wait(internalLock);
            ++activeReaders;
        }
    }

    public void ReleaseReaderLock()
    {
        lock (internalLock)
        {
            // if activeReaders <= 0 do some error handling
            --activeReaders;
            Monitor.PulseAll(internalLock);
        }
    }

    public void AcquireWriterLock()
    {
        lock (internalLock)
        {
            // first wait for any writers to clear 
            // This assumes writers have a higher priority than readers
            // as it will force the readers to wait until all writers are done.
            // you can change the conditionals in here to change that behavior.
            while (activeWriter)
                Monitor.Wait(internalLock);

            // There are no more writers, set this to true to block further readers from acquiring the lock
            activeWriter = true;

            // Now wait till all readers have completed.
            while (activeReaders > 0)
                Monitor.Wait(internalLock);

            // The writer now has the lock
        }
    }

    public void ReleaseWriterLock()
    {
        lock (internalLock)
        {
            // if activeWriter != true handle the error
            activeWriter = false;
            Monitor.PulseAll(internalLock);
        }
    }
}