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
428 views
in Technique[技术] by (71.8m points)

c# - Is variable assignment and reading atomic operation?

I was unable to find any reference to this in the documentations...

Is assigning to a double (or any other simple type, including boolean) an atomic operation viewed from the perspective of threads?

double value = 0;

public void First() {
 while(true) {
  value = (new Random()).NextDouble();
 }
}

public void Second() {
 while(true) {
  Console.WriteLine(value);
 }
}

In this code sample, first method is called in one thread, and the second in another. Can the second method get a messed up value if it gets its execution during assignment to the variable in another thread?

I don't care if I receive the old value, it's only important to receive a valid value (not one where 2 out of 8 bytes are set). I know it's a stupid question, but I want to be sure, cause I don't know how CLR actually sets the variables.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

To answer your question, no. Assignments to doubles are not guarenteed to be atomic. The docs are available here. Basically, <= 32-bit built-in types are atomic, >= 64-bit types aren't. For atomic operations on 64bit types, you can use the methods on System.Threading.Interlocked


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

...