什么是新手原子操作?

What are atomic operations for newbies?

我是操作系统的新手,我在 Whosebug 上找到的每一个答案都太复杂了,我无法理解。有人可以解释什么是

atomic operation

对于新手?

我的理解:我的理解是atomic operation意味着它完全执行没有中断?即,它是一个阻塞操作,没有中断范围?

差不多,是的。 "Atom" 来自希腊语 "atomos" = "uncuttable",并且在 "indivisible smallest unit" 的意义上使用了很长时间(直到物理学家发现,事实上 比原子更小的东西)。在并发编程中,这意味着在此期间不会有上下文切换——没有什么可以影响原子命令的执行。

举个例子:网络投票,开放式问题,但是我们想总结一下有多少人给出了相同的答案。您有一个数据库 table,您可以在其中插入答案和该答案的计数。代码很简单:

get the row for the given answer
if the row didn't exist:
  create the row with answer and count 1
else:
  increment count
  update the row with new count

或者是吗?看看多人同时做会发生什么:

user A answers "ham and eggs"       user B answers "ham and eggs"
get the row: count is 1             get the row: count is 1
okay, we're updating!               okay, we're updating!
count is now 2                      count is now 2
store 2 for "ham and eggs"          store 2 for "ham and eggs"

"Ham and eggs" 虽然有 2 人投票,但只跳了 1!这显然不是我们想要的。如果只有一个原子操作 "increment if it exists or make a new record"...

user A answers "ham and eggs"       user B answers "ham and eggs"
upsert by incrementing count        upsert by incrementing count

在这里,每个 upsert 都是原子的:第一个保留计数为 2,第二个保留计数为 3。一切正常。

请注意 "atomic" 是上下文相关的:在这种情况下,upsert 操作只需要相对于数据库中答案 table 的操作是原子的;计算机可以自由地做其他事情,只要它们不影响(或受其影响)upsert 尝试做的结果。