Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 679
AStrangerGuy Avatar asked Apr 29 '10 10:04

AStrangerGuy


People also ask

Is assignment an atomic operation?

Yes. Assignment of premitive types and reference types are atomic. Read the ECMA C# language specification. Actually, that's not entirely true, only assignments to reference types, bool, char, byte, sbyte, short, ushort, uint, int and float are atomic.

Is Python variable assignment Atomic?

So the assignment is a single python bytecode (instruction 2), which is atomic in CPython since it executes one bytecode at a time. += corresponds to 4 instructions, which is not atomic.

Is variable assignment atomic Java?

Variables shared between multiple threads (e.g., instance variables of objects) have atomic assignment guaranteed by the Java language specification for all data types except for long s and double s.

What is variable and assignment?

A variable is a string of characters and numbers associated with a piece of information. The assignment operator, denoted by the “=” symbol, is the operator that is used to assign values to variables in Python. The line x=1 takes the known value, 1, and assigns that value to the variable with name “x”.


1 Answers

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

like image 162
thecoop Avatar answered Sep 19 '22 17:09

thecoop