1

I am writing a read-write synchronization class, and would like some advice on what I to do next. For some reason, it sometimes allows a Read to happen in the middle of a Write, and I cannot find the reason.

This is what I want from this class:

  • Reads not allowed at the same time as writes.
  • Multiples reads can happen at the same time.
  • Only one write can happen at a time.
  • When a write is needed, all already executing reads continue, no new reads are allowed, when all reads finish the write executes.

I know that .Net framework has a class to do this... but what I want is to understand and to reproduce something like that. I'm not reinventing the wheel, I am trying to understand it by making my own wheel... happens that my wheel is kinda squared a bit.

What I have currently is this:

public class ReadWriteSync
{
    private ManualResetEvent read = new ManualResetEvent(true);
    private volatile int readingBlocks = 0;
    private AutoResetEvent write = new AutoResetEvent(true);
    private object locker = new object();

    public IDisposable ReadLock()
    {
        lock (this.locker)
        {
            this.write.Reset();
            Interlocked.Increment(ref this.readingBlocks);
            this.read.WaitOne();
        }

        return new Disposer(() =>
        {
            if (Interlocked.Decrement(ref this.readingBlocks) == 0)
                this.write.Set();
        });
    }

    public IDisposable WriteLock()
    {
        lock (this.locker)
        {
            this.read.Reset();
            this.write.WaitOne();
        }

        return new Disposer(() =>
        {
            this.read.Set();
            if (this.readingBlocks == 0)
                this.write.Set();
        });
    }

    class Disposer : IDisposable
    {
        Action disposer;
        public Disposer(Action disposer) { this.disposer = disposer; }
        public void Dispose() { this.disposer(); }
    }
}

This is my test program... when something goes wrong it prints the lines in red.

class Program
{
    static ReadWriteSync sync = new ReadWriteSync();

    static void Main(string[] args)
    {
        Console.BackgroundColor = ConsoleColor.DarkGray;
        Console.ForegroundColor = ConsoleColor.Gray;
        Console.Clear();

        Task readTask1 = new Task(() => DoReads("A", 20));
        Task readTask2 = new Task(() => DoReads("B", 30));
        Task readTask3 = new Task(() => DoReads("C", 40));
        Task readTask4 = new Task(() => DoReads("D", 50));

        Task writeTask1 = new Task(() => DoWrites("E", 500));
        Task writeTask2 = new Task(() => DoWrites("F", 200));

        readTask1.Start();
        readTask2.Start();
        readTask3.Start();
        readTask4.Start();

        writeTask1.Start();
        writeTask2.Start();

        Task.WaitAll(
            readTask1, readTask2, readTask3, readTask4,
            writeTask1, writeTask2);
    }

    static volatile bool reading;
    static volatile bool writing;

    static void DoWrites(string name, int interval)
    {
        for (int i = 1; i < int.MaxValue; i += 2)
        {
            using (sync.WriteLock())
            {
                Console.ForegroundColor = (writing || reading) ? ConsoleColor.Red : ConsoleColor.Gray;
                writing = true;
                Console.WriteLine("WRITE {1}-{0} BEGIN", i, name);
                Thread.Sleep(interval);
                Console.WriteLine("WRITE {1}-{0} END", i, name);
                writing = false;
            }

            Thread.Sleep(interval);
        }
    }

    static void DoReads(string name, int interval)
    {
        for (int i = 0; i < int.MaxValue; i += 2)
        {
            using (sync.ReadLock())
            {
                Console.ForegroundColor = (writing) ? ConsoleColor.Red : ConsoleColor.Gray;
                reading = true;
                Console.WriteLine("READ {1}-{0} BEGIN", i, name);
                Thread.Sleep(interval * 3);
                Console.WriteLine("READ {1}-{0} END", i, name);
                reading = false;
            }

            Thread.Sleep(interval);
        }
    }
}

What is wrong with all this... any advice on how to do it correctly?

4

1 回答 1

3

我看到的主要问题是您试图使重置事件既包含读/写的含义,又包含对它们当前状态的处理,而没有以一致的方式进行同步。

这是一个示例,说明不一致的同步如何在您的特定代码中影响您。

  • Awrite正在处理, Aread正在进来。
  • read获取锁
  • write设置ManualResetEvent read(MRE)
  • 检查当前write读取计数,发现 0
  • read重置writeAutoResetEvent (ARE )
  • 增加read读取计数
  • 发现其readMRE 已设置并开始读取

到目前为止一切都很好,但write还没有完成......

  • write进来并获得锁
  • 第二个write重置readMRE
  • 第一个write通过设置writeARE完成
  • 第二个write发现它的 ARE 已设置并开始写入

在考虑多个线程时,除非您处于某种锁中,否则您必须认为所有其他数据都在剧烈波动并且不可信。

一个简单的实现可能会将排队逻辑从状态逻辑中分离出来并适当地同步。

    public class ReadWrite
    {
        private static int readerCount = 0;
        private static int writerCount = 0;
        private int pendingReaderCount = 0;
        private int pendingWriterCount = 0;
        private readonly object decision = new object();

        private class WakeLock:IDisposable
        {
            private readonly object wakeLock;
            public WakeLock(object wakeLock) { this.wakeLock = wakeLock; }
            public virtual void Dispose() { lock(this.wakeLock) Monitor.PulseAll(this.wakeLock); }
        }
        private class ReadLock:WakeLock
        {
            public ReadLock(object wakeLock) : base(wakeLock) { Interlocked.Increment(ref readerCount); }
            public override void Dispose()
            {
                Interlocked.Decrement(ref readerCount);
                base.Dispose();
            }
        }            
        private class WriteLock:WakeLock
        {
            public WriteLock(object wakeLock) : base(wakeLock) { Interlocked.Increment(ref writerCount); }
            public override void Dispose()
            {
                Interlocked.Decrement(ref writerCount);
                base.Dispose();
            }
        }

        public IDisposable TakeReadLock()
        {
            lock(decision)
            {
                pendingReaderCount++;
                while (pendingWriterCount > 0 || Thread.VolatileRead(ref writerCount) > 0)
                    Monitor.Wait(decision);
                pendingReaderCount--;
                return new ReadLock(this.decision);
            }
        }

        public IDisposable TakeWriteLock()
        {
            lock(decision)
            {
                pendingWriterCount++;
                while (Thread.VolatileRead(ref readerCount) > 0 || Thread.VolatileRead(ref writerCount) > 0)
                    Monitor.Wait(decision);
                pendingWriterCount--;
                return new WriteLock(this.decision);
            }
        }
    }
于 2014-01-27T21:23:35.933 回答