我没有提供完整的列表,因为下面的代码对于那些熟悉破坏者的人来说已经足够了。问题是调用Next
和Publish
方法是否是线程安全的。在下面的示例之间,正确的示例是什么?注意Attach
可以同时从不同的线程调用。我有多个消费者。
示例 1。锁定一切:
private object attachLock = new object();
// can be called from parallel threads
public void Attach(OrdersExecutor oe)
{
lock (attachLock)
{
long sequenceNo = ringBuffer.Next();
ringBuffer[sequenceNo].Value = oe;
ringBuffer.Publish(sequenceNo);
}
}
例 2。锁定下一个:
private object attachLock = new object();
// can be called from parallel threads
public void Attach(OrdersExecutor oe)
{
long sequenceNo;
lock (attachLock)
{
sequenceNo = ringBuffer.Next();
}
ringBuffer[sequenceNo].Value = oe;
ringBuffer.Publish(sequenceNo);
}
例 3。无锁
private object attachLock = new object();
// can be called from parallel threads
public void Attach(OrdersExecutor oe)
{
long sequenceNo = ringBuffer.Next();
ringBuffer[sequenceNo].Value = oe;
ringBuffer.Publish(sequenceNo);
}