1

我没有写任何与STM(软件事务内存)相关的东西,只是阅读了网上的信息。所以这里只是一个虚构的例子

假设我们有一个 FIFO 缓冲区,其中包含最大允许项。因此,我们填充数组直到达到最大项目数,并在没有更多项目时移动它。使用传统方法,我不仅会锁定实际的移位和追加,还会锁定检查是否达到最大值的条件读取。我必须这样做,否则两个线程可以模拟地决定剩下的唯一项目是为他们准备的。所以我这里有一种与写冲突没有直接关系的逻辑锁。

使用 STM,我想两个线程都可以决定剩下的项目并尝试填充最后一个项目。但是正确性得以保留,因为在检测到另一个线程修改了相同的内存之后,在一个线程(或两个线程)中触发了回滚。乐观的情况是说某个时候一个线程最终会增加元素的数量,而另一个线程最终会转到另一个分支(FIFO 移位)。但是,如果双方都注意到最后一个项目被留下并试图填充它,我也看到了一个无限循环的可能性。

那么在写STM相关的软件时还需要加“逻辑”锁吗?

4

1 回答 1

1

You should not need any logical locking - certainly not for this scenario.

It is not possible for two threads to "keep noticing" that one slot is still free. The only way for one thread to get rolled back is if another thread has successfully committed - meaning that the last slot has been filled.

Deadlock is guaranteed to never happen because locking happens only during the commit phase, and by then we know exactly what to lock, and can take locks in a consistent order. Livelock is guaranteed to never happen because one transaction can only ever rolled back because another transaction committed successfully. It is therefore impossible for two transactions to block each other forever.

What is theoretically possible is starvation. One particularly unlucky transaction could be rolled back infinity times. This can only happen if an infinite number of conflicting transactions are committing successfully. So globally, the system must make progress, but locally, one specific transaction can get stuck.

In practice, the only way this is likely to happen is if you're running an infinite stream of short transactions, and then you start one very long transaction which thus never gets to complete.

于 2013-07-06T10:28:02.900 回答