我有一个具有以下字段的类:消息数组和当前消息数以及方法read \ write。
当某人写入时,它将消息放入数组中,并将当前消息数增加一,而当某人尝试读取时,则将其减少
当前消息数,然后返回最后一条消息。
我想使此类进行同步,因此它将允许线程从他那里进行写入和读取(当数组为空时,我希望线程将等待直到将要读取的内容)并防止数据争用。
我做了这个实现的类:
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。
答案 0 :(得分:1)
您可以使用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();
}
}
}