制作实现读\写方法的同步数组

我有一个包含以下字段的类:消息数组和当前消息数以及读\写方法。


当有人写入时,它会将消息放入数组并将当前消息数增加一个,当有人试图读取它时,它会先减少

当前消息数然后返回最后一条消息。


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


我做了这个实现的类:


   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

    }

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


海绵宝宝撒
浏览 61回答 1
1回答

慕侠2389804

您可以使用以下方法使代码更简单Monitor:class SynchronizedDATAStructure : DATAStructure{&nbsp; &nbsp; private readonly object syncRoot = new object();&nbsp; &nbsp; public int MessageCount { get; private set; }&nbsp; &nbsp; public override void Write(Message msg)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; lock (syncRoot)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; base.Write(msg);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; MessageCount++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Monitor.Pulse(syncRoot);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public override Message Read()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; lock (syncRoot)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; while (MessageCount <= 0)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Monitor.Wait(syncRoot);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; MessageCount--;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return base.Read();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP