一个写作和许多阅读线程的小数线安全
我想了解有关某个问题的确切行为的更多信息,以便我可以决定是否使用 lock
(使用绩效含义)。
Given the following pseudo code:
class Thread1
{
public decimal TotalValue {get; private set;}
private decimal StockAmount;
private decimal OldPrice;
public async Task GetStockPrices(string fictionalAsset)
{
while (true)
{
decimal totalCopy = TotalValue;
totalCopy -= (StockAmount * OldPrice);
OldPrice = StockPrices.GetValue(fictionalAsset);
totalCopy += (StockAmount * OldPrice);
TotalValue = totalCopy;
}
}
}
Let's assume, that Thread1
is the only Thread ever modifying TotalValue
.所有其他线程(无论他们的计数如何)都只会从中读取。
可以肯定的是,读取线程访问 totalValue
时, totalValue = TotalCopy;
。
它的含义是什么?读取线程“ Just”会收到 totalValue
(OK)的旧版本,还是可能会有另一个不需要的结果(例如0或任何其他数字 - 致命)。是否还有其他含义,例如性能。还是其他线程更新的时间?
I would expect the above code to be more performant than
lock (TotalLock)
{
TotalValue = totalCopy;
}
especially since reading threads could be many and very frequently, effectively locking up the value.
如果需要锁定,则如何提供锁? (我想像FIFO或随机) - 写线程可以分配优先级吗? (可以检查变量是否已锁定的东西,如果是的,请等待)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以通过在 TotalValue 属性。 tuple-1“ rel =” nofollow noreferrer“>
tuple< t>
包装器类似:volatile
关键字可确保编译器不会以不会影响单个单一的代码优化代码 - 线程程序,但可能会导致某些线程在多线程程序中失去对字段的可见性。我的期望是,此实现应比使用
锁定
的速度要快一些,尤其是在get
的情况下,set
s s。否则,如果该属性的更新频率比阅读的频率更高,则垃圾收集大量短寿命tuple<
实例的成本可能会消除避免同步成本的所有好处。You could implement the
TotalValue
property in a lock-free fashion, by boxing the decimals inTuple<T>
wrappers like this:The
volatile
keyword ensures that the compiler will not optimize the code in a way that would not affect a single-thread program, but could cause some threads to lose visibility of the field in a multithreaded program.My expectation is that this implementation should be slightly faster than using a
lock
, especially if theget
s greatly outnumber theset
s. Otherwise, if the property is updated more frequently than it is read, the cost of garbage-collecting a large number of short-livedTuple<decimal>
instances will probably negate all the benefits of avoiding the synchronization cost.