Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is reading from a int[] array while another thread updates that int[] array safe?

Tags:

c#

Two threads. The first furiously reading elements from the array. The second is equally furious in updating elements by reading them and incrementing them by an arbitrary amount.

Is this safe? can anything go wrong in this situation? I don't mind that the reading thread reads an 'old' value while the updating thread is still in the process of updating. I just want to make sure the reader doesn't ever read a number that was not written and also that an exception cannot occur.

like image 484
Weyland Yutani Avatar asked Feb 20 '26 15:02

Weyland Yutani


1 Answers

An int update is atomic on all cpu architectures that can execute managed code. In other words, you won't read a value that has just a single byte modified by the writing thread. Value type values larger than 32-bit, like long and double are not guaranteed atomic. Object references are also always atomic.

like image 113
Hans Passant Avatar answered Feb 22 '26 04:02

Hans Passant