我有一个包含以下字段的类:消息数组和当前消息数以及读\写方法。当有人写入时,它会将消息放入数组并将当前消息数增加一个,当有人试图读取它时,它会先减少当前消息数然后返回最后一条消息。我想让这个类同步,这样它就允许线程从他那里写入和读取(当数组为空时,我希望线程会等到有东西可以读取)并防止数据竞争。我做了这个实现的类: 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。
1 回答
慕侠2389804
TA贡献1719条经验 获得超6个赞
您可以使用以下方法使代码更简单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();
}
}
}
- 1 回答
- 0 关注
- 60 浏览
添加回答
举报
0/150
提交
取消