制作实现 read\write 方法的同步数组

making synchronized array that implements read\write methods

我有一个 class,其中包含以下字段:消息数组和当前消息数以及方法 read\write。

当有人写入时,它会将消息放入数组并将当前消息数加一,当有人尝试首先阅读它时减少
当前消息数,然后 returns 最后一条消息。

我想让这个 class 同步,这样它就可以让线程从他那里写入和读取(当数组为空时,我希望线程会等到有东西可以读取)并防止数据竞争。

我做了这个class实现了:

   class SynchronizedDATAStructure : DATAStructure
{
    private Mutex mutexR = new Mutex();
    private Mutex mutexW = new Mutex();
    private Semaphore semaphore = new Semaphore(0, int.MaxValue);
    private Semaphore semaphore2 = new Semaphore(1, 1);

    public override void Write(Message msg)
    {
        mutexW.WaitOne(); // allows only one thread each time to write
        semaphore2.WaitOne(); // checks if nobody is reading 
        base.Write(msg); // writing
        semaphore.Release(); // counts number of messages
        semaphore2.Release(); // finish to write
        mutexW.ReleaseMutex(); // finish the function
    }

    public override Message Read()
    {
        mutexR.WaitOne(); // allows only one thread each time to read
        semaphore.WaitOne();  // checks if there  are messages 
        semaphore2.WaitOne(); // checks if nobody is writing 
        Message msg1 = base.Read(); // reading
        semaphore2.Release(); // finish to read
        mutexR.ReleaseMutex(); // finish the function
        return msg1; // returns the messge
    }

当线程开始 write\read 时,当线程尝试从空数组中读取时我得到了 outOfBounds。

您可以使用 Monitor:

使代码更简单
class SynchronizedDATAStructure : DATAStructure
{
    private readonly object syncRoot = new object();

    public int MessageCount { get; private set; }

    public override void Write(Message msg)
    {
        lock (syncRoot)
        {
            base.Write(msg);
            MessageCount++;

            Monitor.Pulse(syncRoot);
        }
    }

    public override Message Read()
    {
        lock (syncRoot)
        {
            while (MessageCount <= 0)
            {
                Monitor.Wait(syncRoot);
            }

            MessageCount--;
            return base.Read();
        }
    }
}