我有一个包含字段的类:消息数组和当前消息数以及读取/写入方法。
当有人写时,它会将消息放入数组并将当前消息数增加1,并且当有人尝试首先读取消息时减少 当前消息数,然后返回最后一条消息。
我想让这个类成为同步所以它将允许线程写入和读取(当数组为空时我希望线程将等到将要读取的东西)并防止数据争用。
我做了这个实现的类:
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
}
当线程开始写入\ 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();
}
}
}