Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
665 views
in Technique[技术] by (71.8m points)

multithreading - What are atomic operations for newbies?

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

For a newbie?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"

"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

Here, each upsert is atomic: the first one left count at 2, the second one left it at 3. Everything works.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...