我不久前接受了一个简单的生产者/消费者问题的测试。
我提出了一个有效的解决方案,但我想知道这是否可以改进?
public static class Program
{
public static void Main(params string[] args)
{
var booleanContainer = new BooleanContainer();
var random = new Random();
var booleanContainerMonitor = new BooleanContainerMonitor(booleanContainer);
for (var i = 0; i < 50; i++)
{
var isProducer = random.Next(2) == 1;
if (isProducer)
{
for (var j = 0; j < 4; j++)
{
Task.Run(() => booleanContainerMonitor.SetToFalse());
}
}
else
{
for (var j = 0; j < 4; j++)
{
Task.Run(() => booleanContainerMonitor.SetToTrue());
}
}
}
Console.ReadKey();
}
}
public class BooleanContainerMonitor
{
private readonly BooleanContainer _booleanContainer;
private readonly object _syncRoot = new object();
public BooleanContainerMonitor(BooleanContainer booleanContainer)
{
this._booleanContainer = booleanContainer;
}
public void SetToTrue()
{
lock (_syncRoot)
{
while (_booleanContainer.IsTrue())
{
Monitor.Wait(_syncRoot);
}
_booleanContainer.Set(true);
Monitor.Pulse(_syncRoot);
}
}
public void SetToFalse()
{
lock (_syncRoot)
{
while (!_booleanContainer.IsTrue())
{
Monitor.Wait(_syncRoot);
}
_booleanContainer.Set(false);
Monitor.Pulse(_syncRoot);
}
}
}
public class BooleanContainer
{
private bool _value = true;
public bool IsTrue()
{
return _value;
}
public void Set(bool value)
{
// Something is fishy if _value is true
if (value == _value)
{
throw new InvalidProgramException();
}
_value = value;
Console.WriteLine(_value ? "True" : "False");
}
}
这个想法是为了防止死锁: - Producer将嵌入的BooleanContainer设置为False - Consumer将嵌入的BooleanContainer设置为True 并且前一个值与我们试图设置的值相反。
有什么可以改善的吗? 似乎在运行这个程序时,它有点笨拙和阻塞。