什么是新手的原子操作? [英] What are atomic operations for newbies?
问题描述
我是操作系统的新手,在Stackoverflow上找到的每个答案都非常复杂,以至于我无法理解.有人可以解释什么是
I am a newbie to operating systems and every answer I've found on Stackoverflow is so complicated that I am unable to understand. Can someone provide an explanation for what is an
原子操作
对于新手?
我的理解:我的理解是atomic operation
表示它可以完全执行而不会不间断吗?也就是说,这是阻止操作,没有中断范围?
My understanding: My understanding is that atomic operation
means it executes fully with no interruption? Ie, it is a blocking operation with no scope of interruption?
推荐答案
是的. 原子"来自希腊语"atomos" =不可切割",并且在不可分割的最小单位"的意义上使用了很长时间(直到物理学家发现,实际上, 比原子更重要的事物).在并发编程中,这意味着在此期间不会进行上下文切换-不会影响原子命令的执行.
Pretty much, yes. "Atom" comes from greek "atomos" = "uncuttable", and has been used in the sense "indivisible smallest unit" for a very long time (till physicists found that, in fact, there are smaller things than atoms). In concurrent programming, it means that there will be no context switch during it - nothing can affect the execution of atomic command.
一个例子:网络民意测验,开放式问题,但我们想总结一下有多少人给出相同的答案.您有一个数据库表,您可以在其中插入答案和该答案的计数.代码很简单:
An example: a web poll, open-ended questions, but we want to sum up how many people give the same answer. You have a database table where you insert answers and counts of that answer. The code is straightforward:
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
是吗?看看当多个人同时做时会发生什么:
Or is it? See what happens when multiple people do it at the same time:
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")
"Ham and eggs" only jumped by 1 even though 2 people voted for it! This is clearly not what we wanted. If only there was an atomic operation "increment if it exists or make a new record"... for brevity, let's call it "upsert" (for "update or insert")
user A answers "ham and eggs" user B answers "ham and eggs"
upsert by incrementing count upsert by incrementing count
这里,每个upsert都是原子的:第一个左数为2,第二个左数为3.一切正常.
Here, each upsert is atomic: the first one left count at 2, the second one left it at 3. Everything works.
请注意,原子"是上下文相关的:在这种情况下,关于数据库答案表中的操作,upsert操作仅需要是原子的;只要计算机不影响upsert尝试执行的结果(或受其影响),计算机就可以自由地执行其他操作.
Note that "atomic" is contextual: in this case, the upsert operation only needs to be atomic with respect to operations on the answers table in the database; the computer can be free to do other things as long as they don't affect (or are affected by) the result of what upsert is trying to do.
这篇关于什么是新手的原子操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!