Bri*_*dia 4 concurrency multithreading synchronization operating-system atomic
我是操作系统的新手,在Stackoverflow上找到的每个答案都很复杂,以至于我无法理解。有人可以解释什么是
原子操作
对于新手?
我的理解:我的理解是atomic operation意味着它可以完全执行而不会中断吗?即,这是没有中断范围的阻塞操作?
是的,是的。“凌动”来自希腊语“ATOMOS” =“不能切削”,并在这个意义上“不可分割的最小单位”很长一段时间已经被使用(直到物理学家发现,其实有有东西比原子小)。在并发编程中,这意味着在此期间不会进行上下文切换-不会影响原子命令的执行。
例如:网络民意测验,开放式问题,但我们想总结出多少人给出相同的答案。您有一个数据库表,您可以在其中插入答案和该答案的计数。代码很简单:
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
Run Code Online (Sandbox Code Playgroud)
还是?查看多个人同时执行操作会发生什么情况:
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"
Run Code Online (Sandbox Code Playgroud)
即使有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
Run Code Online (Sandbox Code Playgroud)
在这里,每个ups是原子的:第一个保留为2,第二个保留为3。一切正常。
请注意,“原子”是上下文相关的:在这种情况下,关于数据库中答案表的操作,upsert操作仅需要是原子的;只要计算机不影响upsert尝试执行的结果(或受其影响),计算机就可以自由执行其他操作。