Betamoo
Betamoo

Reputation: 15860

Thread safety in C# arrays

Does having 2 different threads :

is thread safe or not?
(And I mean here without locking reading nor writing)

Upvotes: 13

Views: 4210

Answers (3)

Stewart
Stewart

Reputation: 4028

I'm not sure this is guaranteed to be safe. Imagine you have byte[]. Those bytes are closely packed in memory. Now, if you modify those bytes the compiler may coalesce some of the writes to perform word (32-bit) sized read modify write operations. On some CPUs, ARM for example, this is the only kind of memory modifying instruction the compiler has. This is especially handy if you are modifying more than one byte at a time. The CPU can do the same thing too. It can also reorder stuff without you knowing about it. In the face of that kind of optimization it is possible for a thread reading adjacent memory to see partial modifications. You don't see this kind of effect normally because the heap allocator is nice to you and always gives you memory which is at least word aligned.

Upvotes: 7

TkTech
TkTech

Reputation: 4976

Long story short: Yes. As long as its to two different locations, its a safe operation.

There was a discussion about this awhile ago, it has some useful information if you're curious.

Upvotes: 6

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391336

This particular case is safe, yes.

Reading and writing to different parts of an array does not interfere with the other operations.

However, reading and writing to the same location can give you problems, depending on the type of element, and the size of the elements.

Upvotes: 8

Related Questions