什么是新手的原子操作?

时间:2018-09-06 04:46:13

标签: multithreading concurrency operating-system synchronization atomic

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

  

原子操作

对于新手?

我的理解:我的理解是atomic operation意味着它可以完全执行而不会不受干扰吗?也就是说,这是阻止操作,没有中断范围?

1 个答案:

答案 0 :(得分:2)

是的,是的。 “ Atom”来自希腊语“ atomos” =“ uncuttable”,并且在“不可分割的最小单位”的意义上使用了很长时间(直到物理学家发现,实际上, 比原子更重要的事物)。在并发编程中,这意味着在此期间不会进行上下文切换-不会影响原子命令的执行。

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

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"

即使2个人投票,“火腿和鸡蛋”也只跳了1个!这显然不是我们想要的。为了简便起见,如果只是原子操作“增加它的存在或创建一个新记录” ...为简便起见,我们称其为“ upsert”(用于“ update或insert”)

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

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

请注意,“原子”是上下文相关的:在这种情况下,关于数据库答案表中的操作,upsert操作仅需要是原子的;只要计算机不影响upsert尝试执行的结果(或受其影响),计算机就可以自由地执行其他操作。

相关问题